babylon.viewer.max.js 6.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. if(typeof exports === 'object' && typeof module === 'object') {
  4. module.exports = factory();
  5. } else if(typeof define === 'function' && define.amd) {
  6. define("babylonjs-viewer", amdDependencies, factory);
  7. } else if(typeof exports === 'object') {
  8. exports["babylonjs-viewer"] = factory();
  9. } else {
  10. root["BabylonViewer"] = factory();
  11. }
  12. })(this, function() {
  13. var BabylonViewer =
  14. /******/ (function(modules) { // webpackBootstrap
  15. /******/ // The module cache
  16. /******/ var installedModules = {};
  17. /******/
  18. /******/ // The require function
  19. /******/ function __webpack_require__(moduleId) {
  20. /******/
  21. /******/ // Check if module is in cache
  22. /******/ if(installedModules[moduleId]) {
  23. /******/ return installedModules[moduleId].exports;
  24. /******/ }
  25. /******/ // Create a new module (and put it into the cache)
  26. /******/ var module = installedModules[moduleId] = {
  27. /******/ i: moduleId,
  28. /******/ l: false,
  29. /******/ exports: {}
  30. /******/ };
  31. /******/
  32. /******/ // Execute the module function
  33. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  34. /******/
  35. /******/ // Flag the module as loaded
  36. /******/ module.l = true;
  37. /******/
  38. /******/ // Return the exports of the module
  39. /******/ return module.exports;
  40. /******/ }
  41. /******/
  42. /******/
  43. /******/ // expose the modules object (__webpack_modules__)
  44. /******/ __webpack_require__.m = modules;
  45. /******/
  46. /******/ // expose the module cache
  47. /******/ __webpack_require__.c = installedModules;
  48. /******/
  49. /******/ // define getter function for harmony exports
  50. /******/ __webpack_require__.d = function(exports, name, getter) {
  51. /******/ if(!__webpack_require__.o(exports, name)) {
  52. /******/ Object.defineProperty(exports, name, {
  53. /******/ configurable: false,
  54. /******/ enumerable: true,
  55. /******/ get: getter
  56. /******/ });
  57. /******/ }
  58. /******/ };
  59. /******/
  60. /******/ // getDefaultExport function for compatibility with non-harmony modules
  61. /******/ __webpack_require__.n = function(module) {
  62. /******/ var getter = module && module.__esModule ?
  63. /******/ function getDefault() { return module['default']; } :
  64. /******/ function getModuleExports() { return module; };
  65. /******/ __webpack_require__.d(getter, 'a', getter);
  66. /******/ return getter;
  67. /******/ };
  68. /******/
  69. /******/ // Object.prototype.hasOwnProperty.call
  70. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  71. /******/
  72. /******/ // __webpack_public_path__
  73. /******/ __webpack_require__.p = "";
  74. /******/
  75. /******/ // Load entry module and return exports
  76. /******/ return __webpack_require__(__webpack_require__.s = 17);
  77. /******/ })
  78. /************************************************************************/
  79. /******/ ([
  80. /* 0 */
  81. /***/ (function(module, exports, __webpack_require__) {
  82. /* WEBPACK VAR INJECTION */(function(global) {
  83. (function universalModuleDefinition(root, factory) {
  84. var amdDependencies = [];
  85. var CANNON = root.CANNON || this.CANNON;
  86. var OIMO = root.OIMO || this.OIMO;
  87. var earcut = root.earcut || this.earcut;
  88. if(true) {
  89. try { CANNON = CANNON || __webpack_require__(20); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(21); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(22); } catch(e) {}
  92. module.exports = factory(CANNON,OIMO,earcut);
  93. } else if(typeof define === 'function' && define.amd) {
  94. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  95. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  96. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  97. define("babylonjs", amdDependencies, factory);
  98. } else if(typeof exports === 'object') {
  99. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  100. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  101. try { earcut = earcut || require("earcut"); } catch(e) {}
  102. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  103. } else {
  104. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  105. }
  106. })(this, function(CANNON,OIMO,earcut) {
  107. CANNON = CANNON || this.CANNON;
  108. OIMO = OIMO || this.OIMO;
  109. earcut = earcut || this.earcut;
  110. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  111. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. effect._bonesComputationForcedToCPU = true;
  183. var scene = this._mesh.getScene();
  184. for (var index = 0; index < scene.meshes.length; index++) {
  185. var otherMesh = scene.meshes[index];
  186. if (!otherMesh.material) {
  187. continue;
  188. }
  189. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  190. continue;
  191. }
  192. if (otherMesh.material.getEffect() === effect) {
  193. otherMesh.computeBonesUsingShaders = false;
  194. }
  195. else if (otherMesh.subMeshes) {
  196. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  197. var subMesh = _a[_i];
  198. var subMeshEffect = subMesh.effect;
  199. if (subMeshEffect === effect) {
  200. otherMesh.computeBonesUsingShaders = false;
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. }
  207. else {
  208. var currentFallbacks = this._defines[this._currentRank];
  209. if (currentFallbacks) {
  210. for (var index = 0; index < currentFallbacks.length; index++) {
  211. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  212. }
  213. }
  214. this._currentRank++;
  215. }
  216. return currentDefines;
  217. };
  218. return EffectFallbacks;
  219. }());
  220. BABYLON.EffectFallbacks = EffectFallbacks;
  221. /**
  222. * Options to be used when creating an effect.
  223. */
  224. var EffectCreationOptions = /** @class */ (function () {
  225. function EffectCreationOptions() {
  226. }
  227. return EffectCreationOptions;
  228. }());
  229. BABYLON.EffectCreationOptions = EffectCreationOptions;
  230. /**
  231. * Effect containing vertex and fragment shader that can be executed on an object.
  232. */
  233. var Effect = /** @class */ (function () {
  234. /**
  235. * Instantiates an effect.
  236. * An effect can be used to create/manage/execute vertex and fragment shaders.
  237. * @param baseName Name of the effect.
  238. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  239. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  240. * @param samplers List of sampler variables that will be passed to the shader.
  241. * @param engine Engine to be used to render the effect
  242. * @param defines Define statements to be added to the shader.
  243. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  244. * @param onCompiled Callback that will be called when the shader is compiled.
  245. * @param onError Callback that will be called if an error occurs during shader compilation.
  246. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  247. */
  248. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  249. if (samplers === void 0) { samplers = null; }
  250. if (defines === void 0) { defines = null; }
  251. if (fallbacks === void 0) { fallbacks = null; }
  252. if (onCompiled === void 0) { onCompiled = null; }
  253. if (onError === void 0) { onError = null; }
  254. var _this = this;
  255. /**
  256. * Unique ID of the effect.
  257. */
  258. this.uniqueId = 0;
  259. /**
  260. * Observable that will be called when the shader is compiled.
  261. */
  262. this.onCompileObservable = new BABYLON.Observable();
  263. /**
  264. * Observable that will be called if an error occurs during shader compilation.
  265. */
  266. this.onErrorObservable = new BABYLON.Observable();
  267. /**
  268. * Observable that will be called when effect is bound.
  269. */
  270. this.onBindObservable = new BABYLON.Observable();
  271. /** @hidden */
  272. this._bonesComputationForcedToCPU = false;
  273. this._uniformBuffersNames = {};
  274. this._isReady = false;
  275. this._compilationError = "";
  276. this.name = baseName;
  277. if (attributesNamesOrOptions.attributes) {
  278. var options = attributesNamesOrOptions;
  279. this._engine = uniformsNamesOrEngine;
  280. this._attributesNames = options.attributes;
  281. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  282. this._samplers = options.samplers.slice();
  283. this.defines = options.defines;
  284. this.onError = options.onError;
  285. this.onCompiled = options.onCompiled;
  286. this._fallbacks = options.fallbacks;
  287. this._indexParameters = options.indexParameters;
  288. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  289. if (options.uniformBuffersNames) {
  290. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  291. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  292. }
  293. }
  294. }
  295. else {
  296. this._engine = engine;
  297. this.defines = defines;
  298. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  299. this._samplers = samplers ? samplers.slice() : [];
  300. this._attributesNames = attributesNamesOrOptions;
  301. this.onError = onError;
  302. this.onCompiled = onCompiled;
  303. this._indexParameters = indexParameters;
  304. this._fallbacks = fallbacks;
  305. }
  306. this.uniqueId = Effect._uniqueIdSeed++;
  307. var vertexSource;
  308. var fragmentSource;
  309. if (baseName.vertexElement) {
  310. vertexSource = document.getElementById(baseName.vertexElement);
  311. if (!vertexSource) {
  312. vertexSource = baseName.vertexElement;
  313. }
  314. }
  315. else {
  316. vertexSource = baseName.vertex || baseName;
  317. }
  318. if (baseName.fragmentElement) {
  319. fragmentSource = document.getElementById(baseName.fragmentElement);
  320. if (!fragmentSource) {
  321. fragmentSource = baseName.fragmentElement;
  322. }
  323. }
  324. else {
  325. fragmentSource = baseName.fragment || baseName;
  326. }
  327. this._loadVertexShader(vertexSource, function (vertexCode) {
  328. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  329. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  330. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  331. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  332. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  333. if (baseName) {
  334. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  335. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  336. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  337. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  338. }
  339. else {
  340. _this._vertexSourceCode = migratedVertexCode;
  341. _this._fragmentSourceCode = migratedFragmentCode;
  342. }
  343. _this._prepareEffect();
  344. });
  345. });
  346. });
  347. });
  348. });
  349. });
  350. }
  351. Object.defineProperty(Effect.prototype, "key", {
  352. /**
  353. * Unique key for this effect
  354. */
  355. get: function () {
  356. return this._key;
  357. },
  358. enumerable: true,
  359. configurable: true
  360. });
  361. /**
  362. * If the effect has been compiled and prepared.
  363. * @returns if the effect is compiled and prepared.
  364. */
  365. Effect.prototype.isReady = function () {
  366. return this._isReady;
  367. };
  368. /**
  369. * The engine the effect was initialized with.
  370. * @returns the engine.
  371. */
  372. Effect.prototype.getEngine = function () {
  373. return this._engine;
  374. };
  375. /**
  376. * The compiled webGL program for the effect
  377. * @returns the webGL program.
  378. */
  379. Effect.prototype.getProgram = function () {
  380. return this._program;
  381. };
  382. /**
  383. * The set of names of attribute variables for the shader.
  384. * @returns An array of attribute names.
  385. */
  386. Effect.prototype.getAttributesNames = function () {
  387. return this._attributesNames;
  388. };
  389. /**
  390. * Returns the attribute at the given index.
  391. * @param index The index of the attribute.
  392. * @returns The location of the attribute.
  393. */
  394. Effect.prototype.getAttributeLocation = function (index) {
  395. return this._attributes[index];
  396. };
  397. /**
  398. * Returns the attribute based on the name of the variable.
  399. * @param name of the attribute to look up.
  400. * @returns the attribute location.
  401. */
  402. Effect.prototype.getAttributeLocationByName = function (name) {
  403. var index = this._attributesNames.indexOf(name);
  404. return this._attributes[index];
  405. };
  406. /**
  407. * The number of attributes.
  408. * @returns the numnber of attributes.
  409. */
  410. Effect.prototype.getAttributesCount = function () {
  411. return this._attributes.length;
  412. };
  413. /**
  414. * Gets the index of a uniform variable.
  415. * @param uniformName of the uniform to look up.
  416. * @returns the index.
  417. */
  418. Effect.prototype.getUniformIndex = function (uniformName) {
  419. return this._uniformsNames.indexOf(uniformName);
  420. };
  421. /**
  422. * Returns the attribute based on the name of the variable.
  423. * @param uniformName of the uniform to look up.
  424. * @returns the location of the uniform.
  425. */
  426. Effect.prototype.getUniform = function (uniformName) {
  427. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  428. };
  429. /**
  430. * Returns an array of sampler variable names
  431. * @returns The array of sampler variable neames.
  432. */
  433. Effect.prototype.getSamplers = function () {
  434. return this._samplers;
  435. };
  436. /**
  437. * The error from the last compilation.
  438. * @returns the error string.
  439. */
  440. Effect.prototype.getCompilationError = function () {
  441. return this._compilationError;
  442. };
  443. /**
  444. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  445. * @param func The callback to be used.
  446. */
  447. Effect.prototype.executeWhenCompiled = function (func) {
  448. if (this.isReady()) {
  449. func(this);
  450. return;
  451. }
  452. this.onCompileObservable.add(function (effect) {
  453. func(effect);
  454. });
  455. };
  456. /** @hidden */
  457. Effect.prototype._loadVertexShader = function (vertex, callback) {
  458. if (BABYLON.Tools.IsWindowObjectExist()) {
  459. // DOM element ?
  460. if (vertex instanceof HTMLElement) {
  461. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  462. callback(vertexCode);
  463. return;
  464. }
  465. }
  466. // Base64 encoded ?
  467. if (vertex.substr(0, 7) === "base64:") {
  468. var vertexBinary = window.atob(vertex.substr(7));
  469. callback(vertexBinary);
  470. return;
  471. }
  472. // Is in local store ?
  473. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  474. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  475. return;
  476. }
  477. var vertexShaderUrl;
  478. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  479. vertexShaderUrl = vertex;
  480. }
  481. else {
  482. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  483. }
  484. // Vertex shader
  485. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  486. };
  487. /** @hidden */
  488. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  489. if (BABYLON.Tools.IsWindowObjectExist()) {
  490. // DOM element ?
  491. if (fragment instanceof HTMLElement) {
  492. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  493. callback(fragmentCode);
  494. return;
  495. }
  496. }
  497. // Base64 encoded ?
  498. if (fragment.substr(0, 7) === "base64:") {
  499. var fragmentBinary = window.atob(fragment.substr(7));
  500. callback(fragmentBinary);
  501. return;
  502. }
  503. // Is in local store ?
  504. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  505. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  506. return;
  507. }
  508. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  509. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  510. return;
  511. }
  512. var fragmentShaderUrl;
  513. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  514. fragmentShaderUrl = fragment;
  515. }
  516. else {
  517. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  518. }
  519. // Fragment shader
  520. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  521. };
  522. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  523. // Rebuild shaders source code
  524. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  525. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  526. vertexCode = prefix + vertexCode;
  527. fragmentCode = prefix + fragmentCode;
  528. // Number lines of shaders source code
  529. var i = 2;
  530. var regex = /\n/gm;
  531. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  532. i = 2;
  533. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  534. // Dump shaders name and formatted source code
  535. if (this.name.vertexElement) {
  536. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  537. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  538. }
  539. else if (this.name.vertex) {
  540. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  541. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  542. }
  543. else {
  544. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  545. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  546. }
  547. };
  548. ;
  549. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  550. var preparedSourceCode = this._processPrecision(sourceCode);
  551. if (this._engine.webGLVersion == 1) {
  552. callback(preparedSourceCode);
  553. return;
  554. }
  555. // Already converted
  556. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  557. callback(preparedSourceCode.replace("#version 300 es", ""));
  558. return;
  559. }
  560. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  561. // Remove extensions
  562. // #extension GL_OES_standard_derivatives : enable
  563. // #extension GL_EXT_shader_texture_lod : enable
  564. // #extension GL_EXT_frag_depth : enable
  565. // #extension GL_EXT_draw_buffers : require
  566. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  567. var result = preparedSourceCode.replace(regex, "");
  568. // Migrate to GLSL v300
  569. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  570. result = result.replace(/attribute[ \t]/g, "in ");
  571. result = result.replace(/[ \t]attribute/g, " in");
  572. if (isFragment) {
  573. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  574. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  575. result = result.replace(/texture2D\s*\(/g, "texture(");
  576. result = result.replace(/textureCube\s*\(/g, "texture(");
  577. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  578. result = result.replace(/gl_FragColor/g, "glFragColor");
  579. result = result.replace(/gl_FragData/g, "glFragData");
  580. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  581. }
  582. callback(result);
  583. };
  584. Effect.prototype._processIncludes = function (sourceCode, callback) {
  585. var _this = this;
  586. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  587. var match = regex.exec(sourceCode);
  588. var returnValue = new String(sourceCode);
  589. while (match != null) {
  590. var includeFile = match[1];
  591. // Uniform declaration
  592. if (includeFile.indexOf("__decl__") !== -1) {
  593. includeFile = includeFile.replace(/__decl__/, "");
  594. if (this._engine.supportsUniformBuffers) {
  595. includeFile = includeFile.replace(/Vertex/, "Ubo");
  596. includeFile = includeFile.replace(/Fragment/, "Ubo");
  597. }
  598. includeFile = includeFile + "Declaration";
  599. }
  600. if (Effect.IncludesShadersStore[includeFile]) {
  601. // Substitution
  602. var includeContent = Effect.IncludesShadersStore[includeFile];
  603. if (match[2]) {
  604. var splits = match[3].split(",");
  605. for (var index = 0; index < splits.length; index += 2) {
  606. var source = new RegExp(splits[index], "g");
  607. var dest = splits[index + 1];
  608. includeContent = includeContent.replace(source, dest);
  609. }
  610. }
  611. if (match[4]) {
  612. var indexString = match[5];
  613. if (indexString.indexOf("..") !== -1) {
  614. var indexSplits = indexString.split("..");
  615. var minIndex = parseInt(indexSplits[0]);
  616. var maxIndex = parseInt(indexSplits[1]);
  617. var sourceIncludeContent = includeContent.slice(0);
  618. includeContent = "";
  619. if (isNaN(maxIndex)) {
  620. maxIndex = this._indexParameters[indexSplits[1]];
  621. }
  622. for (var i = minIndex; i < maxIndex; i++) {
  623. if (!this._engine.supportsUniformBuffers) {
  624. // Ubo replacement
  625. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  626. return p1 + "{X}";
  627. });
  628. }
  629. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  630. }
  631. }
  632. else {
  633. if (!this._engine.supportsUniformBuffers) {
  634. // Ubo replacement
  635. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  636. return p1 + "{X}";
  637. });
  638. }
  639. includeContent = includeContent.replace(/\{X\}/g, indexString);
  640. }
  641. }
  642. // Replace
  643. returnValue = returnValue.replace(match[0], includeContent);
  644. }
  645. else {
  646. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  647. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  648. Effect.IncludesShadersStore[includeFile] = fileContent;
  649. _this._processIncludes(returnValue, callback);
  650. });
  651. return;
  652. }
  653. match = regex.exec(sourceCode);
  654. }
  655. callback(returnValue);
  656. };
  657. Effect.prototype._processPrecision = function (source) {
  658. if (source.indexOf("precision highp float") === -1) {
  659. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  660. source = "precision mediump float;\n" + source;
  661. }
  662. else {
  663. source = "precision highp float;\n" + source;
  664. }
  665. }
  666. else {
  667. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  668. source = source.replace("precision highp float", "precision mediump float");
  669. }
  670. }
  671. return source;
  672. };
  673. /**
  674. * Recompiles the webGL program
  675. * @param vertexSourceCode The source code for the vertex shader.
  676. * @param fragmentSourceCode The source code for the fragment shader.
  677. * @param onCompiled Callback called when completed.
  678. * @param onError Callback called on error.
  679. */
  680. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  681. var _this = this;
  682. this._isReady = false;
  683. this._vertexSourceCodeOverride = vertexSourceCode;
  684. this._fragmentSourceCodeOverride = fragmentSourceCode;
  685. this.onError = function (effect, error) {
  686. if (onError) {
  687. onError(error);
  688. }
  689. };
  690. this.onCompiled = function () {
  691. var scenes = _this.getEngine().scenes;
  692. for (var i = 0; i < scenes.length; i++) {
  693. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  694. }
  695. if (onCompiled) {
  696. onCompiled(_this._program);
  697. }
  698. };
  699. this._fallbacks = null;
  700. this._prepareEffect();
  701. };
  702. /**
  703. * Gets the uniform locations of the the specified variable names
  704. * @param names THe names of the variables to lookup.
  705. * @returns Array of locations in the same order as variable names.
  706. */
  707. Effect.prototype.getSpecificUniformLocations = function (names) {
  708. var engine = this._engine;
  709. return engine.getUniforms(this._program, names);
  710. };
  711. /**
  712. * Prepares the effect
  713. */
  714. Effect.prototype._prepareEffect = function () {
  715. var attributesNames = this._attributesNames;
  716. var defines = this.defines;
  717. var fallbacks = this._fallbacks;
  718. this._valueCache = {};
  719. var previousProgram = this._program;
  720. try {
  721. var engine = this._engine;
  722. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  723. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  724. }
  725. else {
  726. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  727. }
  728. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  729. if (engine.supportsUniformBuffers) {
  730. for (var name in this._uniformBuffersNames) {
  731. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  732. }
  733. }
  734. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  735. this._attributes = engine.getAttributes(this._program, attributesNames);
  736. var index;
  737. for (index = 0; index < this._samplers.length; index++) {
  738. var sampler = this.getUniform(this._samplers[index]);
  739. if (sampler == null) {
  740. this._samplers.splice(index, 1);
  741. index--;
  742. }
  743. }
  744. engine.bindSamplers(this);
  745. this._compilationError = "";
  746. this._isReady = true;
  747. if (this.onCompiled) {
  748. this.onCompiled(this);
  749. }
  750. this.onCompileObservable.notifyObservers(this);
  751. this.onCompileObservable.clear();
  752. // Unbind mesh reference in fallbacks
  753. if (this._fallbacks) {
  754. this._fallbacks.unBindMesh();
  755. }
  756. if (previousProgram) {
  757. this.getEngine()._deleteProgram(previousProgram);
  758. }
  759. }
  760. catch (e) {
  761. this._compilationError = e.message;
  762. // Let's go through fallbacks then
  763. BABYLON.Tools.Error("Unable to compile effect:");
  764. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  765. return " " + uniform;
  766. }));
  767. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  768. return " " + attribute;
  769. }));
  770. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  771. BABYLON.Tools.Error("Error: " + this._compilationError);
  772. if (previousProgram) {
  773. this._program = previousProgram;
  774. this._isReady = true;
  775. if (this.onError) {
  776. this.onError(this, this._compilationError);
  777. }
  778. this.onErrorObservable.notifyObservers(this);
  779. }
  780. if (fallbacks && fallbacks.isMoreFallbacks) {
  781. BABYLON.Tools.Error("Trying next fallback.");
  782. this.defines = fallbacks.reduce(this.defines, this);
  783. this._prepareEffect();
  784. }
  785. else { // Sorry we did everything we can
  786. if (this.onError) {
  787. this.onError(this, this._compilationError);
  788. }
  789. this.onErrorObservable.notifyObservers(this);
  790. this.onErrorObservable.clear();
  791. // Unbind mesh reference in fallbacks
  792. if (this._fallbacks) {
  793. this._fallbacks.unBindMesh();
  794. }
  795. }
  796. }
  797. };
  798. Object.defineProperty(Effect.prototype, "isSupported", {
  799. /**
  800. * Checks if the effect is supported. (Must be called after compilation)
  801. */
  802. get: function () {
  803. return this._compilationError === "";
  804. },
  805. enumerable: true,
  806. configurable: true
  807. });
  808. /**
  809. * Binds a texture to the engine to be used as output of the shader.
  810. * @param channel Name of the output variable.
  811. * @param texture Texture to bind.
  812. */
  813. Effect.prototype._bindTexture = function (channel, texture) {
  814. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  815. };
  816. /**
  817. * Sets a texture on the engine to be used in the shader.
  818. * @param channel Name of the sampler variable.
  819. * @param texture Texture to set.
  820. */
  821. Effect.prototype.setTexture = function (channel, texture) {
  822. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  823. };
  824. /**
  825. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  826. * @param channel Name of the sampler variable.
  827. * @param texture Texture to set.
  828. */
  829. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  830. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  831. };
  832. /**
  833. * Sets an array of textures on the engine to be used in the shader.
  834. * @param channel Name of the variable.
  835. * @param textures Textures to set.
  836. */
  837. Effect.prototype.setTextureArray = function (channel, textures) {
  838. if (this._samplers.indexOf(channel + "Ex") === -1) {
  839. var initialPos = this._samplers.indexOf(channel);
  840. for (var index = 1; index < textures.length; index++) {
  841. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  842. }
  843. }
  844. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  845. };
  846. /**
  847. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  848. * @param channel Name of the sampler variable.
  849. * @param postProcess Post process to get the input texture from.
  850. */
  851. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  852. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  853. };
  854. /**
  855. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  856. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  857. * @param channel Name of the sampler variable.
  858. * @param postProcess Post process to get the output texture from.
  859. */
  860. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  861. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  862. };
  863. /** @hidden */
  864. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  865. var cache = this._valueCache[uniformName];
  866. var flag = matrix.updateFlag;
  867. if (cache !== undefined && cache === flag) {
  868. return false;
  869. }
  870. this._valueCache[uniformName] = flag;
  871. return true;
  872. };
  873. /** @hidden */
  874. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  875. var cache = this._valueCache[uniformName];
  876. if (!cache) {
  877. cache = [x, y];
  878. this._valueCache[uniformName] = cache;
  879. return true;
  880. }
  881. var changed = false;
  882. if (cache[0] !== x) {
  883. cache[0] = x;
  884. changed = true;
  885. }
  886. if (cache[1] !== y) {
  887. cache[1] = y;
  888. changed = true;
  889. }
  890. return changed;
  891. };
  892. /** @hidden */
  893. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  894. var cache = this._valueCache[uniformName];
  895. if (!cache) {
  896. cache = [x, y, z];
  897. this._valueCache[uniformName] = cache;
  898. return true;
  899. }
  900. var changed = false;
  901. if (cache[0] !== x) {
  902. cache[0] = x;
  903. changed = true;
  904. }
  905. if (cache[1] !== y) {
  906. cache[1] = y;
  907. changed = true;
  908. }
  909. if (cache[2] !== z) {
  910. cache[2] = z;
  911. changed = true;
  912. }
  913. return changed;
  914. };
  915. /** @hidden */
  916. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  917. var cache = this._valueCache[uniformName];
  918. if (!cache) {
  919. cache = [x, y, z, w];
  920. this._valueCache[uniformName] = cache;
  921. return true;
  922. }
  923. var changed = false;
  924. if (cache[0] !== x) {
  925. cache[0] = x;
  926. changed = true;
  927. }
  928. if (cache[1] !== y) {
  929. cache[1] = y;
  930. changed = true;
  931. }
  932. if (cache[2] !== z) {
  933. cache[2] = z;
  934. changed = true;
  935. }
  936. if (cache[3] !== w) {
  937. cache[3] = w;
  938. changed = true;
  939. }
  940. return changed;
  941. };
  942. /**
  943. * Binds a buffer to a uniform.
  944. * @param buffer Buffer to bind.
  945. * @param name Name of the uniform variable to bind to.
  946. */
  947. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  948. var bufferName = this._uniformBuffersNames[name];
  949. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  950. return;
  951. }
  952. Effect._baseCache[bufferName] = buffer;
  953. this._engine.bindUniformBufferBase(buffer, bufferName);
  954. };
  955. /**
  956. * Binds block to a uniform.
  957. * @param blockName Name of the block to bind.
  958. * @param index Index to bind.
  959. */
  960. Effect.prototype.bindUniformBlock = function (blockName, index) {
  961. this._engine.bindUniformBlock(this._program, blockName, index);
  962. };
  963. /**
  964. * Sets an interger value on a uniform variable.
  965. * @param uniformName Name of the variable.
  966. * @param value Value to be set.
  967. * @returns this effect.
  968. */
  969. Effect.prototype.setInt = function (uniformName, value) {
  970. var cache = this._valueCache[uniformName];
  971. if (cache !== undefined && cache === value)
  972. return this;
  973. this._valueCache[uniformName] = value;
  974. this._engine.setInt(this.getUniform(uniformName), value);
  975. return this;
  976. };
  977. /**
  978. * Sets an int array on a uniform variable.
  979. * @param uniformName Name of the variable.
  980. * @param array array to be set.
  981. * @returns this effect.
  982. */
  983. Effect.prototype.setIntArray = function (uniformName, array) {
  984. this._valueCache[uniformName] = null;
  985. this._engine.setIntArray(this.getUniform(uniformName), array);
  986. return this;
  987. };
  988. /**
  989. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  990. * @param uniformName Name of the variable.
  991. * @param array array to be set.
  992. * @returns this effect.
  993. */
  994. Effect.prototype.setIntArray2 = function (uniformName, array) {
  995. this._valueCache[uniformName] = null;
  996. this._engine.setIntArray2(this.getUniform(uniformName), array);
  997. return this;
  998. };
  999. /**
  1000. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1001. * @param uniformName Name of the variable.
  1002. * @param array array to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1006. this._valueCache[uniformName] = null;
  1007. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1008. return this;
  1009. };
  1010. /**
  1011. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1012. * @param uniformName Name of the variable.
  1013. * @param array array to be set.
  1014. * @returns this effect.
  1015. */
  1016. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1017. this._valueCache[uniformName] = null;
  1018. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1019. return this;
  1020. };
  1021. /**
  1022. * Sets an float array on a uniform variable.
  1023. * @param uniformName Name of the variable.
  1024. * @param array array to be set.
  1025. * @returns this effect.
  1026. */
  1027. Effect.prototype.setFloatArray = function (uniformName, array) {
  1028. this._valueCache[uniformName] = null;
  1029. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1030. return this;
  1031. };
  1032. /**
  1033. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1034. * @param uniformName Name of the variable.
  1035. * @param array array to be set.
  1036. * @returns this effect.
  1037. */
  1038. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1039. this._valueCache[uniformName] = null;
  1040. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1041. return this;
  1042. };
  1043. /**
  1044. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1045. * @param uniformName Name of the variable.
  1046. * @param array array to be set.
  1047. * @returns this effect.
  1048. */
  1049. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1052. return this;
  1053. };
  1054. /**
  1055. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1056. * @param uniformName Name of the variable.
  1057. * @param array array to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1061. this._valueCache[uniformName] = null;
  1062. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets an array on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param array array to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setArray = function (uniformName, array) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setArray(this.getUniform(uniformName), array);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1078. * @param uniformName Name of the variable.
  1079. * @param array array to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setArray2 = function (uniformName, array) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setArray2(this.getUniform(uniformName), array);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1089. * @param uniformName Name of the variable.
  1090. * @param array array to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setArray3 = function (uniformName, array) {
  1094. this._valueCache[uniformName] = null;
  1095. this._engine.setArray3(this.getUniform(uniformName), array);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1100. * @param uniformName Name of the variable.
  1101. * @param array array to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setArray4 = function (uniformName, array) {
  1105. this._valueCache[uniformName] = null;
  1106. this._engine.setArray4(this.getUniform(uniformName), array);
  1107. return this;
  1108. };
  1109. /**
  1110. * Sets matrices on a uniform variable.
  1111. * @param uniformName Name of the variable.
  1112. * @param matrices matrices to be set.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1116. if (!matrices) {
  1117. return this;
  1118. }
  1119. this._valueCache[uniformName] = null;
  1120. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets matrix on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param matrix matrix to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1130. if (this._cacheMatrix(uniformName, matrix)) {
  1131. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1137. * @param uniformName Name of the variable.
  1138. * @param matrix matrix to be set.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1142. this._valueCache[uniformName] = null;
  1143. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1148. * @param uniformName Name of the variable.
  1149. * @param matrix matrix to be set.
  1150. * @returns this effect.
  1151. */
  1152. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1153. this._valueCache[uniformName] = null;
  1154. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1155. return this;
  1156. };
  1157. /**
  1158. * Sets a float on a uniform variable.
  1159. * @param uniformName Name of the variable.
  1160. * @param value value to be set.
  1161. * @returns this effect.
  1162. */
  1163. Effect.prototype.setFloat = function (uniformName, value) {
  1164. var cache = this._valueCache[uniformName];
  1165. if (cache !== undefined && cache === value)
  1166. return this;
  1167. this._valueCache[uniformName] = value;
  1168. this._engine.setFloat(this.getUniform(uniformName), value);
  1169. return this;
  1170. };
  1171. /**
  1172. * Sets a boolean on a uniform variable.
  1173. * @param uniformName Name of the variable.
  1174. * @param bool value to be set.
  1175. * @returns this effect.
  1176. */
  1177. Effect.prototype.setBool = function (uniformName, bool) {
  1178. var cache = this._valueCache[uniformName];
  1179. if (cache !== undefined && cache === bool)
  1180. return this;
  1181. this._valueCache[uniformName] = bool;
  1182. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1183. return this;
  1184. };
  1185. /**
  1186. * Sets a Vector2 on a uniform variable.
  1187. * @param uniformName Name of the variable.
  1188. * @param vector2 vector2 to be set.
  1189. * @returns this effect.
  1190. */
  1191. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1192. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1193. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1194. }
  1195. return this;
  1196. };
  1197. /**
  1198. * Sets a float2 on a uniform variable.
  1199. * @param uniformName Name of the variable.
  1200. * @param x First float in float2.
  1201. * @param y Second float in float2.
  1202. * @returns this effect.
  1203. */
  1204. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1205. if (this._cacheFloat2(uniformName, x, y)) {
  1206. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1207. }
  1208. return this;
  1209. };
  1210. /**
  1211. * Sets a Vector3 on a uniform variable.
  1212. * @param uniformName Name of the variable.
  1213. * @param vector3 Value to be set.
  1214. * @returns this effect.
  1215. */
  1216. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1217. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1218. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1219. }
  1220. return this;
  1221. };
  1222. /**
  1223. * Sets a float3 on a uniform variable.
  1224. * @param uniformName Name of the variable.
  1225. * @param x First float in float3.
  1226. * @param y Second float in float3.
  1227. * @param z Third float in float3.
  1228. * @returns this effect.
  1229. */
  1230. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1231. if (this._cacheFloat3(uniformName, x, y, z)) {
  1232. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1233. }
  1234. return this;
  1235. };
  1236. /**
  1237. * Sets a Vector4 on a uniform variable.
  1238. * @param uniformName Name of the variable.
  1239. * @param vector4 Value to be set.
  1240. * @returns this effect.
  1241. */
  1242. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1243. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1244. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Sets a float4 on a uniform variable.
  1250. * @param uniformName Name of the variable.
  1251. * @param x First float in float4.
  1252. * @param y Second float in float4.
  1253. * @param z Third float in float4.
  1254. * @param w Fourth float in float4.
  1255. * @returns this effect.
  1256. */
  1257. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1258. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1259. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1260. }
  1261. return this;
  1262. };
  1263. /**
  1264. * Sets a Color3 on a uniform variable.
  1265. * @param uniformName Name of the variable.
  1266. * @param color3 Value to be set.
  1267. * @returns this effect.
  1268. */
  1269. Effect.prototype.setColor3 = function (uniformName, color3) {
  1270. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1271. this._engine.setColor3(this.getUniform(uniformName), color3);
  1272. }
  1273. return this;
  1274. };
  1275. /**
  1276. * Sets a Color4 on a uniform variable.
  1277. * @param uniformName Name of the variable.
  1278. * @param color3 Value to be set.
  1279. * @param alpha Alpha value to be set.
  1280. * @returns this effect.
  1281. */
  1282. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1283. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1284. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1285. }
  1286. return this;
  1287. };
  1288. /**
  1289. * Sets a Color4 on a uniform variable
  1290. * @param uniformName defines the name of the variable
  1291. * @param color4 defines the value to be set
  1292. * @returns this effect.
  1293. */
  1294. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1295. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1296. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1297. }
  1298. return this;
  1299. };
  1300. /**
  1301. * Resets the cache of effects.
  1302. */
  1303. Effect.ResetCache = function () {
  1304. Effect._baseCache = {};
  1305. };
  1306. Effect._uniqueIdSeed = 0;
  1307. Effect._baseCache = {};
  1308. /**
  1309. * Store of each shader (The can be looked up using effect.key)
  1310. */
  1311. Effect.ShadersStore = {};
  1312. /**
  1313. * Store of each included file for a shader (The can be looked up using effect.key)
  1314. */
  1315. Effect.IncludesShadersStore = {};
  1316. return Effect;
  1317. }());
  1318. BABYLON.Effect = Effect;
  1319. })(BABYLON || (BABYLON = {}));
  1320. //# sourceMappingURL=babylon.effect.js.map
  1321. //# sourceMappingURL=babylon.types.js.map
  1322. var BABYLON;
  1323. (function (BABYLON) {
  1324. var KeyboardEventTypes = /** @class */ (function () {
  1325. function KeyboardEventTypes() {
  1326. }
  1327. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1328. get: function () {
  1329. return KeyboardEventTypes._KEYDOWN;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1335. get: function () {
  1336. return KeyboardEventTypes._KEYUP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. KeyboardEventTypes._KEYDOWN = 0x01;
  1342. KeyboardEventTypes._KEYUP = 0x02;
  1343. return KeyboardEventTypes;
  1344. }());
  1345. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1346. var KeyboardInfo = /** @class */ (function () {
  1347. function KeyboardInfo(type, event) {
  1348. this.type = type;
  1349. this.event = event;
  1350. }
  1351. return KeyboardInfo;
  1352. }());
  1353. BABYLON.KeyboardInfo = KeyboardInfo;
  1354. /**
  1355. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1356. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1357. */
  1358. var KeyboardInfoPre = /** @class */ (function (_super) {
  1359. __extends(KeyboardInfoPre, _super);
  1360. function KeyboardInfoPre(type, event) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.skipOnPointerObservable = false;
  1363. return _this;
  1364. }
  1365. return KeyboardInfoPre;
  1366. }(KeyboardInfo));
  1367. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1370. var BABYLON;
  1371. (function (BABYLON) {
  1372. var PointerEventTypes = /** @class */ (function () {
  1373. function PointerEventTypes() {
  1374. }
  1375. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1376. get: function () {
  1377. return PointerEventTypes._POINTERDOWN;
  1378. },
  1379. enumerable: true,
  1380. configurable: true
  1381. });
  1382. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1383. get: function () {
  1384. return PointerEventTypes._POINTERUP;
  1385. },
  1386. enumerable: true,
  1387. configurable: true
  1388. });
  1389. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1390. get: function () {
  1391. return PointerEventTypes._POINTERMOVE;
  1392. },
  1393. enumerable: true,
  1394. configurable: true
  1395. });
  1396. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1397. get: function () {
  1398. return PointerEventTypes._POINTERWHEEL;
  1399. },
  1400. enumerable: true,
  1401. configurable: true
  1402. });
  1403. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1404. get: function () {
  1405. return PointerEventTypes._POINTERPICK;
  1406. },
  1407. enumerable: true,
  1408. configurable: true
  1409. });
  1410. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1411. get: function () {
  1412. return PointerEventTypes._POINTERTAP;
  1413. },
  1414. enumerable: true,
  1415. configurable: true
  1416. });
  1417. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1418. get: function () {
  1419. return PointerEventTypes._POINTERDOUBLETAP;
  1420. },
  1421. enumerable: true,
  1422. configurable: true
  1423. });
  1424. PointerEventTypes._POINTERDOWN = 0x01;
  1425. PointerEventTypes._POINTERUP = 0x02;
  1426. PointerEventTypes._POINTERMOVE = 0x04;
  1427. PointerEventTypes._POINTERWHEEL = 0x08;
  1428. PointerEventTypes._POINTERPICK = 0x10;
  1429. PointerEventTypes._POINTERTAP = 0x20;
  1430. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1431. return PointerEventTypes;
  1432. }());
  1433. BABYLON.PointerEventTypes = PointerEventTypes;
  1434. var PointerInfoBase = /** @class */ (function () {
  1435. function PointerInfoBase(type, event) {
  1436. this.type = type;
  1437. this.event = event;
  1438. }
  1439. return PointerInfoBase;
  1440. }());
  1441. BABYLON.PointerInfoBase = PointerInfoBase;
  1442. /**
  1443. * This class is used to store pointer related info for the onPrePointerObservable event.
  1444. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1445. */
  1446. var PointerInfoPre = /** @class */ (function (_super) {
  1447. __extends(PointerInfoPre, _super);
  1448. function PointerInfoPre(type, event, localX, localY) {
  1449. var _this = _super.call(this, type, event) || this;
  1450. /**
  1451. * Ray from a pointer if availible (eg. 6dof controller)
  1452. */
  1453. _this.ray = null;
  1454. _this.skipOnPointerObservable = false;
  1455. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1456. return _this;
  1457. }
  1458. return PointerInfoPre;
  1459. }(PointerInfoBase));
  1460. BABYLON.PointerInfoPre = PointerInfoPre;
  1461. /**
  1462. * This type contains all the data related to a pointer event in Babylon.js.
  1463. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1464. */
  1465. var PointerInfo = /** @class */ (function (_super) {
  1466. __extends(PointerInfo, _super);
  1467. function PointerInfo(type, event, pickInfo) {
  1468. var _this = _super.call(this, type, event) || this;
  1469. _this.pickInfo = pickInfo;
  1470. return _this;
  1471. }
  1472. return PointerInfo;
  1473. }(PointerInfoBase));
  1474. BABYLON.PointerInfo = PointerInfo;
  1475. })(BABYLON || (BABYLON = {}));
  1476. //# sourceMappingURL=babylon.pointerEvents.js.map
  1477. var BABYLON;
  1478. (function (BABYLON) {
  1479. BABYLON.ToGammaSpace = 1 / 2.2;
  1480. BABYLON.ToLinearSpace = 2.2;
  1481. BABYLON.Epsilon = 0.001;
  1482. /**
  1483. * Class used to hold a RBG color
  1484. */
  1485. var Color3 = /** @class */ (function () {
  1486. /**
  1487. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1488. * @param r defines the red component (between 0 and 1, default is 0)
  1489. * @param g defines the green component (between 0 and 1, default is 0)
  1490. * @param b defines the blue component (between 0 and 1, default is 0)
  1491. */
  1492. function Color3(
  1493. /**
  1494. * Defines the red component (between 0 and 1, default is 0)
  1495. */
  1496. r,
  1497. /**
  1498. * Defines the green component (between 0 and 1, default is 0)
  1499. */
  1500. g,
  1501. /**
  1502. * Defines the blue component (between 0 and 1, default is 0)
  1503. */
  1504. b) {
  1505. if (r === void 0) { r = 0; }
  1506. if (g === void 0) { g = 0; }
  1507. if (b === void 0) { b = 0; }
  1508. this.r = r;
  1509. this.g = g;
  1510. this.b = b;
  1511. }
  1512. /**
  1513. * Creates a string with the Color3 current values
  1514. * @returns the string representation of the Color3 object
  1515. */
  1516. Color3.prototype.toString = function () {
  1517. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1518. };
  1519. /**
  1520. * Returns the string "Color3"
  1521. * @returns "Color3"
  1522. */
  1523. Color3.prototype.getClassName = function () {
  1524. return "Color3";
  1525. };
  1526. /**
  1527. * Compute the Color3 hash code
  1528. * @returns an unique number that can be used to hash Color3 objects
  1529. */
  1530. Color3.prototype.getHashCode = function () {
  1531. var hash = this.r || 0;
  1532. hash = (hash * 397) ^ (this.g || 0);
  1533. hash = (hash * 397) ^ (this.b || 0);
  1534. return hash;
  1535. };
  1536. // Operators
  1537. /**
  1538. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1539. * @param array defines the array where to store the r,g,b components
  1540. * @param index defines an optional index in the target array to define where to start storing values
  1541. * @returns the current Color3 object
  1542. */
  1543. Color3.prototype.toArray = function (array, index) {
  1544. if (index === undefined) {
  1545. index = 0;
  1546. }
  1547. array[index] = this.r;
  1548. array[index + 1] = this.g;
  1549. array[index + 2] = this.b;
  1550. return this;
  1551. };
  1552. /**
  1553. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1554. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1555. * @returns a new {BABYLON.Color4} object
  1556. */
  1557. Color3.prototype.toColor4 = function (alpha) {
  1558. if (alpha === void 0) { alpha = 1; }
  1559. return new Color4(this.r, this.g, this.b, alpha);
  1560. };
  1561. /**
  1562. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1563. * @returns the new array
  1564. */
  1565. Color3.prototype.asArray = function () {
  1566. var result = new Array();
  1567. this.toArray(result, 0);
  1568. return result;
  1569. };
  1570. /**
  1571. * Returns the luminance value
  1572. * @returns a float value
  1573. */
  1574. Color3.prototype.toLuminance = function () {
  1575. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1576. };
  1577. /**
  1578. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1579. * @param otherColor defines the second operand
  1580. * @returns the new Color3 object
  1581. */
  1582. Color3.prototype.multiply = function (otherColor) {
  1583. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1584. };
  1585. /**
  1586. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1587. * @param otherColor defines the second operand
  1588. * @param result defines the Color3 object where to store the result
  1589. * @returns the current Color3
  1590. */
  1591. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1592. result.r = this.r * otherColor.r;
  1593. result.g = this.g * otherColor.g;
  1594. result.b = this.b * otherColor.b;
  1595. return this;
  1596. };
  1597. /**
  1598. * Determines equality between Color3 objects
  1599. * @param otherColor defines the second operand
  1600. * @returns true if the rgb values are equal to the given ones
  1601. */
  1602. Color3.prototype.equals = function (otherColor) {
  1603. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1604. };
  1605. /**
  1606. * Determines equality between the current Color3 object and a set of r,b,g values
  1607. * @param r defines the red component to check
  1608. * @param g defines the green component to check
  1609. * @param b defines the blue component to check
  1610. * @returns true if the rgb values are equal to the given ones
  1611. */
  1612. Color3.prototype.equalsFloats = function (r, g, b) {
  1613. return this.r === r && this.g === g && this.b === b;
  1614. };
  1615. /**
  1616. * Multiplies in place each rgb value by scale
  1617. * @param scale defines the scaling factor
  1618. * @returns the updated Color3
  1619. */
  1620. Color3.prototype.scale = function (scale) {
  1621. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1622. };
  1623. /**
  1624. * Multiplies the rgb values by scale and stores the result into "result"
  1625. * @param scale defines the scaling factor
  1626. * @param result defines the Color3 object where to store the result
  1627. * @returns the unmodified current Color3
  1628. */
  1629. Color3.prototype.scaleToRef = function (scale, result) {
  1630. result.r = this.r * scale;
  1631. result.g = this.g * scale;
  1632. result.b = this.b * scale;
  1633. return this;
  1634. };
  1635. /**
  1636. * Scale the current Color3 values by a factor and add the result to a given Color3
  1637. * @param scale defines the scale factor
  1638. * @param result defines color to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1642. result.r += this.r * scale;
  1643. result.g += this.g * scale;
  1644. result.b += this.b * scale;
  1645. return this;
  1646. };
  1647. /**
  1648. * Clamps the rgb values by the min and max values and stores the result into "result"
  1649. * @param min defines minimum clamping value (default is 0)
  1650. * @param max defines maximum clamping value (default is 1)
  1651. * @param result defines color to store the result into
  1652. * @returns the original Color3
  1653. */
  1654. Color3.prototype.clampToRef = function (min, max, result) {
  1655. if (min === void 0) { min = 0; }
  1656. if (max === void 0) { max = 1; }
  1657. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1658. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1659. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1660. return this;
  1661. };
  1662. /**
  1663. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1664. * @param otherColor defines the second operand
  1665. * @returns the new Color3
  1666. */
  1667. Color3.prototype.add = function (otherColor) {
  1668. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1669. };
  1670. /**
  1671. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1672. * @param otherColor defines the second operand
  1673. * @param result defines Color3 object to store the result into
  1674. * @returns the unmodified current Color3
  1675. */
  1676. Color3.prototype.addToRef = function (otherColor, result) {
  1677. result.r = this.r + otherColor.r;
  1678. result.g = this.g + otherColor.g;
  1679. result.b = this.b + otherColor.b;
  1680. return this;
  1681. };
  1682. /**
  1683. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1684. * @param otherColor defines the second operand
  1685. * @returns the new Color3
  1686. */
  1687. Color3.prototype.subtract = function (otherColor) {
  1688. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1689. };
  1690. /**
  1691. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1692. * @param otherColor defines the second operand
  1693. * @param result defines Color3 object to store the result into
  1694. * @returns the unmodified current Color3
  1695. */
  1696. Color3.prototype.subtractToRef = function (otherColor, result) {
  1697. result.r = this.r - otherColor.r;
  1698. result.g = this.g - otherColor.g;
  1699. result.b = this.b - otherColor.b;
  1700. return this;
  1701. };
  1702. /**
  1703. * Copy the current object
  1704. * @returns a new Color3 copied the current one
  1705. */
  1706. Color3.prototype.clone = function () {
  1707. return new Color3(this.r, this.g, this.b);
  1708. };
  1709. /**
  1710. * Copies the rgb values from the source in the current Color3
  1711. * @param source defines the source Color3 object
  1712. * @returns the updated Color3 object
  1713. */
  1714. Color3.prototype.copyFrom = function (source) {
  1715. this.r = source.r;
  1716. this.g = source.g;
  1717. this.b = source.b;
  1718. return this;
  1719. };
  1720. /**
  1721. * Updates the Color3 rgb values from the given floats
  1722. * @param r defines the red component to read from
  1723. * @param g defines the green component to read from
  1724. * @param b defines the blue component to read from
  1725. * @returns the current Color3 object
  1726. */
  1727. Color3.prototype.copyFromFloats = function (r, g, b) {
  1728. this.r = r;
  1729. this.g = g;
  1730. this.b = b;
  1731. return this;
  1732. };
  1733. /**
  1734. * Updates the Color3 rgb values from the given floats
  1735. * @param r defines the red component to read from
  1736. * @param g defines the green component to read from
  1737. * @param b defines the blue component to read from
  1738. * @returns the current Color3 object
  1739. */
  1740. Color3.prototype.set = function (r, g, b) {
  1741. return this.copyFromFloats(r, g, b);
  1742. };
  1743. /**
  1744. * Compute the Color3 hexadecimal code as a string
  1745. * @returns a string containing the hexadecimal representation of the Color3 object
  1746. */
  1747. Color3.prototype.toHexString = function () {
  1748. var intR = (this.r * 255) | 0;
  1749. var intG = (this.g * 255) | 0;
  1750. var intB = (this.b * 255) | 0;
  1751. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1752. };
  1753. /**
  1754. * Computes a new Color3 converted from the current one to linear space
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.prototype.toLinearSpace = function () {
  1758. var convertedColor = new Color3();
  1759. this.toLinearSpaceToRef(convertedColor);
  1760. return convertedColor;
  1761. };
  1762. /**
  1763. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1764. * @param convertedColor defines the Color3 object where to store the linear space version
  1765. * @returns the unmodified Color3
  1766. */
  1767. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1768. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1769. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1770. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1771. return this;
  1772. };
  1773. /**
  1774. * Computes a new Color3 converted from the current one to gamma space
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.prototype.toGammaSpace = function () {
  1778. var convertedColor = new Color3();
  1779. this.toGammaSpaceToRef(convertedColor);
  1780. return convertedColor;
  1781. };
  1782. /**
  1783. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1784. * @param convertedColor defines the Color3 object where to store the gamma space version
  1785. * @returns the unmodified Color3
  1786. */
  1787. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1788. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1789. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1790. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1791. return this;
  1792. };
  1793. // Statics
  1794. /**
  1795. * Creates a new Color3 from the string containing valid hexadecimal values
  1796. * @param hex defines a string containing valid hexadecimal values
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.FromHexString = function (hex) {
  1800. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1801. return new Color3(0, 0, 0);
  1802. }
  1803. var r = parseInt(hex.substring(1, 3), 16);
  1804. var g = parseInt(hex.substring(3, 5), 16);
  1805. var b = parseInt(hex.substring(5, 7), 16);
  1806. return Color3.FromInts(r, g, b);
  1807. };
  1808. /**
  1809. * Creates a new Vector3 from the starting index of the given array
  1810. * @param array defines the source array
  1811. * @param offset defines an offset in the source array
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.FromArray = function (array, offset) {
  1815. if (offset === void 0) { offset = 0; }
  1816. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1817. };
  1818. /**
  1819. * Creates a new Color3 from integer values (< 256)
  1820. * @param r defines the red component to read from (value between 0 and 255)
  1821. * @param g defines the green component to read from (value between 0 and 255)
  1822. * @param b defines the blue component to read from (value between 0 and 255)
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.FromInts = function (r, g, b) {
  1826. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1827. };
  1828. /**
  1829. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1830. * @param start defines the start Color3 value
  1831. * @param end defines the end Color3 value
  1832. * @param amount defines the gradient value between start and end
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Lerp = function (start, end, amount) {
  1836. var r = start.r + ((end.r - start.r) * amount);
  1837. var g = start.g + ((end.g - start.g) * amount);
  1838. var b = start.b + ((end.b - start.b) * amount);
  1839. return new Color3(r, g, b);
  1840. };
  1841. /**
  1842. * Returns a Color3 value containing a red color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Red = function () { return new Color3(1, 0, 0); };
  1846. /**
  1847. * Returns a Color3 value containing a green color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Green = function () { return new Color3(0, 1, 0); };
  1851. /**
  1852. * Returns a Color3 value containing a blue color
  1853. * @returns a new Color3 object
  1854. */
  1855. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1856. /**
  1857. * Returns a Color3 value containing a black color
  1858. * @returns a new Color3 object
  1859. */
  1860. Color3.Black = function () { return new Color3(0, 0, 0); };
  1861. /**
  1862. * Returns a Color3 value containing a white color
  1863. * @returns a new Color3 object
  1864. */
  1865. Color3.White = function () { return new Color3(1, 1, 1); };
  1866. /**
  1867. * Returns a Color3 value containing a purple color
  1868. * @returns a new Color3 object
  1869. */
  1870. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1871. /**
  1872. * Returns a Color3 value containing a magenta color
  1873. * @returns a new Color3 object
  1874. */
  1875. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1876. /**
  1877. * Returns a Color3 value containing a yellow color
  1878. * @returns a new Color3 object
  1879. */
  1880. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1881. /**
  1882. * Returns a Color3 value containing a gray color
  1883. * @returns a new Color3 object
  1884. */
  1885. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1886. /**
  1887. * Returns a Color3 value containing a teal color
  1888. * @returns a new Color3 object
  1889. */
  1890. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1891. /**
  1892. * Returns a Color3 value containing a random color
  1893. * @returns a new Color3 object
  1894. */
  1895. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1896. return Color3;
  1897. }());
  1898. BABYLON.Color3 = Color3;
  1899. /**
  1900. * Class used to hold a RBGA color
  1901. */
  1902. var Color4 = /** @class */ (function () {
  1903. /**
  1904. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1905. * @param r defines the red component (between 0 and 1, default is 0)
  1906. * @param g defines the green component (between 0 and 1, default is 0)
  1907. * @param b defines the blue component (between 0 and 1, default is 0)
  1908. * @param a defines the alpha component (between 0 and 1, default is 1)
  1909. */
  1910. function Color4(
  1911. /**
  1912. * Defines the red component (between 0 and 1, default is 0)
  1913. */
  1914. r,
  1915. /**
  1916. * Defines the green component (between 0 and 1, default is 0)
  1917. */
  1918. g,
  1919. /**
  1920. * Defines the blue component (between 0 and 1, default is 0)
  1921. */
  1922. b,
  1923. /**
  1924. * Defines the alpha component (between 0 and 1, default is 1)
  1925. */
  1926. a) {
  1927. if (r === void 0) { r = 0; }
  1928. if (g === void 0) { g = 0; }
  1929. if (b === void 0) { b = 0; }
  1930. if (a === void 0) { a = 1; }
  1931. this.r = r;
  1932. this.g = g;
  1933. this.b = b;
  1934. this.a = a;
  1935. }
  1936. // Operators
  1937. /**
  1938. * Adds in place the given Color4 values to the current Color4 object
  1939. * @param right defines the second operand
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.addInPlace = function (right) {
  1943. this.r += right.r;
  1944. this.g += right.g;
  1945. this.b += right.b;
  1946. this.a += right.a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1951. * @returns the new array
  1952. */
  1953. Color4.prototype.asArray = function () {
  1954. var result = new Array();
  1955. this.toArray(result, 0);
  1956. return result;
  1957. };
  1958. /**
  1959. * Stores from the starting index in the given array the Color4 successive values
  1960. * @param array defines the array where to store the r,g,b components
  1961. * @param index defines an optional index in the target array to define where to start storing values
  1962. * @returns the current Color4 object
  1963. */
  1964. Color4.prototype.toArray = function (array, index) {
  1965. if (index === undefined) {
  1966. index = 0;
  1967. }
  1968. array[index] = this.r;
  1969. array[index + 1] = this.g;
  1970. array[index + 2] = this.b;
  1971. array[index + 3] = this.a;
  1972. return this;
  1973. };
  1974. /**
  1975. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1976. * @param right defines the second operand
  1977. * @returns a new Color4 object
  1978. */
  1979. Color4.prototype.add = function (right) {
  1980. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1981. };
  1982. /**
  1983. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1984. * @param right defines the second operand
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.subtract = function (right) {
  1988. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1989. };
  1990. /**
  1991. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1992. * @param right defines the second operand
  1993. * @param result defines the Color4 object where to store the result
  1994. * @returns the current Color4 object
  1995. */
  1996. Color4.prototype.subtractToRef = function (right, result) {
  1997. result.r = this.r - right.r;
  1998. result.g = this.g - right.g;
  1999. result.b = this.b - right.b;
  2000. result.a = this.a - right.a;
  2001. return this;
  2002. };
  2003. /**
  2004. * Creates a new Color4 with the current Color4 values multiplied by scale
  2005. * @param scale defines the scaling factor to apply
  2006. * @returns a new Color4 object
  2007. */
  2008. Color4.prototype.scale = function (scale) {
  2009. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2010. };
  2011. /**
  2012. * Multiplies the current Color4 values by scale and stores the result in "result"
  2013. * @param scale defines the scaling factor to apply
  2014. * @param result defines the Color4 object where to store the result
  2015. * @returns the current unmodified Color4
  2016. */
  2017. Color4.prototype.scaleToRef = function (scale, result) {
  2018. result.r = this.r * scale;
  2019. result.g = this.g * scale;
  2020. result.b = this.b * scale;
  2021. result.a = this.a * scale;
  2022. return this;
  2023. };
  2024. /**
  2025. * Scale the current Color4 values by a factor and add the result to a given Color4
  2026. * @param scale defines the scale factor
  2027. * @param result defines the Color4 object where to store the result
  2028. * @returns the unmodified current Color4
  2029. */
  2030. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2031. result.r += this.r * scale;
  2032. result.g += this.g * scale;
  2033. result.b += this.b * scale;
  2034. result.a += this.a * scale;
  2035. return this;
  2036. };
  2037. /**
  2038. * Clamps the rgb values by the min and max values and stores the result into "result"
  2039. * @param min defines minimum clamping value (default is 0)
  2040. * @param max defines maximum clamping value (default is 1)
  2041. * @param result defines color to store the result into.
  2042. * @returns the cuurent Color4
  2043. */
  2044. Color4.prototype.clampToRef = function (min, max, result) {
  2045. if (min === void 0) { min = 0; }
  2046. if (max === void 0) { max = 1; }
  2047. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2048. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2049. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2050. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2051. return this;
  2052. };
  2053. /**
  2054. * Multipy an Color4 value by another and return a new Color4 object
  2055. * @param color defines the Color4 value to multiply by
  2056. * @returns a new Color4 object
  2057. */
  2058. Color4.prototype.multiply = function (color) {
  2059. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2060. };
  2061. /**
  2062. * Multipy a Color4 value by another and push the result in a reference value
  2063. * @param color defines the Color4 value to multiply by
  2064. * @param result defines the Color4 to fill the result in
  2065. * @returns the result Color4
  2066. */
  2067. Color4.prototype.multiplyToRef = function (color, result) {
  2068. result.r = this.r * color.r;
  2069. result.g = this.g * color.g;
  2070. result.b = this.b * color.b;
  2071. result.a = this.a * color.a;
  2072. return result;
  2073. };
  2074. /**
  2075. * Creates a string with the Color4 current values
  2076. * @returns the string representation of the Color4 object
  2077. */
  2078. Color4.prototype.toString = function () {
  2079. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2080. };
  2081. /**
  2082. * Returns the string "Color4"
  2083. * @returns "Color4"
  2084. */
  2085. Color4.prototype.getClassName = function () {
  2086. return "Color4";
  2087. };
  2088. /**
  2089. * Compute the Color4 hash code
  2090. * @returns an unique number that can be used to hash Color4 objects
  2091. */
  2092. Color4.prototype.getHashCode = function () {
  2093. var hash = this.r || 0;
  2094. hash = (hash * 397) ^ (this.g || 0);
  2095. hash = (hash * 397) ^ (this.b || 0);
  2096. hash = (hash * 397) ^ (this.a || 0);
  2097. return hash;
  2098. };
  2099. /**
  2100. * Creates a new Color4 copied from the current one
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.clone = function () {
  2104. return new Color4(this.r, this.g, this.b, this.a);
  2105. };
  2106. /**
  2107. * Copies the given Color4 values into the current one
  2108. * @param source defines the source Color4 object
  2109. * @returns the current updated Color4 object
  2110. */
  2111. Color4.prototype.copyFrom = function (source) {
  2112. this.r = source.r;
  2113. this.g = source.g;
  2114. this.b = source.b;
  2115. this.a = source.a;
  2116. return this;
  2117. };
  2118. /**
  2119. * Copies the given float values into the current one
  2120. * @param r defines the red component to read from
  2121. * @param g defines the green component to read from
  2122. * @param b defines the blue component to read from
  2123. * @param a defines the alpha component to read from
  2124. * @returns the current updated Color4 object
  2125. */
  2126. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2127. this.r = r;
  2128. this.g = g;
  2129. this.b = b;
  2130. this.a = a;
  2131. return this;
  2132. };
  2133. /**
  2134. * Copies the given float values into the current one
  2135. * @param r defines the red component to read from
  2136. * @param g defines the green component to read from
  2137. * @param b defines the blue component to read from
  2138. * @param a defines the alpha component to read from
  2139. * @returns the current updated Color4 object
  2140. */
  2141. Color4.prototype.set = function (r, g, b, a) {
  2142. return this.copyFromFloats(r, g, b, a);
  2143. };
  2144. /**
  2145. * Compute the Color4 hexadecimal code as a string
  2146. * @returns a string containing the hexadecimal representation of the Color4 object
  2147. */
  2148. Color4.prototype.toHexString = function () {
  2149. var intR = (this.r * 255) | 0;
  2150. var intG = (this.g * 255) | 0;
  2151. var intB = (this.b * 255) | 0;
  2152. var intA = (this.a * 255) | 0;
  2153. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2154. };
  2155. /**
  2156. * Computes a new Color4 converted from the current one to linear space
  2157. * @returns a new Color4 object
  2158. */
  2159. Color4.prototype.toLinearSpace = function () {
  2160. var convertedColor = new Color4();
  2161. this.toLinearSpaceToRef(convertedColor);
  2162. return convertedColor;
  2163. };
  2164. /**
  2165. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2166. * @param convertedColor defines the Color4 object where to store the linear space version
  2167. * @returns the unmodified Color4
  2168. */
  2169. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2170. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2171. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2172. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2173. convertedColor.a = this.a;
  2174. return this;
  2175. };
  2176. /**
  2177. * Computes a new Color4 converted from the current one to gamma space
  2178. * @returns a new Color4 object
  2179. */
  2180. Color4.prototype.toGammaSpace = function () {
  2181. var convertedColor = new Color4();
  2182. this.toGammaSpaceToRef(convertedColor);
  2183. return convertedColor;
  2184. };
  2185. /**
  2186. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2187. * @param convertedColor defines the Color4 object where to store the gamma space version
  2188. * @returns the unmodified Color4
  2189. */
  2190. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2191. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2192. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2193. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2194. convertedColor.a = this.a;
  2195. return this;
  2196. };
  2197. // Statics
  2198. /**
  2199. * Creates a new Color4 from the string containing valid hexadecimal values
  2200. * @param hex defines a string containing valid hexadecimal values
  2201. * @returns a new Color4 object
  2202. */
  2203. Color4.FromHexString = function (hex) {
  2204. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2205. return new Color4(0.0, 0.0, 0.0, 0.0);
  2206. }
  2207. var r = parseInt(hex.substring(1, 3), 16);
  2208. var g = parseInt(hex.substring(3, 5), 16);
  2209. var b = parseInt(hex.substring(5, 7), 16);
  2210. var a = parseInt(hex.substring(7, 9), 16);
  2211. return Color4.FromInts(r, g, b, a);
  2212. };
  2213. /**
  2214. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2215. * @param left defines the start value
  2216. * @param right defines the end value
  2217. * @param amount defines the gradient factor
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.Lerp = function (left, right, amount) {
  2221. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2222. Color4.LerpToRef(left, right, amount, result);
  2223. return result;
  2224. };
  2225. /**
  2226. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2227. * @param left defines the start value
  2228. * @param right defines the end value
  2229. * @param amount defines the gradient factor
  2230. * @param result defines the Color4 object where to store data
  2231. */
  2232. Color4.LerpToRef = function (left, right, amount, result) {
  2233. result.r = left.r + (right.r - left.r) * amount;
  2234. result.g = left.g + (right.g - left.g) * amount;
  2235. result.b = left.b + (right.b - left.b) * amount;
  2236. result.a = left.a + (right.a - left.a) * amount;
  2237. };
  2238. /**
  2239. * Creates a new Color4 from the starting index element of the given array
  2240. * @param array defines the source array to read from
  2241. * @param offset defines the offset in the source array
  2242. * @returns a new Color4 object
  2243. */
  2244. Color4.FromArray = function (array, offset) {
  2245. if (offset === void 0) { offset = 0; }
  2246. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2247. };
  2248. /**
  2249. * Creates a new Color3 from integer values (< 256)
  2250. * @param r defines the red component to read from (value between 0 and 255)
  2251. * @param g defines the green component to read from (value between 0 and 255)
  2252. * @param b defines the blue component to read from (value between 0 and 255)
  2253. * @param a defines the alpha component to read from (value between 0 and 255)
  2254. * @returns a new Color3 object
  2255. */
  2256. Color4.FromInts = function (r, g, b, a) {
  2257. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2258. };
  2259. /**
  2260. * Check the content of a given array and convert it to an array containing RGBA data
  2261. * If the original array was already containing count * 4 values then it is returned directly
  2262. * @param colors defines the array to check
  2263. * @param count defines the number of RGBA data to expect
  2264. * @returns an array containing count * 4 values (RGBA)
  2265. */
  2266. Color4.CheckColors4 = function (colors, count) {
  2267. // Check if color3 was used
  2268. if (colors.length === count * 3) {
  2269. var colors4 = [];
  2270. for (var index = 0; index < colors.length; index += 3) {
  2271. var newIndex = (index / 3) * 4;
  2272. colors4[newIndex] = colors[index];
  2273. colors4[newIndex + 1] = colors[index + 1];
  2274. colors4[newIndex + 2] = colors[index + 2];
  2275. colors4[newIndex + 3] = 1.0;
  2276. }
  2277. return colors4;
  2278. }
  2279. return colors;
  2280. };
  2281. return Color4;
  2282. }());
  2283. BABYLON.Color4 = Color4;
  2284. /**
  2285. * Class representing a vector containing 2 coordinates
  2286. */
  2287. var Vector2 = /** @class */ (function () {
  2288. /**
  2289. * Creates a new Vector2 from the given x and y coordinates
  2290. * @param x defines the first coordinate
  2291. * @param y defines the second coordinate
  2292. */
  2293. function Vector2(
  2294. /** defines the first coordinate */
  2295. x,
  2296. /** defines the second coordinate */
  2297. y) {
  2298. if (x === void 0) { x = 0; }
  2299. if (y === void 0) { y = 0; }
  2300. this.x = x;
  2301. this.y = y;
  2302. }
  2303. /**
  2304. * Gets a string with the Vector2 coordinates
  2305. * @returns a string with the Vector2 coordinates
  2306. */
  2307. Vector2.prototype.toString = function () {
  2308. return "{X: " + this.x + " Y:" + this.y + "}";
  2309. };
  2310. /**
  2311. * Gets class name
  2312. * @returns the string "Vector2"
  2313. */
  2314. Vector2.prototype.getClassName = function () {
  2315. return "Vector2";
  2316. };
  2317. /**
  2318. * Gets current vector hash code
  2319. * @returns the Vector2 hash code as a number
  2320. */
  2321. Vector2.prototype.getHashCode = function () {
  2322. var hash = this.x || 0;
  2323. hash = (hash * 397) ^ (this.y || 0);
  2324. return hash;
  2325. };
  2326. // Operators
  2327. /**
  2328. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2329. * @param array defines the source array
  2330. * @param index defines the offset in source array
  2331. * @returns the current Vector2
  2332. */
  2333. Vector2.prototype.toArray = function (array, index) {
  2334. if (index === void 0) { index = 0; }
  2335. array[index] = this.x;
  2336. array[index + 1] = this.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Copy the current vector to an array
  2341. * @returns a new array with 2 elements: the Vector2 coordinates.
  2342. */
  2343. Vector2.prototype.asArray = function () {
  2344. var result = new Array();
  2345. this.toArray(result, 0);
  2346. return result;
  2347. };
  2348. /**
  2349. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2350. * @param source defines the source Vector2
  2351. * @returns the current updated Vector2
  2352. */
  2353. Vector2.prototype.copyFrom = function (source) {
  2354. this.x = source.x;
  2355. this.y = source.y;
  2356. return this;
  2357. };
  2358. /**
  2359. * Sets the Vector2 coordinates with the given floats
  2360. * @param x defines the first coordinate
  2361. * @param y defines the second coordinate
  2362. * @returns the current updated Vector2
  2363. */
  2364. Vector2.prototype.copyFromFloats = function (x, y) {
  2365. this.x = x;
  2366. this.y = y;
  2367. return this;
  2368. };
  2369. /**
  2370. * Sets the Vector2 coordinates with the given floats
  2371. * @param x defines the first coordinate
  2372. * @param y defines the second coordinate
  2373. * @returns the current updated Vector2
  2374. */
  2375. Vector2.prototype.set = function (x, y) {
  2376. return this.copyFromFloats(x, y);
  2377. };
  2378. /**
  2379. * Add another vector with the current one
  2380. * @param otherVector defines the other vector
  2381. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2382. */
  2383. Vector2.prototype.add = function (otherVector) {
  2384. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2385. };
  2386. /**
  2387. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2388. * @param otherVector defines the other vector
  2389. * @param result defines the target vector
  2390. * @returns the unmodified current Vector2
  2391. */
  2392. Vector2.prototype.addToRef = function (otherVector, result) {
  2393. result.x = this.x + otherVector.x;
  2394. result.y = this.y + otherVector.y;
  2395. return this;
  2396. };
  2397. /**
  2398. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2399. * @param otherVector defines the other vector
  2400. * @returns the current updated Vector2
  2401. */
  2402. Vector2.prototype.addInPlace = function (otherVector) {
  2403. this.x += otherVector.x;
  2404. this.y += otherVector.y;
  2405. return this;
  2406. };
  2407. /**
  2408. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2409. * @param otherVector defines the other vector
  2410. * @returns a new Vector2
  2411. */
  2412. Vector2.prototype.addVector3 = function (otherVector) {
  2413. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2414. };
  2415. /**
  2416. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2417. * @param otherVector defines the other vector
  2418. * @returns a new Vector2
  2419. */
  2420. Vector2.prototype.subtract = function (otherVector) {
  2421. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2422. };
  2423. /**
  2424. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2425. * @param otherVector defines the other vector
  2426. * @param result defines the target vector
  2427. * @returns the unmodified current Vector2
  2428. */
  2429. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2430. result.x = this.x - otherVector.x;
  2431. result.y = this.y - otherVector.y;
  2432. return this;
  2433. };
  2434. /**
  2435. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2436. * @param otherVector defines the other vector
  2437. * @returns the current updated Vector2
  2438. */
  2439. Vector2.prototype.subtractInPlace = function (otherVector) {
  2440. this.x -= otherVector.x;
  2441. this.y -= otherVector.y;
  2442. return this;
  2443. };
  2444. /**
  2445. * Multiplies in place the current Vector2 coordinates by the given ones
  2446. * @param otherVector defines the other vector
  2447. * @returns the current updated Vector2
  2448. */
  2449. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2450. this.x *= otherVector.x;
  2451. this.y *= otherVector.y;
  2452. return this;
  2453. };
  2454. /**
  2455. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2456. * @param otherVector defines the other vector
  2457. * @returns a new Vector2
  2458. */
  2459. Vector2.prototype.multiply = function (otherVector) {
  2460. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2461. };
  2462. /**
  2463. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2464. * @param otherVector defines the other vector
  2465. * @param result defines the target vector
  2466. * @returns the unmodified current Vector2
  2467. */
  2468. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2469. result.x = this.x * otherVector.x;
  2470. result.y = this.y * otherVector.y;
  2471. return this;
  2472. };
  2473. /**
  2474. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2475. * @param x defines the first coordinate
  2476. * @param y defines the second coordinate
  2477. * @returns a new Vector2
  2478. */
  2479. Vector2.prototype.multiplyByFloats = function (x, y) {
  2480. return new Vector2(this.x * x, this.y * y);
  2481. };
  2482. /**
  2483. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2484. * @param otherVector defines the other vector
  2485. * @returns a new Vector2
  2486. */
  2487. Vector2.prototype.divide = function (otherVector) {
  2488. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2489. };
  2490. /**
  2491. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2492. * @param otherVector defines the other vector
  2493. * @param result defines the target vector
  2494. * @returns the unmodified current Vector2
  2495. */
  2496. Vector2.prototype.divideToRef = function (otherVector, result) {
  2497. result.x = this.x / otherVector.x;
  2498. result.y = this.y / otherVector.y;
  2499. return this;
  2500. };
  2501. /**
  2502. * Divides the current Vector3 coordinates by the given ones
  2503. * @param otherVector defines the other vector
  2504. * @returns the current updated Vector2
  2505. */
  2506. Vector2.prototype.divideInPlace = function (otherVector) {
  2507. return this.divideToRef(otherVector, this);
  2508. };
  2509. /**
  2510. * Gets a new Vector2 with current Vector2 negated coordinates
  2511. * @returns a new Vector2
  2512. */
  2513. Vector2.prototype.negate = function () {
  2514. return new Vector2(-this.x, -this.y);
  2515. };
  2516. /**
  2517. * Multiply the Vector2 coordinates by scale
  2518. * @param scale defines the scaling factor
  2519. * @returns the current updated Vector2
  2520. */
  2521. Vector2.prototype.scaleInPlace = function (scale) {
  2522. this.x *= scale;
  2523. this.y *= scale;
  2524. return this;
  2525. };
  2526. /**
  2527. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2528. * @param scale defines the scaling factor
  2529. * @returns a new Vector2
  2530. */
  2531. Vector2.prototype.scale = function (scale) {
  2532. var result = new Vector2(0, 0);
  2533. this.scaleToRef(scale, result);
  2534. return result;
  2535. };
  2536. /**
  2537. * Scale the current Vector2 values by a factor to a given Vector2
  2538. * @param scale defines the scale factor
  2539. * @param result defines the Vector2 object where to store the result
  2540. * @returns the unmodified current Vector2
  2541. */
  2542. Vector2.prototype.scaleToRef = function (scale, result) {
  2543. result.x = this.x * scale;
  2544. result.y = this.y * scale;
  2545. return this;
  2546. };
  2547. /**
  2548. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2549. * @param scale defines the scale factor
  2550. * @param result defines the Vector2 object where to store the result
  2551. * @returns the unmodified current Vector2
  2552. */
  2553. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2554. result.x += this.x * scale;
  2555. result.y += this.y * scale;
  2556. return this;
  2557. };
  2558. /**
  2559. * Gets a boolean if two vectors are equals
  2560. * @param otherVector defines the other vector
  2561. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2562. */
  2563. Vector2.prototype.equals = function (otherVector) {
  2564. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2565. };
  2566. /**
  2567. * Gets a boolean if two vectors are equals (using an epsilon value)
  2568. * @param otherVector defines the other vector
  2569. * @param epsilon defines the minimal distance to consider equality
  2570. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2571. */
  2572. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2573. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2574. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2575. };
  2576. // Properties
  2577. /**
  2578. * Gets the length of the vector
  2579. * @returns the vector length (float)
  2580. */
  2581. Vector2.prototype.length = function () {
  2582. return Math.sqrt(this.x * this.x + this.y * this.y);
  2583. };
  2584. /**
  2585. * Gets the vector squared length
  2586. * @returns the vector squared length (float)
  2587. */
  2588. Vector2.prototype.lengthSquared = function () {
  2589. return (this.x * this.x + this.y * this.y);
  2590. };
  2591. // Methods
  2592. /**
  2593. * Normalize the vector
  2594. * @returns the current updated Vector2
  2595. */
  2596. Vector2.prototype.normalize = function () {
  2597. var len = this.length();
  2598. if (len === 0)
  2599. return this;
  2600. var num = 1.0 / len;
  2601. this.x *= num;
  2602. this.y *= num;
  2603. return this;
  2604. };
  2605. /**
  2606. * Gets a new Vector2 copied from the Vector2
  2607. * @returns a new Vector2
  2608. */
  2609. Vector2.prototype.clone = function () {
  2610. return new Vector2(this.x, this.y);
  2611. };
  2612. // Statics
  2613. /**
  2614. * Gets a new Vector2(0, 0)
  2615. * @returns a new Vector2
  2616. */
  2617. Vector2.Zero = function () {
  2618. return new Vector2(0, 0);
  2619. };
  2620. /**
  2621. * Gets a new Vector2(1, 1)
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.One = function () {
  2625. return new Vector2(1, 1);
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set from the given index element of the given array
  2629. * @param array defines the data source
  2630. * @param offset defines the offset in the data source
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.FromArray = function (array, offset) {
  2634. if (offset === void 0) { offset = 0; }
  2635. return new Vector2(array[offset], array[offset + 1]);
  2636. };
  2637. /**
  2638. * Sets "result" from the given index element of the given array
  2639. * @param array defines the data source
  2640. * @param offset defines the offset in the data source
  2641. * @param result defines the target vector
  2642. */
  2643. Vector2.FromArrayToRef = function (array, offset, result) {
  2644. result.x = array[offset];
  2645. result.y = array[offset + 1];
  2646. };
  2647. /**
  2648. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2649. * @param value1 defines 1st point of control
  2650. * @param value2 defines 2nd point of control
  2651. * @param value3 defines 3rd point of control
  2652. * @param value4 defines 4th point of control
  2653. * @param amount defines the interpolation factor
  2654. * @returns a new Vector2
  2655. */
  2656. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2657. var squared = amount * amount;
  2658. var cubed = amount * squared;
  2659. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2660. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2661. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2662. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2663. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2664. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2669. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2670. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2671. * @param value defines the value to clamp
  2672. * @param min defines the lower limit
  2673. * @param max defines the upper limit
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Clamp = function (value, min, max) {
  2677. var x = value.x;
  2678. x = (x > max.x) ? max.x : x;
  2679. x = (x < min.x) ? min.x : x;
  2680. var y = value.y;
  2681. y = (y > max.y) ? max.y : y;
  2682. y = (y < min.y) ? min.y : y;
  2683. return new Vector2(x, y);
  2684. };
  2685. /**
  2686. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2687. * @param value1 defines the 1st control point
  2688. * @param tangent1 defines the outgoing tangent
  2689. * @param value2 defines the 2nd control point
  2690. * @param tangent2 defines the incoming tangent
  2691. * @param amount defines the interpolation factor
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2695. var squared = amount * amount;
  2696. var cubed = amount * squared;
  2697. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2698. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2699. var part3 = (cubed - (2.0 * squared)) + amount;
  2700. var part4 = cubed - squared;
  2701. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2702. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2707. * @param start defines the start vector
  2708. * @param end defines the end vector
  2709. * @param amount defines the interpolation factor
  2710. * @returns a new Vector2
  2711. */
  2712. Vector2.Lerp = function (start, end, amount) {
  2713. var x = start.x + ((end.x - start.x) * amount);
  2714. var y = start.y + ((end.y - start.y) * amount);
  2715. return new Vector2(x, y);
  2716. };
  2717. /**
  2718. * Gets the dot product of the vector "left" and the vector "right"
  2719. * @param left defines first vector
  2720. * @param right defines second vector
  2721. * @returns the dot product (float)
  2722. */
  2723. Vector2.Dot = function (left, right) {
  2724. return left.x * right.x + left.y * right.y;
  2725. };
  2726. /**
  2727. * Returns a new Vector2 equal to the normalized given vector
  2728. * @param vector defines the vector to normalize
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Normalize = function (vector) {
  2732. var newVector = vector.clone();
  2733. newVector.normalize();
  2734. return newVector;
  2735. };
  2736. /**
  2737. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2738. * @param left defines 1st vector
  2739. * @param right defines 2nd vector
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Minimize = function (left, right) {
  2743. var x = (left.x < right.x) ? left.x : right.x;
  2744. var y = (left.y < right.y) ? left.y : right.y;
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2749. * @param left defines 1st vector
  2750. * @param right defines 2nd vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Maximize = function (left, right) {
  2754. var x = (left.x > right.x) ? left.x : right.x;
  2755. var y = (left.y > right.y) ? left.y : right.y;
  2756. return new Vector2(x, y);
  2757. };
  2758. /**
  2759. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2760. * @param vector defines the vector to transform
  2761. * @param transformation defines the matrix to apply
  2762. * @returns a new Vector2
  2763. */
  2764. Vector2.Transform = function (vector, transformation) {
  2765. var r = Vector2.Zero();
  2766. Vector2.TransformToRef(vector, transformation, r);
  2767. return r;
  2768. };
  2769. /**
  2770. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2771. * @param vector defines the vector to transform
  2772. * @param transformation defines the matrix to apply
  2773. * @param result defines the target vector
  2774. */
  2775. Vector2.TransformToRef = function (vector, transformation, result) {
  2776. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2777. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2778. result.x = x;
  2779. result.y = y;
  2780. };
  2781. /**
  2782. * Determines if a given vector is included in a triangle
  2783. * @param p defines the vector to test
  2784. * @param p0 defines 1st triangle point
  2785. * @param p1 defines 2nd triangle point
  2786. * @param p2 defines 3rd triangle point
  2787. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2788. */
  2789. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2790. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2791. var sign = a < 0 ? -1 : 1;
  2792. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2793. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2794. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2795. };
  2796. /**
  2797. * Gets the distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the distance between vectors
  2801. */
  2802. Vector2.Distance = function (value1, value2) {
  2803. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2804. };
  2805. /**
  2806. * Returns the squared distance between the vectors "value1" and "value2"
  2807. * @param value1 defines first vector
  2808. * @param value2 defines second vector
  2809. * @returns the squared distance between vectors
  2810. */
  2811. Vector2.DistanceSquared = function (value1, value2) {
  2812. var x = value1.x - value2.x;
  2813. var y = value1.y - value2.y;
  2814. return (x * x) + (y * y);
  2815. };
  2816. /**
  2817. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2818. * @param value1 defines first vector
  2819. * @param value2 defines second vector
  2820. * @returns a new Vector2
  2821. */
  2822. Vector2.Center = function (value1, value2) {
  2823. var center = value1.add(value2);
  2824. center.scaleInPlace(0.5);
  2825. return center;
  2826. };
  2827. /**
  2828. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2829. * @param p defines the middle point
  2830. * @param segA defines one point of the segment
  2831. * @param segB defines the other point of the segment
  2832. * @returns the shortest distance
  2833. */
  2834. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2835. var l2 = Vector2.DistanceSquared(segA, segB);
  2836. if (l2 === 0.0) {
  2837. return Vector2.Distance(p, segA);
  2838. }
  2839. var v = segB.subtract(segA);
  2840. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2841. var proj = segA.add(v.multiplyByFloats(t, t));
  2842. return Vector2.Distance(p, proj);
  2843. };
  2844. return Vector2;
  2845. }());
  2846. BABYLON.Vector2 = Vector2;
  2847. /**
  2848. * Classed used to store (x,y,z) vector representation
  2849. * A Vector3 is the main object used in 3D geometry
  2850. * It can represent etiher the coordinates of a point the space, either a direction
  2851. * Reminder: Babylon.js uses a left handed forward facing system
  2852. */
  2853. var Vector3 = /** @class */ (function () {
  2854. /**
  2855. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2856. * @param x defines the first coordinates (on X axis)
  2857. * @param y defines the second coordinates (on Y axis)
  2858. * @param z defines the third coordinates (on Z axis)
  2859. */
  2860. function Vector3(
  2861. /**
  2862. * Defines the first coordinates (on X axis)
  2863. */
  2864. x,
  2865. /**
  2866. * Defines the second coordinates (on Y axis)
  2867. */
  2868. y,
  2869. /**
  2870. * Defines the third coordinates (on Z axis)
  2871. */
  2872. z) {
  2873. if (x === void 0) { x = 0; }
  2874. if (y === void 0) { y = 0; }
  2875. if (z === void 0) { z = 0; }
  2876. this.x = x;
  2877. this.y = y;
  2878. this.z = z;
  2879. }
  2880. /**
  2881. * Creates a string representation of the Vector3
  2882. * @returns a string with the Vector3 coordinates.
  2883. */
  2884. Vector3.prototype.toString = function () {
  2885. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2886. };
  2887. /**
  2888. * Gets the class name
  2889. * @returns the string "Vector3"
  2890. */
  2891. Vector3.prototype.getClassName = function () {
  2892. return "Vector3";
  2893. };
  2894. /**
  2895. * Creates the Vector3 hash code
  2896. * @returns a number which tends to be unique between Vector3 instances
  2897. */
  2898. Vector3.prototype.getHashCode = function () {
  2899. var hash = this.x || 0;
  2900. hash = (hash * 397) ^ (this.y || 0);
  2901. hash = (hash * 397) ^ (this.z || 0);
  2902. return hash;
  2903. };
  2904. // Operators
  2905. /**
  2906. * Creates an array containing three elements : the coordinates of the Vector3
  2907. * @returns a new array of numbers
  2908. */
  2909. Vector3.prototype.asArray = function () {
  2910. var result = [];
  2911. this.toArray(result, 0);
  2912. return result;
  2913. };
  2914. /**
  2915. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2916. * @param array defines the destination array
  2917. * @param index defines the offset in the destination array
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.toArray = function (array, index) {
  2921. if (index === void 0) { index = 0; }
  2922. array[index] = this.x;
  2923. array[index + 1] = this.y;
  2924. array[index + 2] = this.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2929. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2930. */
  2931. Vector3.prototype.toQuaternion = function () {
  2932. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2933. };
  2934. /**
  2935. * Adds the given vector to the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.addInPlace = function (otherVector) {
  2940. this.x += otherVector.x;
  2941. this.y += otherVector.y;
  2942. this.z += otherVector.z;
  2943. return this;
  2944. };
  2945. /**
  2946. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2947. * @param otherVector defines the second operand
  2948. * @returns the resulting Vector3
  2949. */
  2950. Vector3.prototype.add = function (otherVector) {
  2951. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2952. };
  2953. /**
  2954. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2955. * @param otherVector defines the second operand
  2956. * @param result defines the Vector3 object where to store the result
  2957. * @returns the current Vector3
  2958. */
  2959. Vector3.prototype.addToRef = function (otherVector, result) {
  2960. result.x = this.x + otherVector.x;
  2961. result.y = this.y + otherVector.y;
  2962. result.z = this.z + otherVector.z;
  2963. return this;
  2964. };
  2965. /**
  2966. * Subtract the given vector from the current Vector3
  2967. * @param otherVector defines the second operand
  2968. * @returns the current updated Vector3
  2969. */
  2970. Vector3.prototype.subtractInPlace = function (otherVector) {
  2971. this.x -= otherVector.x;
  2972. this.y -= otherVector.y;
  2973. this.z -= otherVector.z;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2978. * @param otherVector defines the second operand
  2979. * @returns the resulting Vector3
  2980. */
  2981. Vector3.prototype.subtract = function (otherVector) {
  2982. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2983. };
  2984. /**
  2985. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2986. * @param otherVector defines the second operand
  2987. * @param result defines the Vector3 object where to store the result
  2988. * @returns the current Vector3
  2989. */
  2990. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2991. result.x = this.x - otherVector.x;
  2992. result.y = this.y - otherVector.y;
  2993. result.z = this.z - otherVector.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the resulting Vector3
  3002. */
  3003. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3004. return new Vector3(this.x - x, this.y - y, this.z - z);
  3005. };
  3006. /**
  3007. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3015. result.x = this.x - x;
  3016. result.y = this.y - y;
  3017. result.z = this.z - z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3022. * @returns a new Vector3
  3023. */
  3024. Vector3.prototype.negate = function () {
  3025. return new Vector3(-this.x, -this.y, -this.z);
  3026. };
  3027. /**
  3028. * Multiplies the Vector3 coordinates by the float "scale"
  3029. * @param scale defines the multiplier factor
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.scaleInPlace = function (scale) {
  3033. this.x *= scale;
  3034. this.y *= scale;
  3035. this.z *= scale;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3040. * @param scale defines the multiplier factor
  3041. * @returns a new Vector3
  3042. */
  3043. Vector3.prototype.scale = function (scale) {
  3044. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3045. };
  3046. /**
  3047. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3048. * @param scale defines the multiplier factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the current Vector3
  3051. */
  3052. Vector3.prototype.scaleToRef = function (scale, result) {
  3053. result.x = this.x * scale;
  3054. result.y = this.y * scale;
  3055. result.z = this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3060. * @param scale defines the scale factor
  3061. * @param result defines the Vector3 object where to store the result
  3062. * @returns the unmodified current Vector3
  3063. */
  3064. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3065. result.x += this.x * scale;
  3066. result.y += this.y * scale;
  3067. result.z += this.z * scale;
  3068. return this;
  3069. };
  3070. /**
  3071. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3072. * @param otherVector defines the second operand
  3073. * @returns true if both vectors are equals
  3074. */
  3075. Vector3.prototype.equals = function (otherVector) {
  3076. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3077. };
  3078. /**
  3079. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3080. * @param otherVector defines the second operand
  3081. * @param epsilon defines the minimal distance to define values as equals
  3082. * @returns true if both vectors are distant less than epsilon
  3083. */
  3084. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3085. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3086. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3087. };
  3088. /**
  3089. * Returns true if the current Vector3 coordinates equals the given floats
  3090. * @param x defines the x coordinate of the operand
  3091. * @param y defines the y coordinate of the operand
  3092. * @param z defines the z coordinate of the operand
  3093. * @returns true if both vectors are equals
  3094. */
  3095. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3096. return this.x === x && this.y === y && this.z === z;
  3097. };
  3098. /**
  3099. * Multiplies the current Vector3 coordinates by the given ones
  3100. * @param otherVector defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3104. this.x *= otherVector.x;
  3105. this.y *= otherVector.y;
  3106. this.z *= otherVector.z;
  3107. return this;
  3108. };
  3109. /**
  3110. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3111. * @param otherVector defines the second operand
  3112. * @returns the new Vector3
  3113. */
  3114. Vector3.prototype.multiply = function (otherVector) {
  3115. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3116. };
  3117. /**
  3118. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3119. * @param otherVector defines the second operand
  3120. * @param result defines the Vector3 object where to store the result
  3121. * @returns the current Vector3
  3122. */
  3123. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3124. result.x = this.x * otherVector.x;
  3125. result.y = this.y * otherVector.y;
  3126. result.z = this.z * otherVector.z;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3131. * @param x defines the x coordinate of the operand
  3132. * @param y defines the y coordinate of the operand
  3133. * @param z defines the z coordinate of the operand
  3134. * @returns the new Vector3
  3135. */
  3136. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3137. return new Vector3(this.x * x, this.y * y, this.z * z);
  3138. };
  3139. /**
  3140. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.divide = function (otherVector) {
  3145. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.divideToRef = function (otherVector, result) {
  3154. result.x = this.x / otherVector.x;
  3155. result.y = this.y / otherVector.y;
  3156. result.z = this.z / otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Divides the current Vector3 coordinates by the given ones.
  3161. * @param otherVector defines the second operand
  3162. * @returns the current updated Vector3
  3163. */
  3164. Vector3.prototype.divideInPlace = function (otherVector) {
  3165. return this.divideToRef(otherVector, this);
  3166. };
  3167. /**
  3168. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3169. * @param other defines the second operand
  3170. * @returns the current updated Vector3
  3171. */
  3172. Vector3.prototype.minimizeInPlace = function (other) {
  3173. if (other.x < this.x)
  3174. this.x = other.x;
  3175. if (other.y < this.y)
  3176. this.y = other.y;
  3177. if (other.z < this.z)
  3178. this.z = other.z;
  3179. return this;
  3180. };
  3181. /**
  3182. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3183. * @param other defines the second operand
  3184. * @returns the current updated Vector3
  3185. */
  3186. Vector3.prototype.maximizeInPlace = function (other) {
  3187. if (other.x > this.x)
  3188. this.x = other.x;
  3189. if (other.y > this.y)
  3190. this.y = other.y;
  3191. if (other.z > this.z)
  3192. this.z = other.z;
  3193. return this;
  3194. };
  3195. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3196. /**
  3197. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3198. */
  3199. get: function () {
  3200. var absX = Math.abs(this.x);
  3201. var absY = Math.abs(this.y);
  3202. if (absX !== absY) {
  3203. return true;
  3204. }
  3205. var absZ = Math.abs(this.z);
  3206. if (absX !== absZ) {
  3207. return true;
  3208. }
  3209. if (absY !== absZ) {
  3210. return true;
  3211. }
  3212. return false;
  3213. },
  3214. enumerable: true,
  3215. configurable: true
  3216. });
  3217. // Properties
  3218. /**
  3219. * Gets the length of the Vector3
  3220. * @returns the length of the Vecto3
  3221. */
  3222. Vector3.prototype.length = function () {
  3223. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3224. };
  3225. /**
  3226. * Gets the squared length of the Vector3
  3227. * @returns squared length of the Vector3
  3228. */
  3229. Vector3.prototype.lengthSquared = function () {
  3230. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3231. };
  3232. /**
  3233. * Normalize the current Vector3.
  3234. * Please note that this is an in place operation.
  3235. * @returns the current updated Vector3
  3236. */
  3237. Vector3.prototype.normalize = function () {
  3238. var len = this.length();
  3239. if (len === 0 || len === 1.0)
  3240. return this;
  3241. var num = 1.0 / len;
  3242. this.x *= num;
  3243. this.y *= num;
  3244. this.z *= num;
  3245. return this;
  3246. };
  3247. /**
  3248. * Normalize the current Vector3 to a new vector
  3249. * @returns the new Vector3
  3250. */
  3251. Vector3.prototype.normalizeToNew = function () {
  3252. var normalized = new Vector3(0, 0, 0);
  3253. this.normalizeToRef(normalized);
  3254. return normalized;
  3255. };
  3256. /**
  3257. * Normalize the current Vector3 to the reference
  3258. * @param reference define the Vector3 to update
  3259. * @returns the updated Vector3
  3260. */
  3261. Vector3.prototype.normalizeToRef = function (reference) {
  3262. var len = this.length();
  3263. if (len === 0 || len === 1.0) {
  3264. reference.set(this.x, this.y, this.z);
  3265. return reference;
  3266. }
  3267. var scale = 1.0 / len;
  3268. this.scaleToRef(scale, reference);
  3269. return reference;
  3270. };
  3271. /**
  3272. * Creates a new Vector3 copied from the current Vector3
  3273. * @returns the new Vector3
  3274. */
  3275. Vector3.prototype.clone = function () {
  3276. return new Vector3(this.x, this.y, this.z);
  3277. };
  3278. /**
  3279. * Copies the given vector coordinates to the current Vector3 ones
  3280. * @param source defines the source Vector3
  3281. * @returns the current updated Vector3
  3282. */
  3283. Vector3.prototype.copyFrom = function (source) {
  3284. this.x = source.x;
  3285. this.y = source.y;
  3286. this.z = source.z;
  3287. return this;
  3288. };
  3289. /**
  3290. * Copies the given floats to the current Vector3 coordinates
  3291. * @param x defines the x coordinate of the operand
  3292. * @param y defines the y coordinate of the operand
  3293. * @param z defines the z coordinate of the operand
  3294. * @returns the current updated Vector3
  3295. */
  3296. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3297. this.x = x;
  3298. this.y = y;
  3299. this.z = z;
  3300. return this;
  3301. };
  3302. /**
  3303. * Copies the given floats to the current Vector3 coordinates
  3304. * @param x defines the x coordinate of the operand
  3305. * @param y defines the y coordinate of the operand
  3306. * @param z defines the z coordinate of the operand
  3307. * @returns the current updated Vector3
  3308. */
  3309. Vector3.prototype.set = function (x, y, z) {
  3310. return this.copyFromFloats(x, y, z);
  3311. };
  3312. // Statics
  3313. /**
  3314. * Get the clip factor between two vectors
  3315. * @param vector0 defines the first operand
  3316. * @param vector1 defines the second operand
  3317. * @param axis defines the axis to use
  3318. * @param size defines the size along the axis
  3319. * @returns the clip factor
  3320. */
  3321. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3322. var d0 = Vector3.Dot(vector0, axis) - size;
  3323. var d1 = Vector3.Dot(vector1, axis) - size;
  3324. var s = d0 / (d0 - d1);
  3325. return s;
  3326. };
  3327. /**
  3328. * Get angle between two vectors
  3329. * @param vector0 angle between vector0 and vector1
  3330. * @param vector1 angle between vector0 and vector1
  3331. * @param normal direction of the normal
  3332. * @return the angle between vector0 and vector1
  3333. */
  3334. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3335. var v0 = vector0.clone().normalize();
  3336. var v1 = vector1.clone().normalize();
  3337. var dot = Vector3.Dot(v0, v1);
  3338. var n = Vector3.Cross(v0, v1);
  3339. if (Vector3.Dot(n, normal) > 0) {
  3340. return Math.acos(dot);
  3341. }
  3342. return -Math.acos(dot);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set from the index "offset" of the given array
  3346. * @param array defines the source array
  3347. * @param offset defines the offset in the source array
  3348. * @returns the new Vector3
  3349. */
  3350. Vector3.FromArray = function (array, offset) {
  3351. if (!offset) {
  3352. offset = 0;
  3353. }
  3354. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3355. };
  3356. /**
  3357. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3358. * This function is deprecated. Use FromArray instead
  3359. * @param array defines the source array
  3360. * @param offset defines the offset in the source array
  3361. * @returns the new Vector3
  3362. */
  3363. Vector3.FromFloatArray = function (array, offset) {
  3364. return Vector3.FromArray(array, offset);
  3365. };
  3366. /**
  3367. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3368. * @param array defines the source array
  3369. * @param offset defines the offset in the source array
  3370. * @param result defines the Vector3 where to store the result
  3371. */
  3372. Vector3.FromArrayToRef = function (array, offset, result) {
  3373. result.x = array[offset];
  3374. result.y = array[offset + 1];
  3375. result.z = array[offset + 2];
  3376. };
  3377. /**
  3378. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3379. * This function is deprecated. Use FromArrayToRef instead.
  3380. * @param array defines the source array
  3381. * @param offset defines the offset in the source array
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3385. return Vector3.FromArrayToRef(array, offset, result);
  3386. };
  3387. /**
  3388. * Sets the given vector "result" with the given floats.
  3389. * @param x defines the x coordinate of the source
  3390. * @param y defines the y coordinate of the source
  3391. * @param z defines the z coordinate of the source
  3392. * @param result defines the Vector3 where to store the result
  3393. */
  3394. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3395. result.x = x;
  3396. result.y = y;
  3397. result.z = z;
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3401. * @returns a new empty Vector3
  3402. */
  3403. Vector3.Zero = function () {
  3404. return new Vector3(0.0, 0.0, 0.0);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3408. * @returns a new unit Vector3
  3409. */
  3410. Vector3.One = function () {
  3411. return new Vector3(1.0, 1.0, 1.0);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3415. * @returns a new up Vector3
  3416. */
  3417. Vector3.Up = function () {
  3418. return new Vector3(0.0, 1.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3422. * @returns a new down Vector3
  3423. */
  3424. Vector3.Down = function () {
  3425. return new Vector3(0.0, -1.0, 0.0);
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3429. * @returns a new forward Vector3
  3430. */
  3431. Vector3.Forward = function () {
  3432. return new Vector3(0.0, 0.0, 1.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3436. * @returns a new right Vector3
  3437. */
  3438. Vector3.Right = function () {
  3439. return new Vector3(1.0, 0.0, 0.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3443. * @returns a new left Vector3
  3444. */
  3445. Vector3.Left = function () {
  3446. return new Vector3(-1.0, 0.0, 0.0);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3450. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3451. * @param vector defines the Vector3 to transform
  3452. * @param transformation defines the transformation matrix
  3453. * @returns the transformed Vector3
  3454. */
  3455. Vector3.TransformCoordinates = function (vector, transformation) {
  3456. var result = Vector3.Zero();
  3457. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3458. return result;
  3459. };
  3460. /**
  3461. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3462. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3463. * @param vector defines the Vector3 to transform
  3464. * @param transformation defines the transformation matrix
  3465. * @param result defines the Vector3 where to store the result
  3466. */
  3467. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3468. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3469. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3470. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3471. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3472. result.x = x / w;
  3473. result.y = y / w;
  3474. result.z = z / w;
  3475. };
  3476. /**
  3477. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3478. * This method computes tranformed coordinates only, not transformed direction vectors
  3479. * @param x define the x coordinate of the source vector
  3480. * @param y define the y coordinate of the source vector
  3481. * @param z define the z coordinate of the source vector
  3482. * @param transformation defines the transformation matrix
  3483. * @param result defines the Vector3 where to store the result
  3484. */
  3485. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3486. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3487. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3488. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3489. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3490. result.x = rx / rw;
  3491. result.y = ry / rw;
  3492. result.z = rz / rw;
  3493. };
  3494. /**
  3495. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3496. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3497. * @param vector defines the Vector3 to transform
  3498. * @param transformation defines the transformation matrix
  3499. * @returns the new Vector3
  3500. */
  3501. Vector3.TransformNormal = function (vector, transformation) {
  3502. var result = Vector3.Zero();
  3503. Vector3.TransformNormalToRef(vector, transformation, result);
  3504. return result;
  3505. };
  3506. /**
  3507. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3508. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3509. * @param vector defines the Vector3 to transform
  3510. * @param transformation defines the transformation matrix
  3511. * @param result defines the Vector3 where to store the result
  3512. */
  3513. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3514. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3515. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3516. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3517. result.x = x;
  3518. result.y = y;
  3519. result.z = z;
  3520. };
  3521. /**
  3522. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3523. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3524. * @param x define the x coordinate of the source vector
  3525. * @param y define the y coordinate of the source vector
  3526. * @param z define the z coordinate of the source vector
  3527. * @param transformation defines the transformation matrix
  3528. * @param result defines the Vector3 where to store the result
  3529. */
  3530. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3531. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3532. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3533. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3534. };
  3535. /**
  3536. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3537. * @param value1 defines the first control point
  3538. * @param value2 defines the second control point
  3539. * @param value3 defines the third control point
  3540. * @param value4 defines the fourth control point
  3541. * @param amount defines the amount on the spline to use
  3542. * @returns the new Vector3
  3543. */
  3544. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3545. var squared = amount * amount;
  3546. var cubed = amount * squared;
  3547. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3548. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3549. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3550. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3551. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3552. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3553. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3554. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3555. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3556. return new Vector3(x, y, z);
  3557. };
  3558. /**
  3559. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3560. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3561. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3562. * @param value defines the current value
  3563. * @param min defines the lower range value
  3564. * @param max defines the upper range value
  3565. * @returns the new Vector3
  3566. */
  3567. Vector3.Clamp = function (value, min, max) {
  3568. var x = value.x;
  3569. x = (x > max.x) ? max.x : x;
  3570. x = (x < min.x) ? min.x : x;
  3571. var y = value.y;
  3572. y = (y > max.y) ? max.y : y;
  3573. y = (y < min.y) ? min.y : y;
  3574. var z = value.z;
  3575. z = (z > max.z) ? max.z : z;
  3576. z = (z < min.z) ? min.z : z;
  3577. return new Vector3(x, y, z);
  3578. };
  3579. /**
  3580. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3581. * @param value1 defines the first control point
  3582. * @param tangent1 defines the first tangent vector
  3583. * @param value2 defines the second control point
  3584. * @param tangent2 defines the second tangent vector
  3585. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3586. * @returns the new Vector3
  3587. */
  3588. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3589. var squared = amount * amount;
  3590. var cubed = amount * squared;
  3591. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3592. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3593. var part3 = (cubed - (2.0 * squared)) + amount;
  3594. var part4 = cubed - squared;
  3595. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3596. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3597. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3598. return new Vector3(x, y, z);
  3599. };
  3600. /**
  3601. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3602. * @param start defines the start value
  3603. * @param end defines the end value
  3604. * @param amount max defines amount between both (between 0 and 1)
  3605. * @returns the new Vector3
  3606. */
  3607. Vector3.Lerp = function (start, end, amount) {
  3608. var result = new Vector3(0, 0, 0);
  3609. Vector3.LerpToRef(start, end, amount, result);
  3610. return result;
  3611. };
  3612. /**
  3613. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3614. * @param start defines the start value
  3615. * @param end defines the end value
  3616. * @param amount max defines amount between both (between 0 and 1)
  3617. * @param result defines the Vector3 where to store the result
  3618. */
  3619. Vector3.LerpToRef = function (start, end, amount, result) {
  3620. result.x = start.x + ((end.x - start.x) * amount);
  3621. result.y = start.y + ((end.y - start.y) * amount);
  3622. result.z = start.z + ((end.z - start.z) * amount);
  3623. };
  3624. /**
  3625. * Returns the dot product (float) between the vectors "left" and "right"
  3626. * @param left defines the left operand
  3627. * @param right defines the right operand
  3628. * @returns the dot product
  3629. */
  3630. Vector3.Dot = function (left, right) {
  3631. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3632. };
  3633. /**
  3634. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3635. * The cross product is then orthogonal to both "left" and "right"
  3636. * @param left defines the left operand
  3637. * @param right defines the right operand
  3638. * @returns the cross product
  3639. */
  3640. Vector3.Cross = function (left, right) {
  3641. var result = Vector3.Zero();
  3642. Vector3.CrossToRef(left, right, result);
  3643. return result;
  3644. };
  3645. /**
  3646. * Sets the given vector "result" with the cross product of "left" and "right"
  3647. * The cross product is then orthogonal to both "left" and "right"
  3648. * @param left defines the left operand
  3649. * @param right defines the right operand
  3650. * @param result defines the Vector3 where to store the result
  3651. */
  3652. Vector3.CrossToRef = function (left, right, result) {
  3653. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3654. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3655. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3656. result.copyFrom(MathTmp.Vector3[0]);
  3657. };
  3658. /**
  3659. * Returns a new Vector3 as the normalization of the given vector
  3660. * @param vector defines the Vector3 to normalize
  3661. * @returns the new Vector3
  3662. */
  3663. Vector3.Normalize = function (vector) {
  3664. var result = Vector3.Zero();
  3665. Vector3.NormalizeToRef(vector, result);
  3666. return result;
  3667. };
  3668. /**
  3669. * Sets the given vector "result" with the normalization of the given first vector
  3670. * @param vector defines the Vector3 to normalize
  3671. * @param result defines the Vector3 where to store the result
  3672. */
  3673. Vector3.NormalizeToRef = function (vector, result) {
  3674. result.copyFrom(vector);
  3675. result.normalize();
  3676. };
  3677. /**
  3678. * Project a Vector3 onto screen space
  3679. * @param vector defines the Vector3 to project
  3680. * @param world defines the world matrix to use
  3681. * @param transform defines the transform (view x projection) matrix to use
  3682. * @param viewport defines the screen viewport to use
  3683. * @returns the new Vector3
  3684. */
  3685. Vector3.Project = function (vector, world, transform, viewport) {
  3686. var cw = viewport.width;
  3687. var ch = viewport.height;
  3688. var cx = viewport.x;
  3689. var cy = viewport.y;
  3690. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3691. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3692. var matrix = MathTmp.Matrix[0];
  3693. world.multiplyToRef(transform, matrix);
  3694. matrix.multiplyToRef(viewportMatrix, matrix);
  3695. return Vector3.TransformCoordinates(vector, matrix);
  3696. };
  3697. /**
  3698. * Unproject from screen space to object space
  3699. * @param source defines the screen space Vector3 to use
  3700. * @param viewportWidth defines the current width of the viewport
  3701. * @param viewportHeight defines the current height of the viewport
  3702. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3703. * @param transform defines the transform (view x projection) matrix to use
  3704. * @returns the new Vector3
  3705. */
  3706. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3707. var matrix = MathTmp.Matrix[0];
  3708. world.multiplyToRef(transform, matrix);
  3709. matrix.invert();
  3710. source.x = source.x / viewportWidth * 2 - 1;
  3711. source.y = -(source.y / viewportHeight * 2 - 1);
  3712. var vector = Vector3.TransformCoordinates(source, matrix);
  3713. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3714. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3715. vector = vector.scale(1.0 / num);
  3716. }
  3717. return vector;
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param source defines the screen space Vector3 to use
  3722. * @param viewportWidth defines the current width of the viewport
  3723. * @param viewportHeight defines the current height of the viewport
  3724. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3725. * @param view defines the view matrix to use
  3726. * @param projection defines the projection matrix to use
  3727. * @returns the new Vector3
  3728. */
  3729. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3730. var result = Vector3.Zero();
  3731. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3732. return result;
  3733. };
  3734. /**
  3735. * Unproject from screen space to object space
  3736. * @param source defines the screen space Vector3 to use
  3737. * @param viewportWidth defines the current width of the viewport
  3738. * @param viewportHeight defines the current height of the viewport
  3739. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3740. * @param view defines the view matrix to use
  3741. * @param projection defines the projection matrix to use
  3742. * @param result defines the Vector3 where to store the result
  3743. */
  3744. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3745. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3746. };
  3747. /**
  3748. * Unproject from screen space to object space
  3749. * @param sourceX defines the screen space x coordinate to use
  3750. * @param sourceY defines the screen space y coordinate to use
  3751. * @param sourceZ defines the screen space z coordinate to use
  3752. * @param viewportWidth defines the current width of the viewport
  3753. * @param viewportHeight defines the current height of the viewport
  3754. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3755. * @param view defines the view matrix to use
  3756. * @param projection defines the projection matrix to use
  3757. * @param result defines the Vector3 where to store the result
  3758. */
  3759. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3760. var matrix = MathTmp.Matrix[0];
  3761. world.multiplyToRef(view, matrix);
  3762. matrix.multiplyToRef(projection, matrix);
  3763. matrix.invert();
  3764. var screenSource = MathTmp.Vector3[0];
  3765. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3766. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3767. screenSource.z = 2 * sourceZ - 1.0;
  3768. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3769. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3770. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3771. result.scaleInPlace(1.0 / num);
  3772. }
  3773. };
  3774. /**
  3775. * Gets the minimal coordinate values between two Vector3
  3776. * @param left defines the first operand
  3777. * @param right defines the second operand
  3778. * @returns the new Vector3
  3779. */
  3780. Vector3.Minimize = function (left, right) {
  3781. var min = left.clone();
  3782. min.minimizeInPlace(right);
  3783. return min;
  3784. };
  3785. /**
  3786. * Gets the maximal coordinate values between two Vector3
  3787. * @param left defines the first operand
  3788. * @param right defines the second operand
  3789. * @returns the new Vector3
  3790. */
  3791. Vector3.Maximize = function (left, right) {
  3792. var max = left.clone();
  3793. max.maximizeInPlace(right);
  3794. return max;
  3795. };
  3796. /**
  3797. * Returns the distance between the vectors "value1" and "value2"
  3798. * @param value1 defines the first operand
  3799. * @param value2 defines the second operand
  3800. * @returns the distance
  3801. */
  3802. Vector3.Distance = function (value1, value2) {
  3803. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3804. };
  3805. /**
  3806. * Returns the squared distance between the vectors "value1" and "value2"
  3807. * @param value1 defines the first operand
  3808. * @param value2 defines the second operand
  3809. * @returns the squared distance
  3810. */
  3811. Vector3.DistanceSquared = function (value1, value2) {
  3812. var x = value1.x - value2.x;
  3813. var y = value1.y - value2.y;
  3814. var z = value1.z - value2.z;
  3815. return (x * x) + (y * y) + (z * z);
  3816. };
  3817. /**
  3818. * Returns a new Vector3 located at the center between "value1" and "value2"
  3819. * @param value1 defines the first operand
  3820. * @param value2 defines the second operand
  3821. * @returns the new Vector3
  3822. */
  3823. Vector3.Center = function (value1, value2) {
  3824. var center = value1.add(value2);
  3825. center.scaleInPlace(0.5);
  3826. return center;
  3827. };
  3828. /**
  3829. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3830. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3831. * to something in order to rotate it from its local system to the given target system
  3832. * Note: axis1, axis2 and axis3 are normalized during this operation
  3833. * @param axis1 defines the first axis
  3834. * @param axis2 defines the second axis
  3835. * @param axis3 defines the third axis
  3836. * @returns a new Vector3
  3837. */
  3838. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3839. var rotation = Vector3.Zero();
  3840. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3841. return rotation;
  3842. };
  3843. /**
  3844. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3845. * @param axis1 defines the first axis
  3846. * @param axis2 defines the second axis
  3847. * @param axis3 defines the third axis
  3848. * @param ref defines the Vector3 where to store the result
  3849. */
  3850. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3851. var quat = MathTmp.Quaternion[0];
  3852. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3853. quat.toEulerAnglesToRef(ref);
  3854. };
  3855. return Vector3;
  3856. }());
  3857. BABYLON.Vector3 = Vector3;
  3858. //Vector4 class created for EulerAngle class conversion to Quaternion
  3859. var Vector4 = /** @class */ (function () {
  3860. /**
  3861. * Creates a Vector4 object from the given floats.
  3862. */
  3863. function Vector4(x, y, z, w) {
  3864. this.x = x;
  3865. this.y = y;
  3866. this.z = z;
  3867. this.w = w;
  3868. }
  3869. /**
  3870. * Returns the string with the Vector4 coordinates.
  3871. */
  3872. Vector4.prototype.toString = function () {
  3873. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3874. };
  3875. /**
  3876. * Returns the string "Vector4".
  3877. */
  3878. Vector4.prototype.getClassName = function () {
  3879. return "Vector4";
  3880. };
  3881. /**
  3882. * Returns the Vector4 hash code.
  3883. */
  3884. Vector4.prototype.getHashCode = function () {
  3885. var hash = this.x || 0;
  3886. hash = (hash * 397) ^ (this.y || 0);
  3887. hash = (hash * 397) ^ (this.z || 0);
  3888. hash = (hash * 397) ^ (this.w || 0);
  3889. return hash;
  3890. };
  3891. // Operators
  3892. /**
  3893. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3894. */
  3895. Vector4.prototype.asArray = function () {
  3896. var result = new Array();
  3897. this.toArray(result, 0);
  3898. return result;
  3899. };
  3900. /**
  3901. * Populates the given array from the given index with the Vector4 coordinates.
  3902. * Returns the Vector4.
  3903. */
  3904. Vector4.prototype.toArray = function (array, index) {
  3905. if (index === undefined) {
  3906. index = 0;
  3907. }
  3908. array[index] = this.x;
  3909. array[index + 1] = this.y;
  3910. array[index + 2] = this.z;
  3911. array[index + 3] = this.w;
  3912. return this;
  3913. };
  3914. /**
  3915. * Adds the given vector to the current Vector4.
  3916. * Returns the updated Vector4.
  3917. */
  3918. Vector4.prototype.addInPlace = function (otherVector) {
  3919. this.x += otherVector.x;
  3920. this.y += otherVector.y;
  3921. this.z += otherVector.z;
  3922. this.w += otherVector.w;
  3923. return this;
  3924. };
  3925. /**
  3926. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3927. */
  3928. Vector4.prototype.add = function (otherVector) {
  3929. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3930. };
  3931. /**
  3932. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3933. * Returns the current Vector4.
  3934. */
  3935. Vector4.prototype.addToRef = function (otherVector, result) {
  3936. result.x = this.x + otherVector.x;
  3937. result.y = this.y + otherVector.y;
  3938. result.z = this.z + otherVector.z;
  3939. result.w = this.w + otherVector.w;
  3940. return this;
  3941. };
  3942. /**
  3943. * Subtract in place the given vector from the current Vector4.
  3944. * Returns the updated Vector4.
  3945. */
  3946. Vector4.prototype.subtractInPlace = function (otherVector) {
  3947. this.x -= otherVector.x;
  3948. this.y -= otherVector.y;
  3949. this.z -= otherVector.z;
  3950. this.w -= otherVector.w;
  3951. return this;
  3952. };
  3953. /**
  3954. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3955. */
  3956. Vector4.prototype.subtract = function (otherVector) {
  3957. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3958. };
  3959. /**
  3960. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3961. * Returns the current Vector4.
  3962. */
  3963. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3964. result.x = this.x - otherVector.x;
  3965. result.y = this.y - otherVector.y;
  3966. result.z = this.z - otherVector.z;
  3967. result.w = this.w - otherVector.w;
  3968. return this;
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3972. */
  3973. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3974. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3975. };
  3976. /**
  3977. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3981. result.x = this.x - x;
  3982. result.y = this.y - y;
  3983. result.z = this.z - z;
  3984. result.w = this.w - w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3989. */
  3990. Vector4.prototype.negate = function () {
  3991. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3992. };
  3993. /**
  3994. * Multiplies the current Vector4 coordinates by scale (float).
  3995. * Returns the updated Vector4.
  3996. */
  3997. Vector4.prototype.scaleInPlace = function (scale) {
  3998. this.x *= scale;
  3999. this.y *= scale;
  4000. this.z *= scale;
  4001. this.w *= scale;
  4002. return this;
  4003. };
  4004. /**
  4005. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4006. */
  4007. Vector4.prototype.scale = function (scale) {
  4008. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4009. };
  4010. /**
  4011. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4012. * Returns the current Vector4.
  4013. */
  4014. Vector4.prototype.scaleToRef = function (scale, result) {
  4015. result.x = this.x * scale;
  4016. result.y = this.y * scale;
  4017. result.z = this.z * scale;
  4018. result.w = this.w * scale;
  4019. return this;
  4020. };
  4021. /**
  4022. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4023. * @param scale defines the scale factor
  4024. * @param result defines the Vector4 object where to store the result
  4025. * @returns the unmodified current Vector4
  4026. */
  4027. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4028. result.x += this.x * scale;
  4029. result.y += this.y * scale;
  4030. result.z += this.z * scale;
  4031. result.w += this.w * scale;
  4032. return this;
  4033. };
  4034. /**
  4035. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4036. */
  4037. Vector4.prototype.equals = function (otherVector) {
  4038. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4039. };
  4040. /**
  4041. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4042. */
  4043. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4044. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4045. return otherVector
  4046. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4047. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4048. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4049. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4050. };
  4051. /**
  4052. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4053. */
  4054. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4055. return this.x === x && this.y === y && this.z === z && this.w === w;
  4056. };
  4057. /**
  4058. * Multiplies in place the current Vector4 by the given one.
  4059. * Returns the updated Vector4.
  4060. */
  4061. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4062. this.x *= otherVector.x;
  4063. this.y *= otherVector.y;
  4064. this.z *= otherVector.z;
  4065. this.w *= otherVector.w;
  4066. return this;
  4067. };
  4068. /**
  4069. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4070. */
  4071. Vector4.prototype.multiply = function (otherVector) {
  4072. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4073. };
  4074. /**
  4075. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4076. * Returns the current Vector4.
  4077. */
  4078. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4079. result.x = this.x * otherVector.x;
  4080. result.y = this.y * otherVector.y;
  4081. result.z = this.z * otherVector.z;
  4082. result.w = this.w * otherVector.w;
  4083. return this;
  4084. };
  4085. /**
  4086. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4087. */
  4088. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4089. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4090. };
  4091. /**
  4092. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4093. */
  4094. Vector4.prototype.divide = function (otherVector) {
  4095. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4096. };
  4097. /**
  4098. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4099. * Returns the current Vector4.
  4100. */
  4101. Vector4.prototype.divideToRef = function (otherVector, result) {
  4102. result.x = this.x / otherVector.x;
  4103. result.y = this.y / otherVector.y;
  4104. result.z = this.z / otherVector.z;
  4105. result.w = this.w / otherVector.w;
  4106. return this;
  4107. };
  4108. /**
  4109. * Divides the current Vector3 coordinates by the given ones.
  4110. * @returns the updated Vector3.
  4111. */
  4112. Vector4.prototype.divideInPlace = function (otherVector) {
  4113. return this.divideToRef(otherVector, this);
  4114. };
  4115. /**
  4116. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4117. * @param other defines the second operand
  4118. * @returns the current updated Vector4
  4119. */
  4120. Vector4.prototype.minimizeInPlace = function (other) {
  4121. if (other.x < this.x)
  4122. this.x = other.x;
  4123. if (other.y < this.y)
  4124. this.y = other.y;
  4125. if (other.z < this.z)
  4126. this.z = other.z;
  4127. if (other.w < this.w)
  4128. this.w = other.w;
  4129. return this;
  4130. };
  4131. /**
  4132. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4133. * @param other defines the second operand
  4134. * @returns the current updated Vector4
  4135. */
  4136. Vector4.prototype.maximizeInPlace = function (other) {
  4137. if (other.x > this.x)
  4138. this.x = other.x;
  4139. if (other.y > this.y)
  4140. this.y = other.y;
  4141. if (other.z > this.z)
  4142. this.z = other.z;
  4143. if (other.w > this.w)
  4144. this.w = other.w;
  4145. return this;
  4146. };
  4147. // Properties
  4148. /**
  4149. * Returns the Vector4 length (float).
  4150. */
  4151. Vector4.prototype.length = function () {
  4152. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4153. };
  4154. /**
  4155. * Returns the Vector4 squared length (float).
  4156. */
  4157. Vector4.prototype.lengthSquared = function () {
  4158. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4159. };
  4160. // Methods
  4161. /**
  4162. * Normalizes in place the Vector4.
  4163. * Returns the updated Vector4.
  4164. */
  4165. Vector4.prototype.normalize = function () {
  4166. var len = this.length();
  4167. if (len === 0)
  4168. return this;
  4169. var num = 1.0 / len;
  4170. this.x *= num;
  4171. this.y *= num;
  4172. this.z *= num;
  4173. this.w *= num;
  4174. return this;
  4175. };
  4176. /**
  4177. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4178. */
  4179. Vector4.prototype.toVector3 = function () {
  4180. return new Vector3(this.x, this.y, this.z);
  4181. };
  4182. /**
  4183. * Returns a new Vector4 copied from the current one.
  4184. */
  4185. Vector4.prototype.clone = function () {
  4186. return new Vector4(this.x, this.y, this.z, this.w);
  4187. };
  4188. /**
  4189. * Updates the current Vector4 with the given one coordinates.
  4190. * Returns the updated Vector4.
  4191. */
  4192. Vector4.prototype.copyFrom = function (source) {
  4193. this.x = source.x;
  4194. this.y = source.y;
  4195. this.z = source.z;
  4196. this.w = source.w;
  4197. return this;
  4198. };
  4199. /**
  4200. * Updates the current Vector4 coordinates with the given floats.
  4201. * Returns the updated Vector4.
  4202. */
  4203. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4204. this.x = x;
  4205. this.y = y;
  4206. this.z = z;
  4207. this.w = w;
  4208. return this;
  4209. };
  4210. /**
  4211. * Updates the current Vector4 coordinates with the given floats.
  4212. * Returns the updated Vector4.
  4213. */
  4214. Vector4.prototype.set = function (x, y, z, w) {
  4215. return this.copyFromFloats(x, y, z, w);
  4216. };
  4217. // Statics
  4218. /**
  4219. * Returns a new Vector4 set from the starting index of the given array.
  4220. */
  4221. Vector4.FromArray = function (array, offset) {
  4222. if (!offset) {
  4223. offset = 0;
  4224. }
  4225. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4226. };
  4227. /**
  4228. * Updates the given vector "result" from the starting index of the given array.
  4229. */
  4230. Vector4.FromArrayToRef = function (array, offset, result) {
  4231. result.x = array[offset];
  4232. result.y = array[offset + 1];
  4233. result.z = array[offset + 2];
  4234. result.w = array[offset + 3];
  4235. };
  4236. /**
  4237. * Updates the given vector "result" from the starting index of the given Float32Array.
  4238. */
  4239. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4240. Vector4.FromArrayToRef(array, offset, result);
  4241. };
  4242. /**
  4243. * Updates the given vector "result" coordinates from the given floats.
  4244. */
  4245. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4246. result.x = x;
  4247. result.y = y;
  4248. result.z = z;
  4249. result.w = w;
  4250. };
  4251. /**
  4252. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4253. */
  4254. Vector4.Zero = function () {
  4255. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4256. };
  4257. /**
  4258. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4259. */
  4260. Vector4.One = function () {
  4261. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4262. };
  4263. /**
  4264. * Returns a new normalized Vector4 from the given one.
  4265. */
  4266. Vector4.Normalize = function (vector) {
  4267. var result = Vector4.Zero();
  4268. Vector4.NormalizeToRef(vector, result);
  4269. return result;
  4270. };
  4271. /**
  4272. * Updates the given vector "result" from the normalization of the given one.
  4273. */
  4274. Vector4.NormalizeToRef = function (vector, result) {
  4275. result.copyFrom(vector);
  4276. result.normalize();
  4277. };
  4278. Vector4.Minimize = function (left, right) {
  4279. var min = left.clone();
  4280. min.minimizeInPlace(right);
  4281. return min;
  4282. };
  4283. Vector4.Maximize = function (left, right) {
  4284. var max = left.clone();
  4285. max.maximizeInPlace(right);
  4286. return max;
  4287. };
  4288. /**
  4289. * Returns the distance (float) between the vectors "value1" and "value2".
  4290. */
  4291. Vector4.Distance = function (value1, value2) {
  4292. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4293. };
  4294. /**
  4295. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4296. */
  4297. Vector4.DistanceSquared = function (value1, value2) {
  4298. var x = value1.x - value2.x;
  4299. var y = value1.y - value2.y;
  4300. var z = value1.z - value2.z;
  4301. var w = value1.w - value2.w;
  4302. return (x * x) + (y * y) + (z * z) + (w * w);
  4303. };
  4304. /**
  4305. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4306. */
  4307. Vector4.Center = function (value1, value2) {
  4308. var center = value1.add(value2);
  4309. center.scaleInPlace(0.5);
  4310. return center;
  4311. };
  4312. /**
  4313. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4314. * This methods computes transformed normalized direction vectors only.
  4315. */
  4316. Vector4.TransformNormal = function (vector, transformation) {
  4317. var result = Vector4.Zero();
  4318. Vector4.TransformNormalToRef(vector, transformation, result);
  4319. return result;
  4320. };
  4321. /**
  4322. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4323. * This methods computes transformed normalized direction vectors only.
  4324. */
  4325. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4326. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4327. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4328. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4329. result.x = x;
  4330. result.y = y;
  4331. result.z = z;
  4332. result.w = vector.w;
  4333. };
  4334. /**
  4335. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4336. * This methods computes transformed normalized direction vectors only.
  4337. */
  4338. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4339. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4340. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4341. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4342. result.w = w;
  4343. };
  4344. return Vector4;
  4345. }());
  4346. BABYLON.Vector4 = Vector4;
  4347. var Size = /** @class */ (function () {
  4348. /**
  4349. * Creates a Size object from the given width and height (floats).
  4350. */
  4351. function Size(width, height) {
  4352. this.width = width;
  4353. this.height = height;
  4354. }
  4355. // Returns a string with the Size width and height.
  4356. Size.prototype.toString = function () {
  4357. return "{W: " + this.width + ", H: " + this.height + "}";
  4358. };
  4359. /**
  4360. * Returns the string "Size"
  4361. */
  4362. Size.prototype.getClassName = function () {
  4363. return "Size";
  4364. };
  4365. /**
  4366. * Returns the Size hash code.
  4367. */
  4368. Size.prototype.getHashCode = function () {
  4369. var hash = this.width || 0;
  4370. hash = (hash * 397) ^ (this.height || 0);
  4371. return hash;
  4372. };
  4373. /**
  4374. * Updates the current size from the given one.
  4375. * Returns the updated Size.
  4376. */
  4377. Size.prototype.copyFrom = function (src) {
  4378. this.width = src.width;
  4379. this.height = src.height;
  4380. };
  4381. /**
  4382. * Updates in place the current Size from the given floats.
  4383. * Returns the updated Size.
  4384. */
  4385. Size.prototype.copyFromFloats = function (width, height) {
  4386. this.width = width;
  4387. this.height = height;
  4388. return this;
  4389. };
  4390. /**
  4391. * Updates in place the current Size from the given floats.
  4392. * Returns the updated Size.
  4393. */
  4394. Size.prototype.set = function (width, height) {
  4395. return this.copyFromFloats(width, height);
  4396. };
  4397. /**
  4398. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4399. */
  4400. Size.prototype.multiplyByFloats = function (w, h) {
  4401. return new Size(this.width * w, this.height * h);
  4402. };
  4403. /**
  4404. * Returns a new Size copied from the given one.
  4405. */
  4406. Size.prototype.clone = function () {
  4407. return new Size(this.width, this.height);
  4408. };
  4409. /**
  4410. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4411. */
  4412. Size.prototype.equals = function (other) {
  4413. if (!other) {
  4414. return false;
  4415. }
  4416. return (this.width === other.width) && (this.height === other.height);
  4417. };
  4418. Object.defineProperty(Size.prototype, "surface", {
  4419. /**
  4420. * Returns the surface of the Size : width * height (float).
  4421. */
  4422. get: function () {
  4423. return this.width * this.height;
  4424. },
  4425. enumerable: true,
  4426. configurable: true
  4427. });
  4428. /**
  4429. * Returns a new Size set to (0.0, 0.0)
  4430. */
  4431. Size.Zero = function () {
  4432. return new Size(0.0, 0.0);
  4433. };
  4434. /**
  4435. * Returns a new Size set as the addition result of the current Size and the given one.
  4436. */
  4437. Size.prototype.add = function (otherSize) {
  4438. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4439. return r;
  4440. };
  4441. /**
  4442. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4443. */
  4444. Size.prototype.subtract = function (otherSize) {
  4445. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4446. return r;
  4447. };
  4448. /**
  4449. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4450. */
  4451. Size.Lerp = function (start, end, amount) {
  4452. var w = start.width + ((end.width - start.width) * amount);
  4453. var h = start.height + ((end.height - start.height) * amount);
  4454. return new Size(w, h);
  4455. };
  4456. return Size;
  4457. }());
  4458. BABYLON.Size = Size;
  4459. /**
  4460. * Class used to store quaternion data
  4461. * @see https://en.wikipedia.org/wiki/Quaternion
  4462. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4463. */
  4464. var Quaternion = /** @class */ (function () {
  4465. /**
  4466. * Creates a new Quaternion from the given floats
  4467. * @param x defines the first component (0 by default)
  4468. * @param y defines the second component (0 by default)
  4469. * @param z defines the third component (0 by default)
  4470. * @param w defines the fourth component (1.0 by default)
  4471. */
  4472. function Quaternion(
  4473. /** defines the first component (0 by default) */
  4474. x,
  4475. /** defines the second component (0 by default) */
  4476. y,
  4477. /** defines the third component (0 by default) */
  4478. z,
  4479. /** defines the fourth component (1.0 by default) */
  4480. w) {
  4481. if (x === void 0) { x = 0.0; }
  4482. if (y === void 0) { y = 0.0; }
  4483. if (z === void 0) { z = 0.0; }
  4484. if (w === void 0) { w = 1.0; }
  4485. this.x = x;
  4486. this.y = y;
  4487. this.z = z;
  4488. this.w = w;
  4489. }
  4490. /**
  4491. * Gets a string representation for the current quaternion
  4492. * @returns a string with the Quaternion coordinates
  4493. */
  4494. Quaternion.prototype.toString = function () {
  4495. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4496. };
  4497. /**
  4498. * Gets the class name of the quaternion
  4499. * @returns the string "Quaternion"
  4500. */
  4501. Quaternion.prototype.getClassName = function () {
  4502. return "Quaternion";
  4503. };
  4504. /**
  4505. * Gets a hash code for this quaternion
  4506. * @returns the quaternion hash code
  4507. */
  4508. Quaternion.prototype.getHashCode = function () {
  4509. var hash = this.x || 0;
  4510. hash = (hash * 397) ^ (this.y || 0);
  4511. hash = (hash * 397) ^ (this.z || 0);
  4512. hash = (hash * 397) ^ (this.w || 0);
  4513. return hash;
  4514. };
  4515. /**
  4516. * Copy the quaternion to an array
  4517. * @returns a new array populated with 4 elements from the quaternion coordinates
  4518. */
  4519. Quaternion.prototype.asArray = function () {
  4520. return [this.x, this.y, this.z, this.w];
  4521. };
  4522. /**
  4523. * Check if two quaternions are equals
  4524. * @param otherQuaternion defines the second operand
  4525. * @return true if the current quaternion and the given one coordinates are strictly equals
  4526. */
  4527. Quaternion.prototype.equals = function (otherQuaternion) {
  4528. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4529. };
  4530. /**
  4531. * Clone the current quaternion
  4532. * @returns a new quaternion copied from the current one
  4533. */
  4534. Quaternion.prototype.clone = function () {
  4535. return new Quaternion(this.x, this.y, this.z, this.w);
  4536. };
  4537. /**
  4538. * Copy a quaternion to the current one
  4539. * @param other defines the other quaternion
  4540. * @returns the updated current quaternion
  4541. */
  4542. Quaternion.prototype.copyFrom = function (other) {
  4543. this.x = other.x;
  4544. this.y = other.y;
  4545. this.z = other.z;
  4546. this.w = other.w;
  4547. return this;
  4548. };
  4549. /**
  4550. * Updates the current quaternion with the given float coordinates
  4551. * @param x defines the x coordinate
  4552. * @param y defines the y coordinate
  4553. * @param z defines the z coordinate
  4554. * @param w defines the w coordinate
  4555. * @returns the updated current quaternion
  4556. */
  4557. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4558. this.x = x;
  4559. this.y = y;
  4560. this.z = z;
  4561. this.w = w;
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion from the given float coordinates
  4566. * @param x defines the x coordinate
  4567. * @param y defines the y coordinate
  4568. * @param z defines the z coordinate
  4569. * @param w defines the w coordinate
  4570. * @returns the updated current quaternion
  4571. */
  4572. Quaternion.prototype.set = function (x, y, z, w) {
  4573. return this.copyFromFloats(x, y, z, w);
  4574. };
  4575. /**
  4576. * Adds two quaternions
  4577. * @param other defines the second operand
  4578. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4579. */
  4580. Quaternion.prototype.add = function (other) {
  4581. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4582. };
  4583. /**
  4584. * Add a quaternion to the current one
  4585. * @param other defines the quaternion to add
  4586. * @returns the current quaternion
  4587. */
  4588. Quaternion.prototype.addInPlace = function (other) {
  4589. this.x += other.x;
  4590. this.y += other.y;
  4591. this.z += other.z;
  4592. this.w += other.w;
  4593. return this;
  4594. };
  4595. /**
  4596. * Subtract two quaternions
  4597. * @param other defines the second operand
  4598. * @returns a new quaternion as the subtraction result of the given one from the current one
  4599. */
  4600. Quaternion.prototype.subtract = function (other) {
  4601. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4602. };
  4603. /**
  4604. * Multiplies the current quaternion by a scale factor
  4605. * @param value defines the scale factor
  4606. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4607. */
  4608. Quaternion.prototype.scale = function (value) {
  4609. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4610. };
  4611. /**
  4612. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4613. * @param scale defines the scale factor
  4614. * @param result defines the Quaternion object where to store the result
  4615. * @returns the unmodified current quaternion
  4616. */
  4617. Quaternion.prototype.scaleToRef = function (scale, result) {
  4618. result.x = this.x * scale;
  4619. result.y = this.y * scale;
  4620. result.z = this.z * scale;
  4621. result.w = this.w * scale;
  4622. return this;
  4623. };
  4624. /**
  4625. * Multiplies in place the current quaternion by a scale factor
  4626. * @param value defines the scale factor
  4627. * @returns the current modified quaternion
  4628. */
  4629. Quaternion.prototype.scaleInPlace = function (value) {
  4630. this.x *= value;
  4631. this.y *= value;
  4632. this.z *= value;
  4633. this.w *= value;
  4634. return this;
  4635. };
  4636. /**
  4637. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4638. * @param scale defines the scale factor
  4639. * @param result defines the Quaternion object where to store the result
  4640. * @returns the unmodified current quaternion
  4641. */
  4642. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4643. result.x += this.x * scale;
  4644. result.y += this.y * scale;
  4645. result.z += this.z * scale;
  4646. result.w += this.w * scale;
  4647. return this;
  4648. };
  4649. /**
  4650. * Multiplies two quaternions
  4651. * @param q1 defines the second operand
  4652. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4653. */
  4654. Quaternion.prototype.multiply = function (q1) {
  4655. var result = new Quaternion(0, 0, 0, 1.0);
  4656. this.multiplyToRef(q1, result);
  4657. return result;
  4658. };
  4659. /**
  4660. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4661. * @param q1 defines the second operand
  4662. * @param result defines the target quaternion
  4663. * @returns the current quaternion
  4664. */
  4665. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4666. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4667. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4668. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4669. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4670. result.copyFromFloats(x, y, z, w);
  4671. return this;
  4672. };
  4673. /**
  4674. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4675. * @param q1 defines the second operand
  4676. * @returns the currentupdated quaternion
  4677. */
  4678. Quaternion.prototype.multiplyInPlace = function (q1) {
  4679. this.multiplyToRef(q1, this);
  4680. return this;
  4681. };
  4682. /**
  4683. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4684. * @param ref defines the target quaternion
  4685. * @returns the current quaternion
  4686. */
  4687. Quaternion.prototype.conjugateToRef = function (ref) {
  4688. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4689. return this;
  4690. };
  4691. /**
  4692. * Conjugates in place (1-q) the current quaternion
  4693. * @returns the current updated quaternion
  4694. */
  4695. Quaternion.prototype.conjugateInPlace = function () {
  4696. this.x *= -1;
  4697. this.y *= -1;
  4698. this.z *= -1;
  4699. return this;
  4700. };
  4701. /**
  4702. * Conjugates in place (1-q) the current quaternion
  4703. * @returns a new quaternion
  4704. */
  4705. Quaternion.prototype.conjugate = function () {
  4706. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4707. return result;
  4708. };
  4709. /**
  4710. * Gets length of current quaternion
  4711. * @returns the quaternion length (float)
  4712. */
  4713. Quaternion.prototype.length = function () {
  4714. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4715. };
  4716. /**
  4717. * Normalize in place the current quaternion
  4718. * @returns the current updated quaternion
  4719. */
  4720. Quaternion.prototype.normalize = function () {
  4721. var length = 1.0 / this.length();
  4722. this.x *= length;
  4723. this.y *= length;
  4724. this.z *= length;
  4725. this.w *= length;
  4726. return this;
  4727. };
  4728. /**
  4729. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4730. * @param order is a reserved parameter and is ignore for now
  4731. * @returns a new Vector3 containing the Euler angles
  4732. */
  4733. Quaternion.prototype.toEulerAngles = function (order) {
  4734. if (order === void 0) { order = "YZX"; }
  4735. var result = Vector3.Zero();
  4736. this.toEulerAnglesToRef(result, order);
  4737. return result;
  4738. };
  4739. /**
  4740. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4741. * @param result defines the vector which will be filled with the Euler angles
  4742. * @param order is a reserved parameter and is ignore for now
  4743. * @returns the current unchanged quaternion
  4744. */
  4745. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4746. if (order === void 0) { order = "YZX"; }
  4747. var qz = this.z;
  4748. var qx = this.x;
  4749. var qy = this.y;
  4750. var qw = this.w;
  4751. var sqw = qw * qw;
  4752. var sqz = qz * qz;
  4753. var sqx = qx * qx;
  4754. var sqy = qy * qy;
  4755. var zAxisY = qy * qz - qx * qw;
  4756. var limit = .4999999;
  4757. if (zAxisY < -limit) {
  4758. result.y = 2 * Math.atan2(qy, qw);
  4759. result.x = Math.PI / 2;
  4760. result.z = 0;
  4761. }
  4762. else if (zAxisY > limit) {
  4763. result.y = 2 * Math.atan2(qy, qw);
  4764. result.x = -Math.PI / 2;
  4765. result.z = 0;
  4766. }
  4767. else {
  4768. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4769. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4770. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4771. }
  4772. return this;
  4773. };
  4774. /**
  4775. * Updates the given rotation matrix with the current quaternion values
  4776. * @param result defines the target matrix
  4777. * @returns the current unchanged quaternion
  4778. */
  4779. Quaternion.prototype.toRotationMatrix = function (result) {
  4780. var xx = this.x * this.x;
  4781. var yy = this.y * this.y;
  4782. var zz = this.z * this.z;
  4783. var xy = this.x * this.y;
  4784. var zw = this.z * this.w;
  4785. var zx = this.z * this.x;
  4786. var yw = this.y * this.w;
  4787. var yz = this.y * this.z;
  4788. var xw = this.x * this.w;
  4789. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4790. result.m[1] = 2.0 * (xy + zw);
  4791. result.m[2] = 2.0 * (zx - yw);
  4792. result.m[3] = 0;
  4793. result.m[4] = 2.0 * (xy - zw);
  4794. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4795. result.m[6] = 2.0 * (yz + xw);
  4796. result.m[7] = 0;
  4797. result.m[8] = 2.0 * (zx + yw);
  4798. result.m[9] = 2.0 * (yz - xw);
  4799. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4800. result.m[11] = 0;
  4801. result.m[12] = 0;
  4802. result.m[13] = 0;
  4803. result.m[14] = 0;
  4804. result.m[15] = 1.0;
  4805. result._markAsUpdated();
  4806. return this;
  4807. };
  4808. /**
  4809. * Updates the current quaternion from the given rotation matrix values
  4810. * @param matrix defines the source matrix
  4811. * @returns the current updated quaternion
  4812. */
  4813. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4814. Quaternion.FromRotationMatrixToRef(matrix, this);
  4815. return this;
  4816. };
  4817. // Statics
  4818. /**
  4819. * Creates a new quaternion from a rotation matrix
  4820. * @param matrix defines the source matrix
  4821. * @returns a new quaternion created from the given rotation matrix values
  4822. */
  4823. Quaternion.FromRotationMatrix = function (matrix) {
  4824. var result = new Quaternion();
  4825. Quaternion.FromRotationMatrixToRef(matrix, result);
  4826. return result;
  4827. };
  4828. /**
  4829. * Updates the given quaternion with the given rotation matrix values
  4830. * @param matrix defines the source matrix
  4831. * @param result defines the target quaternion
  4832. */
  4833. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4834. var data = matrix.m;
  4835. var m11 = data[0], m12 = data[4], m13 = data[8];
  4836. var m21 = data[1], m22 = data[5], m23 = data[9];
  4837. var m31 = data[2], m32 = data[6], m33 = data[10];
  4838. var trace = m11 + m22 + m33;
  4839. var s;
  4840. if (trace > 0) {
  4841. s = 0.5 / Math.sqrt(trace + 1.0);
  4842. result.w = 0.25 / s;
  4843. result.x = (m32 - m23) * s;
  4844. result.y = (m13 - m31) * s;
  4845. result.z = (m21 - m12) * s;
  4846. }
  4847. else if (m11 > m22 && m11 > m33) {
  4848. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4849. result.w = (m32 - m23) / s;
  4850. result.x = 0.25 * s;
  4851. result.y = (m12 + m21) / s;
  4852. result.z = (m13 + m31) / s;
  4853. }
  4854. else if (m22 > m33) {
  4855. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4856. result.w = (m13 - m31) / s;
  4857. result.x = (m12 + m21) / s;
  4858. result.y = 0.25 * s;
  4859. result.z = (m23 + m32) / s;
  4860. }
  4861. else {
  4862. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4863. result.w = (m21 - m12) / s;
  4864. result.x = (m13 + m31) / s;
  4865. result.y = (m23 + m32) / s;
  4866. result.z = 0.25 * s;
  4867. }
  4868. };
  4869. /**
  4870. * Returns the dot product (float) between the quaternions "left" and "right"
  4871. * @param left defines the left operand
  4872. * @param right defines the right operand
  4873. * @returns the dot product
  4874. */
  4875. Quaternion.Dot = function (left, right) {
  4876. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4877. };
  4878. /**
  4879. * Checks if the two quaternions are close to each other
  4880. * @param quat0 defines the first quaternion to check
  4881. * @param quat1 defines the second quaternion to check
  4882. * @returns true if the two quaternions are close to each other
  4883. */
  4884. Quaternion.AreClose = function (quat0, quat1) {
  4885. var dot = Quaternion.Dot(quat0, quat1);
  4886. return dot >= 0;
  4887. };
  4888. /**
  4889. * Creates an empty quaternion
  4890. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4891. */
  4892. Quaternion.Zero = function () {
  4893. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4894. };
  4895. /**
  4896. * Inverse a given quaternion
  4897. * @param q defines the source quaternion
  4898. * @returns a new quaternion as the inverted current quaternion
  4899. */
  4900. Quaternion.Inverse = function (q) {
  4901. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4902. };
  4903. /**
  4904. * Creates an identity quaternion
  4905. * @returns the identity quaternion
  4906. */
  4907. Quaternion.Identity = function () {
  4908. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4909. };
  4910. /**
  4911. * Gets a boolean indicating if the given quaternion is identity
  4912. * @param quaternion defines the quaternion to check
  4913. * @returns true if the quaternion is identity
  4914. */
  4915. Quaternion.IsIdentity = function (quaternion) {
  4916. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4917. };
  4918. /**
  4919. * Creates a quaternion from a rotation around an axis
  4920. * @param axis defines the axis to use
  4921. * @param angle defines the angle to use
  4922. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4923. */
  4924. Quaternion.RotationAxis = function (axis, angle) {
  4925. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4926. };
  4927. /**
  4928. * Creates a rotation around an axis and stores it into the given quaternion
  4929. * @param axis defines the axis to use
  4930. * @param angle defines the angle to use
  4931. * @param result defines the target quaternion
  4932. * @returns the target quaternion
  4933. */
  4934. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4935. var sin = Math.sin(angle / 2);
  4936. axis.normalize();
  4937. result.w = Math.cos(angle / 2);
  4938. result.x = axis.x * sin;
  4939. result.y = axis.y * sin;
  4940. result.z = axis.z * sin;
  4941. return result;
  4942. };
  4943. /**
  4944. * Creates a new quaternion from data stored into an array
  4945. * @param array defines the data source
  4946. * @param offset defines the offset in the source array where the data starts
  4947. * @returns a new quaternion
  4948. */
  4949. Quaternion.FromArray = function (array, offset) {
  4950. if (!offset) {
  4951. offset = 0;
  4952. }
  4953. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4954. };
  4955. /**
  4956. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4957. * @param yaw defines the rotation around Y axis
  4958. * @param pitch defines the rotation around X axis
  4959. * @param roll defines the rotation around Z axis
  4960. * @returns the new quaternion
  4961. */
  4962. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4963. var q = new Quaternion();
  4964. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4965. return q;
  4966. };
  4967. /**
  4968. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4969. * @param yaw defines the rotation around Y axis
  4970. * @param pitch defines the rotation around X axis
  4971. * @param roll defines the rotation around Z axis
  4972. * @param result defines the target quaternion
  4973. */
  4974. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4975. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4976. var halfRoll = roll * 0.5;
  4977. var halfPitch = pitch * 0.5;
  4978. var halfYaw = yaw * 0.5;
  4979. var sinRoll = Math.sin(halfRoll);
  4980. var cosRoll = Math.cos(halfRoll);
  4981. var sinPitch = Math.sin(halfPitch);
  4982. var cosPitch = Math.cos(halfPitch);
  4983. var sinYaw = Math.sin(halfYaw);
  4984. var cosYaw = Math.cos(halfYaw);
  4985. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4986. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4987. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4988. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4989. };
  4990. /**
  4991. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4992. * @param alpha defines the rotation around first axis
  4993. * @param beta defines the rotation around second axis
  4994. * @param gamma defines the rotation around third axis
  4995. * @returns the new quaternion
  4996. */
  4997. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4998. var result = new Quaternion();
  4999. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5000. return result;
  5001. };
  5002. /**
  5003. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5004. * @param alpha defines the rotation around first axis
  5005. * @param beta defines the rotation around second axis
  5006. * @param gamma defines the rotation around third axis
  5007. * @param result defines the target quaternion
  5008. */
  5009. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5010. // Produces a quaternion from Euler angles in the z-x-z orientation
  5011. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5012. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5013. var halfBeta = beta * 0.5;
  5014. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5015. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5016. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5017. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5018. };
  5019. /**
  5020. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5021. * @param axis1 defines the first axis
  5022. * @param axis2 defines the second axis
  5023. * @param axis3 defines the third axis
  5024. * @returns the new quaternion
  5025. */
  5026. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5027. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5028. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5029. return quat;
  5030. };
  5031. /**
  5032. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5033. * @param axis1 defines the first axis
  5034. * @param axis2 defines the second axis
  5035. * @param axis3 defines the third axis
  5036. * @param ref defines the target quaternion
  5037. */
  5038. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5039. var rotMat = MathTmp.Matrix[0];
  5040. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5041. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5042. };
  5043. /**
  5044. * Interpolates between two quaternions
  5045. * @param left defines first quaternion
  5046. * @param right defines second quaternion
  5047. * @param amount defines the gradient to use
  5048. * @returns the new interpolated quaternion
  5049. */
  5050. Quaternion.Slerp = function (left, right, amount) {
  5051. var result = Quaternion.Identity();
  5052. Quaternion.SlerpToRef(left, right, amount, result);
  5053. return result;
  5054. };
  5055. /**
  5056. * Interpolates between two quaternions and stores it into a target quaternion
  5057. * @param left defines first quaternion
  5058. * @param right defines second quaternion
  5059. * @param amount defines the gradient to use
  5060. * @param result defines the target quaternion
  5061. */
  5062. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5063. var num2;
  5064. var num3;
  5065. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5066. var flag = false;
  5067. if (num4 < 0) {
  5068. flag = true;
  5069. num4 = -num4;
  5070. }
  5071. if (num4 > 0.999999) {
  5072. num3 = 1 - amount;
  5073. num2 = flag ? -amount : amount;
  5074. }
  5075. else {
  5076. var num5 = Math.acos(num4);
  5077. var num6 = (1.0 / Math.sin(num5));
  5078. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5079. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5080. }
  5081. result.x = (num3 * left.x) + (num2 * right.x);
  5082. result.y = (num3 * left.y) + (num2 * right.y);
  5083. result.z = (num3 * left.z) + (num2 * right.z);
  5084. result.w = (num3 * left.w) + (num2 * right.w);
  5085. };
  5086. /**
  5087. * Interpolate between two quaternions using Hermite interpolation
  5088. * @param value1 defines first quaternion
  5089. * @param tangent1 defines the incoming tangent
  5090. * @param value2 defines second quaternion
  5091. * @param tangent2 defines the outgoing tangent
  5092. * @param amount defines the target quaternion
  5093. * @returns the new interpolated quaternion
  5094. */
  5095. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5096. var squared = amount * amount;
  5097. var cubed = amount * squared;
  5098. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5099. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5100. var part3 = (cubed - (2.0 * squared)) + amount;
  5101. var part4 = cubed - squared;
  5102. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5103. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5104. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5105. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5106. return new Quaternion(x, y, z, w);
  5107. };
  5108. return Quaternion;
  5109. }());
  5110. BABYLON.Quaternion = Quaternion;
  5111. /**
  5112. * Class used to store matrix data (4x4)
  5113. */
  5114. var Matrix = /** @class */ (function () {
  5115. /**
  5116. * Creates an empty matrix (filled with zeros)
  5117. */
  5118. function Matrix() {
  5119. this._isIdentity = false;
  5120. this._isIdentityDirty = true;
  5121. /**
  5122. * Gets or sets the internal data of the matrix
  5123. */
  5124. this.m = new Float32Array(16);
  5125. this._markAsUpdated();
  5126. }
  5127. /** @hidden */
  5128. Matrix.prototype._markAsUpdated = function () {
  5129. this.updateFlag = Matrix._updateFlagSeed++;
  5130. this._isIdentityDirty = true;
  5131. };
  5132. // Properties
  5133. /**
  5134. * Check if the current matrix is indentity
  5135. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5136. * @returns true is the matrix is the identity matrix
  5137. */
  5138. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5139. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5140. if (this._isIdentityDirty) {
  5141. this._isIdentityDirty = false;
  5142. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5143. this._isIdentity = false;
  5144. }
  5145. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5146. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5147. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5148. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5149. this._isIdentity = false;
  5150. }
  5151. else {
  5152. this._isIdentity = true;
  5153. }
  5154. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5155. this._isIdentity = false;
  5156. }
  5157. }
  5158. return this._isIdentity;
  5159. };
  5160. /**
  5161. * Gets the determinant of the matrix
  5162. * @returns the matrix determinant
  5163. */
  5164. Matrix.prototype.determinant = function () {
  5165. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5166. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5167. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5168. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5169. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5170. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5171. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5172. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5173. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5174. };
  5175. // Methods
  5176. /**
  5177. * Returns the matrix as a Float32Array
  5178. * @returns the matrix underlying array
  5179. */
  5180. Matrix.prototype.toArray = function () {
  5181. return this.m;
  5182. };
  5183. /**
  5184. * Returns the matrix as a Float32Array
  5185. * @returns the matrix underlying array.
  5186. */
  5187. Matrix.prototype.asArray = function () {
  5188. return this.toArray();
  5189. };
  5190. /**
  5191. * Inverts the current matrix in place
  5192. * @returns the current inverted matrix
  5193. */
  5194. Matrix.prototype.invert = function () {
  5195. this.invertToRef(this);
  5196. return this;
  5197. };
  5198. /**
  5199. * Sets all the matrix elements to zero
  5200. * @returns the current matrix
  5201. */
  5202. Matrix.prototype.reset = function () {
  5203. for (var index = 0; index < 16; index++) {
  5204. this.m[index] = 0.0;
  5205. }
  5206. this._markAsUpdated();
  5207. return this;
  5208. };
  5209. /**
  5210. * Adds the current matrix with a second one
  5211. * @param other defines the matrix to add
  5212. * @returns a new matrix as the addition of the current matrix and the given one
  5213. */
  5214. Matrix.prototype.add = function (other) {
  5215. var result = new Matrix();
  5216. this.addToRef(other, result);
  5217. return result;
  5218. };
  5219. /**
  5220. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5221. * @param other defines the matrix to add
  5222. * @param result defines the target matrix
  5223. * @returns the current matrix
  5224. */
  5225. Matrix.prototype.addToRef = function (other, result) {
  5226. for (var index = 0; index < 16; index++) {
  5227. result.m[index] = this.m[index] + other.m[index];
  5228. }
  5229. result._markAsUpdated();
  5230. return this;
  5231. };
  5232. /**
  5233. * Adds in place the given matrix to the current matrix
  5234. * @param other defines the second operand
  5235. * @returns the current updated matrix
  5236. */
  5237. Matrix.prototype.addToSelf = function (other) {
  5238. for (var index = 0; index < 16; index++) {
  5239. this.m[index] += other.m[index];
  5240. }
  5241. this._markAsUpdated();
  5242. return this;
  5243. };
  5244. /**
  5245. * Sets the given matrix to the current inverted Matrix
  5246. * @param other defines the target matrix
  5247. * @returns the unmodified current matrix
  5248. */
  5249. Matrix.prototype.invertToRef = function (other) {
  5250. var l1 = this.m[0];
  5251. var l2 = this.m[1];
  5252. var l3 = this.m[2];
  5253. var l4 = this.m[3];
  5254. var l5 = this.m[4];
  5255. var l6 = this.m[5];
  5256. var l7 = this.m[6];
  5257. var l8 = this.m[7];
  5258. var l9 = this.m[8];
  5259. var l10 = this.m[9];
  5260. var l11 = this.m[10];
  5261. var l12 = this.m[11];
  5262. var l13 = this.m[12];
  5263. var l14 = this.m[13];
  5264. var l15 = this.m[14];
  5265. var l16 = this.m[15];
  5266. var l17 = (l11 * l16) - (l12 * l15);
  5267. var l18 = (l10 * l16) - (l12 * l14);
  5268. var l19 = (l10 * l15) - (l11 * l14);
  5269. var l20 = (l9 * l16) - (l12 * l13);
  5270. var l21 = (l9 * l15) - (l11 * l13);
  5271. var l22 = (l9 * l14) - (l10 * l13);
  5272. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5273. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5274. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5275. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5276. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5277. var l28 = (l7 * l16) - (l8 * l15);
  5278. var l29 = (l6 * l16) - (l8 * l14);
  5279. var l30 = (l6 * l15) - (l7 * l14);
  5280. var l31 = (l5 * l16) - (l8 * l13);
  5281. var l32 = (l5 * l15) - (l7 * l13);
  5282. var l33 = (l5 * l14) - (l6 * l13);
  5283. var l34 = (l7 * l12) - (l8 * l11);
  5284. var l35 = (l6 * l12) - (l8 * l10);
  5285. var l36 = (l6 * l11) - (l7 * l10);
  5286. var l37 = (l5 * l12) - (l8 * l9);
  5287. var l38 = (l5 * l11) - (l7 * l9);
  5288. var l39 = (l5 * l10) - (l6 * l9);
  5289. other.m[0] = l23 * l27;
  5290. other.m[4] = l24 * l27;
  5291. other.m[8] = l25 * l27;
  5292. other.m[12] = l26 * l27;
  5293. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5294. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5295. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5296. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5297. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5298. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5299. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5300. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5301. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5302. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5303. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5304. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5305. other._markAsUpdated();
  5306. return this;
  5307. };
  5308. /**
  5309. * Inserts the translation vector (using 3 floats) in the current matrix
  5310. * @param x defines the 1st component of the translation
  5311. * @param y defines the 2nd component of the translation
  5312. * @param z defines the 3rd component of the translation
  5313. * @returns the current updated matrix
  5314. */
  5315. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5316. this.m[12] = x;
  5317. this.m[13] = y;
  5318. this.m[14] = z;
  5319. this._markAsUpdated();
  5320. return this;
  5321. };
  5322. /**
  5323. * Inserts the translation vector in the current matrix
  5324. * @param vector3 defines the translation to insert
  5325. * @returns the current updated matrix
  5326. */
  5327. Matrix.prototype.setTranslation = function (vector3) {
  5328. this.m[12] = vector3.x;
  5329. this.m[13] = vector3.y;
  5330. this.m[14] = vector3.z;
  5331. this._markAsUpdated();
  5332. return this;
  5333. };
  5334. /**
  5335. * Gets the translation value of the current matrix
  5336. * @returns a new Vector3 as the extracted translation from the matrix
  5337. */
  5338. Matrix.prototype.getTranslation = function () {
  5339. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5340. };
  5341. /**
  5342. * Fill a Vector3 with the extracted translation from the matrix
  5343. * @param result defines the Vector3 where to store the translation
  5344. * @returns the current matrix
  5345. */
  5346. Matrix.prototype.getTranslationToRef = function (result) {
  5347. result.x = this.m[12];
  5348. result.y = this.m[13];
  5349. result.z = this.m[14];
  5350. return this;
  5351. };
  5352. /**
  5353. * Remove rotation and scaling part from the matrix
  5354. * @returns the updated matrix
  5355. */
  5356. Matrix.prototype.removeRotationAndScaling = function () {
  5357. this.setRowFromFloats(0, 1, 0, 0, 0);
  5358. this.setRowFromFloats(1, 0, 1, 0, 0);
  5359. this.setRowFromFloats(2, 0, 0, 1, 0);
  5360. return this;
  5361. };
  5362. /**
  5363. * Multiply two matrices
  5364. * @param other defines the second operand
  5365. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5366. */
  5367. Matrix.prototype.multiply = function (other) {
  5368. var result = new Matrix();
  5369. this.multiplyToRef(other, result);
  5370. return result;
  5371. };
  5372. /**
  5373. * Copy the current matrix from the given one
  5374. * @param other defines the source matrix
  5375. * @returns the current updated matrix
  5376. */
  5377. Matrix.prototype.copyFrom = function (other) {
  5378. for (var index = 0; index < 16; index++) {
  5379. this.m[index] = other.m[index];
  5380. }
  5381. this._markAsUpdated();
  5382. return this;
  5383. };
  5384. /**
  5385. * Populates the given array from the starting index with the current matrix values
  5386. * @param array defines the target array
  5387. * @param offset defines the offset in the target array where to start storing values
  5388. * @returns the current matrix
  5389. */
  5390. Matrix.prototype.copyToArray = function (array, offset) {
  5391. if (offset === void 0) { offset = 0; }
  5392. for (var index = 0; index < 16; index++) {
  5393. array[offset + index] = this.m[index];
  5394. }
  5395. return this;
  5396. };
  5397. /**
  5398. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5399. * @param other defines the second operand
  5400. * @param result defines the matrix where to store the multiplication
  5401. * @returns the current matrix
  5402. */
  5403. Matrix.prototype.multiplyToRef = function (other, result) {
  5404. this.multiplyToArray(other, result.m, 0);
  5405. result._markAsUpdated();
  5406. return this;
  5407. };
  5408. /**
  5409. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5410. * @param other defines the second operand
  5411. * @param result defines the array where to store the multiplication
  5412. * @param offset defines the offset in the target array where to start storing values
  5413. * @returns the current matrix
  5414. */
  5415. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5416. var tm0 = this.m[0];
  5417. var tm1 = this.m[1];
  5418. var tm2 = this.m[2];
  5419. var tm3 = this.m[3];
  5420. var tm4 = this.m[4];
  5421. var tm5 = this.m[5];
  5422. var tm6 = this.m[6];
  5423. var tm7 = this.m[7];
  5424. var tm8 = this.m[8];
  5425. var tm9 = this.m[9];
  5426. var tm10 = this.m[10];
  5427. var tm11 = this.m[11];
  5428. var tm12 = this.m[12];
  5429. var tm13 = this.m[13];
  5430. var tm14 = this.m[14];
  5431. var tm15 = this.m[15];
  5432. var om0 = other.m[0];
  5433. var om1 = other.m[1];
  5434. var om2 = other.m[2];
  5435. var om3 = other.m[3];
  5436. var om4 = other.m[4];
  5437. var om5 = other.m[5];
  5438. var om6 = other.m[6];
  5439. var om7 = other.m[7];
  5440. var om8 = other.m[8];
  5441. var om9 = other.m[9];
  5442. var om10 = other.m[10];
  5443. var om11 = other.m[11];
  5444. var om12 = other.m[12];
  5445. var om13 = other.m[13];
  5446. var om14 = other.m[14];
  5447. var om15 = other.m[15];
  5448. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5449. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5450. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5451. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5452. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5453. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5454. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5455. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5456. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5457. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5458. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5459. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5460. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5461. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5462. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5463. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5464. return this;
  5465. };
  5466. /**
  5467. * Check equality between this matrix and a second one
  5468. * @param value defines the second matrix to compare
  5469. * @returns true is the current matrix and the given one values are strictly equal
  5470. */
  5471. Matrix.prototype.equals = function (value) {
  5472. return value &&
  5473. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5474. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5475. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5476. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5477. };
  5478. /**
  5479. * Clone the current matrix
  5480. * @returns a new matrix from the current matrix
  5481. */
  5482. Matrix.prototype.clone = function () {
  5483. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5484. };
  5485. /**
  5486. * Returns the name of the current matrix class
  5487. * @returns the string "Matrix"
  5488. */
  5489. Matrix.prototype.getClassName = function () {
  5490. return "Matrix";
  5491. };
  5492. /**
  5493. * Gets the hash code of the current matrix
  5494. * @returns the hash code
  5495. */
  5496. Matrix.prototype.getHashCode = function () {
  5497. var hash = this.m[0] || 0;
  5498. for (var i = 1; i < 16; i++) {
  5499. hash = (hash * 397) ^ (this.m[i] || 0);
  5500. }
  5501. return hash;
  5502. };
  5503. /**
  5504. * Decomposes the current Matrix into a translation, rotation and scaling components
  5505. * @param scale defines the scale vector3 given as a reference to update
  5506. * @param rotation defines the rotation quaternion given as a reference to update
  5507. * @param translation defines the translation vector3 given as a reference to update
  5508. * @returns true if operation was successful
  5509. */
  5510. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5511. if (translation) {
  5512. translation.x = this.m[12];
  5513. translation.y = this.m[13];
  5514. translation.z = this.m[14];
  5515. }
  5516. scale = scale || MathTmp.Vector3[0];
  5517. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5518. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5519. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5520. if (this.determinant() <= 0) {
  5521. scale.y *= -1;
  5522. }
  5523. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5524. if (rotation) {
  5525. rotation.x = 0;
  5526. rotation.y = 0;
  5527. rotation.z = 0;
  5528. rotation.w = 1;
  5529. }
  5530. return false;
  5531. }
  5532. if (rotation) {
  5533. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5534. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5535. }
  5536. return true;
  5537. };
  5538. /**
  5539. * Gets specific row of the matrix
  5540. * @param index defines the number of the row to get
  5541. * @returns the index-th row of the current matrix as a new Vector4
  5542. */
  5543. Matrix.prototype.getRow = function (index) {
  5544. if (index < 0 || index > 3) {
  5545. return null;
  5546. }
  5547. var i = index * 4;
  5548. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5549. };
  5550. /**
  5551. * Sets the index-th row of the current matrix to the vector4 values
  5552. * @param index defines the number of the row to set
  5553. * @param row defines the target vector4
  5554. * @returns the updated current matrix
  5555. */
  5556. Matrix.prototype.setRow = function (index, row) {
  5557. if (index < 0 || index > 3) {
  5558. return this;
  5559. }
  5560. var i = index * 4;
  5561. this.m[i + 0] = row.x;
  5562. this.m[i + 1] = row.y;
  5563. this.m[i + 2] = row.z;
  5564. this.m[i + 3] = row.w;
  5565. this._markAsUpdated();
  5566. return this;
  5567. };
  5568. /**
  5569. * Compute the transpose of the matrix
  5570. * @returns the new transposed matrix
  5571. */
  5572. Matrix.prototype.transpose = function () {
  5573. return Matrix.Transpose(this);
  5574. };
  5575. /**
  5576. * Compute the transpose of the matrix and store it in a given matrix
  5577. * @param result defines the target matrix
  5578. * @returns the current matrix
  5579. */
  5580. Matrix.prototype.transposeToRef = function (result) {
  5581. Matrix.TransposeToRef(this, result);
  5582. return this;
  5583. };
  5584. /**
  5585. * Sets the index-th row of the current matrix with the given 4 x float values
  5586. * @param index defines the row index
  5587. * @param x defines the x component to set
  5588. * @param y defines the y component to set
  5589. * @param z defines the z component to set
  5590. * @param w defines the w component to set
  5591. * @returns the updated current matrix
  5592. */
  5593. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5594. if (index < 0 || index > 3) {
  5595. return this;
  5596. }
  5597. var i = index * 4;
  5598. this.m[i + 0] = x;
  5599. this.m[i + 1] = y;
  5600. this.m[i + 2] = z;
  5601. this.m[i + 3] = w;
  5602. this._markAsUpdated();
  5603. return this;
  5604. };
  5605. /**
  5606. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5607. * @param scale defines the scale factor
  5608. * @returns a new matrix
  5609. */
  5610. Matrix.prototype.scale = function (scale) {
  5611. var result = new Matrix();
  5612. this.scaleToRef(scale, result);
  5613. return result;
  5614. };
  5615. /**
  5616. * Scale the current matrix values by a factor to a given result matrix
  5617. * @param scale defines the scale factor
  5618. * @param result defines the matrix to store the result
  5619. * @returns the current matrix
  5620. */
  5621. Matrix.prototype.scaleToRef = function (scale, result) {
  5622. for (var index = 0; index < 16; index++) {
  5623. result.m[index] = this.m[index] * scale;
  5624. }
  5625. result._markAsUpdated();
  5626. return this;
  5627. };
  5628. /**
  5629. * Scale the current matrix values by a factor and add the result to a given matrix
  5630. * @param scale defines the scale factor
  5631. * @param result defines the Matrix to store the result
  5632. * @returns the current matrix
  5633. */
  5634. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5635. for (var index = 0; index < 16; index++) {
  5636. result.m[index] += this.m[index] * scale;
  5637. }
  5638. result._markAsUpdated();
  5639. return this;
  5640. };
  5641. /**
  5642. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5643. * @param ref matrix to store the result
  5644. */
  5645. Matrix.prototype.toNormalMatrix = function (ref) {
  5646. this.invertToRef(ref);
  5647. ref.transpose();
  5648. var m = ref.m;
  5649. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5650. };
  5651. /**
  5652. * Gets only rotation part of the current matrix
  5653. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5654. */
  5655. Matrix.prototype.getRotationMatrix = function () {
  5656. var result = Matrix.Identity();
  5657. this.getRotationMatrixToRef(result);
  5658. return result;
  5659. };
  5660. /**
  5661. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5662. * @param result defines the target matrix to store data to
  5663. * @returns the current matrix
  5664. */
  5665. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5666. var m = this.m;
  5667. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5668. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5669. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5670. if (this.determinant() <= 0) {
  5671. sy *= -1;
  5672. }
  5673. if (sx === 0 || sy === 0 || sz === 0) {
  5674. Matrix.IdentityToRef(result);
  5675. }
  5676. else {
  5677. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5678. }
  5679. return this;
  5680. };
  5681. // Statics
  5682. /**
  5683. * Creates a matrix from an array
  5684. * @param array defines the source array
  5685. * @param offset defines an offset in the source array
  5686. * @returns a new Matrix set from the starting index of the given array
  5687. */
  5688. Matrix.FromArray = function (array, offset) {
  5689. var result = new Matrix();
  5690. if (!offset) {
  5691. offset = 0;
  5692. }
  5693. Matrix.FromArrayToRef(array, offset, result);
  5694. return result;
  5695. };
  5696. /**
  5697. * Copy the content of an array into a given matrix
  5698. * @param array defines the source array
  5699. * @param offset defines an offset in the source array
  5700. * @param result defines the target matrix
  5701. */
  5702. Matrix.FromArrayToRef = function (array, offset, result) {
  5703. for (var index = 0; index < 16; index++) {
  5704. result.m[index] = array[index + offset];
  5705. }
  5706. result._markAsUpdated();
  5707. };
  5708. /**
  5709. * Stores an array into a matrix after having multiplied each component by a given factor
  5710. * @param array defines the source array
  5711. * @param offset defines the offset in the source array
  5712. * @param scale defines the scaling factor
  5713. * @param result defines the target matrix
  5714. */
  5715. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5716. for (var index = 0; index < 16; index++) {
  5717. result.m[index] = array[index + offset] * scale;
  5718. }
  5719. result._markAsUpdated();
  5720. };
  5721. /**
  5722. * Stores a list of values (16) inside a given matrix
  5723. * @param initialM11 defines 1st value of 1st row
  5724. * @param initialM12 defines 2nd value of 1st row
  5725. * @param initialM13 defines 3rd value of 1st row
  5726. * @param initialM14 defines 4th value of 1st row
  5727. * @param initialM21 defines 1st value of 2nd row
  5728. * @param initialM22 defines 2nd value of 2nd row
  5729. * @param initialM23 defines 3rd value of 2nd row
  5730. * @param initialM24 defines 4th value of 2nd row
  5731. * @param initialM31 defines 1st value of 3rd row
  5732. * @param initialM32 defines 2nd value of 3rd row
  5733. * @param initialM33 defines 3rd value of 3rd row
  5734. * @param initialM34 defines 4th value of 3rd row
  5735. * @param initialM41 defines 1st value of 4th row
  5736. * @param initialM42 defines 2nd value of 4th row
  5737. * @param initialM43 defines 3rd value of 4th row
  5738. * @param initialM44 defines 4th value of 4th row
  5739. * @param result defines the target matrix
  5740. */
  5741. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5742. result.m[0] = initialM11;
  5743. result.m[1] = initialM12;
  5744. result.m[2] = initialM13;
  5745. result.m[3] = initialM14;
  5746. result.m[4] = initialM21;
  5747. result.m[5] = initialM22;
  5748. result.m[6] = initialM23;
  5749. result.m[7] = initialM24;
  5750. result.m[8] = initialM31;
  5751. result.m[9] = initialM32;
  5752. result.m[10] = initialM33;
  5753. result.m[11] = initialM34;
  5754. result.m[12] = initialM41;
  5755. result.m[13] = initialM42;
  5756. result.m[14] = initialM43;
  5757. result.m[15] = initialM44;
  5758. result._markAsUpdated();
  5759. };
  5760. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5761. /**
  5762. * Gets an identity matrix that must not be updated
  5763. */
  5764. get: function () {
  5765. return Matrix._identityReadOnly;
  5766. },
  5767. enumerable: true,
  5768. configurable: true
  5769. });
  5770. /**
  5771. * Creates new matrix from a list of values (16)
  5772. * @param initialM11 defines 1st value of 1st row
  5773. * @param initialM12 defines 2nd value of 1st row
  5774. * @param initialM13 defines 3rd value of 1st row
  5775. * @param initialM14 defines 4th value of 1st row
  5776. * @param initialM21 defines 1st value of 2nd row
  5777. * @param initialM22 defines 2nd value of 2nd row
  5778. * @param initialM23 defines 3rd value of 2nd row
  5779. * @param initialM24 defines 4th value of 2nd row
  5780. * @param initialM31 defines 1st value of 3rd row
  5781. * @param initialM32 defines 2nd value of 3rd row
  5782. * @param initialM33 defines 3rd value of 3rd row
  5783. * @param initialM34 defines 4th value of 3rd row
  5784. * @param initialM41 defines 1st value of 4th row
  5785. * @param initialM42 defines 2nd value of 4th row
  5786. * @param initialM43 defines 3rd value of 4th row
  5787. * @param initialM44 defines 4th value of 4th row
  5788. * @returns the new matrix
  5789. */
  5790. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5791. var result = new Matrix();
  5792. result.m[0] = initialM11;
  5793. result.m[1] = initialM12;
  5794. result.m[2] = initialM13;
  5795. result.m[3] = initialM14;
  5796. result.m[4] = initialM21;
  5797. result.m[5] = initialM22;
  5798. result.m[6] = initialM23;
  5799. result.m[7] = initialM24;
  5800. result.m[8] = initialM31;
  5801. result.m[9] = initialM32;
  5802. result.m[10] = initialM33;
  5803. result.m[11] = initialM34;
  5804. result.m[12] = initialM41;
  5805. result.m[13] = initialM42;
  5806. result.m[14] = initialM43;
  5807. result.m[15] = initialM44;
  5808. return result;
  5809. };
  5810. /**
  5811. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5812. * @param scale defines the scale vector3
  5813. * @param rotation defines the rotation quaternion
  5814. * @param translation defines the translation vector3
  5815. * @returns a new matrix
  5816. */
  5817. Matrix.Compose = function (scale, rotation, translation) {
  5818. var result = Matrix.Identity();
  5819. Matrix.ComposeToRef(scale, rotation, translation, result);
  5820. return result;
  5821. };
  5822. /**
  5823. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5824. * @param scale defines the scale vector3
  5825. * @param rotation defines the rotation quaternion
  5826. * @param translation defines the translation vector3
  5827. * @param result defines the target matrix
  5828. */
  5829. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5830. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5831. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5832. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5833. result.setTranslation(translation);
  5834. };
  5835. /**
  5836. * Creates a new identity matrix
  5837. * @returns a new identity matrix
  5838. */
  5839. Matrix.Identity = function () {
  5840. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5841. };
  5842. /**
  5843. * Creates a new identity matrix and stores the result in a given matrix
  5844. * @param result defines the target matrix
  5845. */
  5846. Matrix.IdentityToRef = function (result) {
  5847. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5848. };
  5849. /**
  5850. * Creates a new zero matrix
  5851. * @returns a new zero matrix
  5852. */
  5853. Matrix.Zero = function () {
  5854. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5855. };
  5856. /**
  5857. * Creates a new rotation matrix for "angle" radians around the X axis
  5858. * @param angle defines the angle (in radians) to use
  5859. * @return the new matrix
  5860. */
  5861. Matrix.RotationX = function (angle) {
  5862. var result = new Matrix();
  5863. Matrix.RotationXToRef(angle, result);
  5864. return result;
  5865. };
  5866. /**
  5867. * Creates a new matrix as the invert of a given matrix
  5868. * @param source defines the source matrix
  5869. * @returns the new matrix
  5870. */
  5871. Matrix.Invert = function (source) {
  5872. var result = new Matrix();
  5873. source.invertToRef(result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5878. * @param angle defines the angle (in radians) to use
  5879. * @param result defines the target matrix
  5880. */
  5881. Matrix.RotationXToRef = function (angle, result) {
  5882. var s = Math.sin(angle);
  5883. var c = Math.cos(angle);
  5884. result.m[0] = 1.0;
  5885. result.m[15] = 1.0;
  5886. result.m[5] = c;
  5887. result.m[10] = c;
  5888. result.m[9] = -s;
  5889. result.m[6] = s;
  5890. result.m[1] = 0.0;
  5891. result.m[2] = 0.0;
  5892. result.m[3] = 0.0;
  5893. result.m[4] = 0.0;
  5894. result.m[7] = 0.0;
  5895. result.m[8] = 0.0;
  5896. result.m[11] = 0.0;
  5897. result.m[12] = 0.0;
  5898. result.m[13] = 0.0;
  5899. result.m[14] = 0.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a new rotation matrix for "angle" radians around the Y axis
  5904. * @param angle defines the angle (in radians) to use
  5905. * @return the new matrix
  5906. */
  5907. Matrix.RotationY = function (angle) {
  5908. var result = new Matrix();
  5909. Matrix.RotationYToRef(angle, result);
  5910. return result;
  5911. };
  5912. /**
  5913. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5914. * @param angle defines the angle (in radians) to use
  5915. * @param result defines the target matrix
  5916. */
  5917. Matrix.RotationYToRef = function (angle, result) {
  5918. var s = Math.sin(angle);
  5919. var c = Math.cos(angle);
  5920. result.m[5] = 1.0;
  5921. result.m[15] = 1.0;
  5922. result.m[0] = c;
  5923. result.m[2] = -s;
  5924. result.m[8] = s;
  5925. result.m[10] = c;
  5926. result.m[1] = 0.0;
  5927. result.m[3] = 0.0;
  5928. result.m[4] = 0.0;
  5929. result.m[6] = 0.0;
  5930. result.m[7] = 0.0;
  5931. result.m[9] = 0.0;
  5932. result.m[11] = 0.0;
  5933. result.m[12] = 0.0;
  5934. result.m[13] = 0.0;
  5935. result.m[14] = 0.0;
  5936. result._markAsUpdated();
  5937. };
  5938. /**
  5939. * Creates a new rotation matrix for "angle" radians around the Z axis
  5940. * @param angle defines the angle (in radians) to use
  5941. * @return the new matrix
  5942. */
  5943. Matrix.RotationZ = function (angle) {
  5944. var result = new Matrix();
  5945. Matrix.RotationZToRef(angle, result);
  5946. return result;
  5947. };
  5948. /**
  5949. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5950. * @param angle defines the angle (in radians) to use
  5951. * @param result defines the target matrix
  5952. */
  5953. Matrix.RotationZToRef = function (angle, result) {
  5954. var s = Math.sin(angle);
  5955. var c = Math.cos(angle);
  5956. result.m[10] = 1.0;
  5957. result.m[15] = 1.0;
  5958. result.m[0] = c;
  5959. result.m[1] = s;
  5960. result.m[4] = -s;
  5961. result.m[5] = c;
  5962. result.m[2] = 0.0;
  5963. result.m[3] = 0.0;
  5964. result.m[6] = 0.0;
  5965. result.m[7] = 0.0;
  5966. result.m[8] = 0.0;
  5967. result.m[9] = 0.0;
  5968. result.m[11] = 0.0;
  5969. result.m[12] = 0.0;
  5970. result.m[13] = 0.0;
  5971. result.m[14] = 0.0;
  5972. result._markAsUpdated();
  5973. };
  5974. /**
  5975. * Creates a new rotation matrix for "angle" radians around the given axis
  5976. * @param axis defines the axis to use
  5977. * @param angle defines the angle (in radians) to use
  5978. * @return the new matrix
  5979. */
  5980. Matrix.RotationAxis = function (axis, angle) {
  5981. var result = Matrix.Zero();
  5982. Matrix.RotationAxisToRef(axis, angle, result);
  5983. return result;
  5984. };
  5985. /**
  5986. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5987. * @param axis defines the axis to use
  5988. * @param angle defines the angle (in radians) to use
  5989. * @param result defines the target matrix
  5990. */
  5991. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5992. var s = Math.sin(-angle);
  5993. var c = Math.cos(-angle);
  5994. var c1 = 1 - c;
  5995. axis.normalize();
  5996. result.m[0] = (axis.x * axis.x) * c1 + c;
  5997. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5998. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5999. result.m[3] = 0.0;
  6000. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6001. result.m[5] = (axis.y * axis.y) * c1 + c;
  6002. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6003. result.m[7] = 0.0;
  6004. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6005. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6006. result.m[10] = (axis.z * axis.z) * c1 + c;
  6007. result.m[11] = 0.0;
  6008. result.m[15] = 1.0;
  6009. result._markAsUpdated();
  6010. };
  6011. /**
  6012. * Creates a rotation matrix
  6013. * @param yaw defines the yaw angle in radians (Y axis)
  6014. * @param pitch defines the pitch angle in radians (X axis)
  6015. * @param roll defines the roll angle in radians (X axis)
  6016. * @returns the new rotation matrix
  6017. */
  6018. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6019. var result = new Matrix();
  6020. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6021. return result;
  6022. };
  6023. /**
  6024. * Creates a rotation matrix and stores it in a given matrix
  6025. * @param yaw defines the yaw angle in radians (Y axis)
  6026. * @param pitch defines the pitch angle in radians (X axis)
  6027. * @param roll defines the roll angle in radians (X axis)
  6028. * @param result defines the target matrix
  6029. */
  6030. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6031. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6032. this._tempQuaternion.toRotationMatrix(result);
  6033. };
  6034. /**
  6035. * Creates a scaling matrix
  6036. * @param x defines the scale factor on X axis
  6037. * @param y defines the scale factor on Y axis
  6038. * @param z defines the scale factor on Z axis
  6039. * @returns the new matrix
  6040. */
  6041. Matrix.Scaling = function (x, y, z) {
  6042. var result = Matrix.Zero();
  6043. Matrix.ScalingToRef(x, y, z, result);
  6044. return result;
  6045. };
  6046. /**
  6047. * Creates a scaling matrix and stores it in a given matrix
  6048. * @param x defines the scale factor on X axis
  6049. * @param y defines the scale factor on Y axis
  6050. * @param z defines the scale factor on Z axis
  6051. * @param result defines the target matrix
  6052. */
  6053. Matrix.ScalingToRef = function (x, y, z, result) {
  6054. result.m[0] = x;
  6055. result.m[1] = 0.0;
  6056. result.m[2] = 0.0;
  6057. result.m[3] = 0.0;
  6058. result.m[4] = 0.0;
  6059. result.m[5] = y;
  6060. result.m[6] = 0.0;
  6061. result.m[7] = 0.0;
  6062. result.m[8] = 0.0;
  6063. result.m[9] = 0.0;
  6064. result.m[10] = z;
  6065. result.m[11] = 0.0;
  6066. result.m[12] = 0.0;
  6067. result.m[13] = 0.0;
  6068. result.m[14] = 0.0;
  6069. result.m[15] = 1.0;
  6070. result._markAsUpdated();
  6071. };
  6072. /**
  6073. * Creates a translation matrix
  6074. * @param x defines the translation on X axis
  6075. * @param y defines the translation on Y axis
  6076. * @param z defines the translationon Z axis
  6077. * @returns the new matrix
  6078. */
  6079. Matrix.Translation = function (x, y, z) {
  6080. var result = Matrix.Identity();
  6081. Matrix.TranslationToRef(x, y, z, result);
  6082. return result;
  6083. };
  6084. /**
  6085. * Creates a translation matrix and stores it in a given matrix
  6086. * @param x defines the translation on X axis
  6087. * @param y defines the translation on Y axis
  6088. * @param z defines the translationon Z axis
  6089. * @param result defines the target matrix
  6090. */
  6091. Matrix.TranslationToRef = function (x, y, z, result) {
  6092. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  6093. };
  6094. /**
  6095. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6096. * @param startValue defines the start value
  6097. * @param endValue defines the end value
  6098. * @param gradient defines the gradient factor
  6099. * @returns the new matrix
  6100. */
  6101. Matrix.Lerp = function (startValue, endValue, gradient) {
  6102. var result = Matrix.Zero();
  6103. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6104. return result;
  6105. };
  6106. /**
  6107. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6108. * @param startValue defines the start value
  6109. * @param endValue defines the end value
  6110. * @param gradient defines the gradient factor
  6111. * @param result defines the Matrix object where to store data
  6112. */
  6113. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6114. for (var index = 0; index < 16; index++) {
  6115. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6116. }
  6117. result._markAsUpdated();
  6118. };
  6119. /**
  6120. * Builds a new matrix whose values are computed by:
  6121. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6122. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6123. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6124. * @param startValue defines the first matrix
  6125. * @param endValue defines the second matrix
  6126. * @param gradient defines the gradient between the two matrices
  6127. * @returns the new matrix
  6128. */
  6129. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6130. var result = Matrix.Zero();
  6131. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6132. return result;
  6133. };
  6134. /**
  6135. * Update a matrix to values which are computed by:
  6136. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6137. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6138. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6139. * @param startValue defines the first matrix
  6140. * @param endValue defines the second matrix
  6141. * @param gradient defines the gradient between the two matrices
  6142. * @param result defines the target matrix
  6143. */
  6144. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6145. var startScale = MathTmp.Vector3[0];
  6146. var startRotation = MathTmp.Quaternion[0];
  6147. var startTranslation = MathTmp.Vector3[1];
  6148. startValue.decompose(startScale, startRotation, startTranslation);
  6149. var endScale = MathTmp.Vector3[2];
  6150. var endRotation = MathTmp.Quaternion[1];
  6151. var endTranslation = MathTmp.Vector3[3];
  6152. endValue.decompose(endScale, endRotation, endTranslation);
  6153. var resultScale = MathTmp.Vector3[4];
  6154. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6155. var resultRotation = MathTmp.Quaternion[2];
  6156. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6157. var resultTranslation = MathTmp.Vector3[5];
  6158. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6159. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6160. };
  6161. /**
  6162. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6163. * This function works in left handed mode
  6164. * @param eye defines the final position of the entity
  6165. * @param target defines where the entity should look at
  6166. * @param up defines the up vector for the entity
  6167. * @returns the new matrix
  6168. */
  6169. Matrix.LookAtLH = function (eye, target, up) {
  6170. var result = Matrix.Zero();
  6171. Matrix.LookAtLHToRef(eye, target, up, result);
  6172. return result;
  6173. };
  6174. /**
  6175. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6176. * This function works in left handed mode
  6177. * @param eye defines the final position of the entity
  6178. * @param target defines where the entity should look at
  6179. * @param up defines the up vector for the entity
  6180. * @param result defines the target matrix
  6181. */
  6182. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6183. // Z axis
  6184. target.subtractToRef(eye, this._zAxis);
  6185. this._zAxis.normalize();
  6186. // X axis
  6187. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6188. if (this._xAxis.lengthSquared() === 0) {
  6189. this._xAxis.x = 1.0;
  6190. }
  6191. else {
  6192. this._xAxis.normalize();
  6193. }
  6194. // Y axis
  6195. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6196. this._yAxis.normalize();
  6197. // Eye angles
  6198. var ex = -Vector3.Dot(this._xAxis, eye);
  6199. var ey = -Vector3.Dot(this._yAxis, eye);
  6200. var ez = -Vector3.Dot(this._zAxis, eye);
  6201. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6202. };
  6203. /**
  6204. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6205. * This function works in right handed mode
  6206. * @param eye defines the final position of the entity
  6207. * @param target defines where the entity should look at
  6208. * @param up defines the up vector for the entity
  6209. * @returns the new matrix
  6210. */
  6211. Matrix.LookAtRH = function (eye, target, up) {
  6212. var result = Matrix.Zero();
  6213. Matrix.LookAtRHToRef(eye, target, up, result);
  6214. return result;
  6215. };
  6216. /**
  6217. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6218. * This function works in right handed mode
  6219. * @param eye defines the final position of the entity
  6220. * @param target defines where the entity should look at
  6221. * @param up defines the up vector for the entity
  6222. * @param result defines the target matrix
  6223. */
  6224. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6225. // Z axis
  6226. eye.subtractToRef(target, this._zAxis);
  6227. this._zAxis.normalize();
  6228. // X axis
  6229. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6230. if (this._xAxis.lengthSquared() === 0) {
  6231. this._xAxis.x = 1.0;
  6232. }
  6233. else {
  6234. this._xAxis.normalize();
  6235. }
  6236. // Y axis
  6237. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6238. this._yAxis.normalize();
  6239. // Eye angles
  6240. var ex = -Vector3.Dot(this._xAxis, eye);
  6241. var ey = -Vector3.Dot(this._yAxis, eye);
  6242. var ez = -Vector3.Dot(this._zAxis, eye);
  6243. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6244. };
  6245. /**
  6246. * Create a left-handed orthographic projection matrix
  6247. * @param width defines the viewport width
  6248. * @param height defines the viewport height
  6249. * @param znear defines the near clip plane
  6250. * @param zfar defines the far clip plane
  6251. * @returns a new matrix as a left-handed orthographic projection matrix
  6252. */
  6253. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6254. var matrix = Matrix.Zero();
  6255. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6256. return matrix;
  6257. };
  6258. /**
  6259. * Store a left-handed orthographic projection to a given matrix
  6260. * @param width defines the viewport width
  6261. * @param height defines the viewport height
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @param result defines the target matrix
  6265. */
  6266. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6267. var n = znear;
  6268. var f = zfar;
  6269. var a = 2.0 / width;
  6270. var b = 2.0 / height;
  6271. var c = 2.0 / (f - n);
  6272. var d = -(f + n) / (f - n);
  6273. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6274. };
  6275. /**
  6276. * Create a left-handed orthographic projection matrix
  6277. * @param left defines the viewport left coordinate
  6278. * @param right defines the viewport right coordinate
  6279. * @param bottom defines the viewport bottom coordinate
  6280. * @param top defines the viewport top coordinate
  6281. * @param znear defines the near clip plane
  6282. * @param zfar defines the far clip plane
  6283. * @returns a new matrix as a left-handed orthographic projection matrix
  6284. */
  6285. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6286. var matrix = Matrix.Zero();
  6287. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6288. return matrix;
  6289. };
  6290. /**
  6291. * Stores a left-handed orthographic projection into a given matrix
  6292. * @param left defines the viewport left coordinate
  6293. * @param right defines the viewport right coordinate
  6294. * @param bottom defines the viewport bottom coordinate
  6295. * @param top defines the viewport top coordinate
  6296. * @param znear defines the near clip plane
  6297. * @param zfar defines the far clip plane
  6298. * @param result defines the target matrix
  6299. */
  6300. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6301. var n = znear;
  6302. var f = zfar;
  6303. var a = 2.0 / (right - left);
  6304. var b = 2.0 / (top - bottom);
  6305. var c = 2.0 / (f - n);
  6306. var d = -(f + n) / (f - n);
  6307. var i0 = (left + right) / (left - right);
  6308. var i1 = (top + bottom) / (bottom - top);
  6309. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6310. };
  6311. /**
  6312. * Creates a right-handed orthographic projection matrix
  6313. * @param left defines the viewport left coordinate
  6314. * @param right defines the viewport right coordinate
  6315. * @param bottom defines the viewport bottom coordinate
  6316. * @param top defines the viewport top coordinate
  6317. * @param znear defines the near clip plane
  6318. * @param zfar defines the far clip plane
  6319. * @returns a new matrix as a right-handed orthographic projection matrix
  6320. */
  6321. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6322. var matrix = Matrix.Zero();
  6323. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6324. return matrix;
  6325. };
  6326. /**
  6327. * Stores a right-handed orthographic projection into a given matrix
  6328. * @param left defines the viewport left coordinate
  6329. * @param right defines the viewport right coordinate
  6330. * @param bottom defines the viewport bottom coordinate
  6331. * @param top defines the viewport top coordinate
  6332. * @param znear defines the near clip plane
  6333. * @param zfar defines the far clip plane
  6334. * @param result defines the target matrix
  6335. */
  6336. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6337. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6338. result.m[10] *= -1.0;
  6339. };
  6340. /**
  6341. * Creates a left-handed perspective projection matrix
  6342. * @param width defines the viewport width
  6343. * @param height defines the viewport height
  6344. * @param znear defines the near clip plane
  6345. * @param zfar defines the far clip plane
  6346. * @returns a new matrix as a left-handed perspective projection matrix
  6347. */
  6348. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6349. var matrix = Matrix.Zero();
  6350. var n = znear;
  6351. var f = zfar;
  6352. var a = 2.0 * n / width;
  6353. var b = 2.0 * n / height;
  6354. var c = (f + n) / (f - n);
  6355. var d = -2.0 * f * n / (f - n);
  6356. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6357. return matrix;
  6358. };
  6359. /**
  6360. * Creates a left-handed perspective projection matrix
  6361. * @param fov defines the horizontal field of view
  6362. * @param aspect defines the aspect ratio
  6363. * @param znear defines the near clip plane
  6364. * @param zfar defines the far clip plane
  6365. * @returns a new matrix as a left-handed perspective projection matrix
  6366. */
  6367. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6368. var matrix = Matrix.Zero();
  6369. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6370. return matrix;
  6371. };
  6372. /**
  6373. * Stores a left-handed perspective projection into a given matrix
  6374. * @param fov defines the horizontal field of view
  6375. * @param aspect defines the aspect ratio
  6376. * @param znear defines the near clip plane
  6377. * @param zfar defines the far clip plane
  6378. * @param result defines the target matrix
  6379. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6380. */
  6381. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6382. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6383. var n = znear;
  6384. var f = zfar;
  6385. var t = 1.0 / (Math.tan(fov * 0.5));
  6386. var a = isVerticalFovFixed ? (t / aspect) : t;
  6387. var b = isVerticalFovFixed ? t : (t * aspect);
  6388. var c = (f + n) / (f - n);
  6389. var d = -2.0 * f * n / (f - n);
  6390. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6391. };
  6392. /**
  6393. * Creates a right-handed perspective projection matrix
  6394. * @param fov defines the horizontal field of view
  6395. * @param aspect defines the aspect ratio
  6396. * @param znear defines the near clip plane
  6397. * @param zfar defines the far clip plane
  6398. * @returns a new matrix as a right-handed perspective projection matrix
  6399. */
  6400. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6401. var matrix = Matrix.Zero();
  6402. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6403. return matrix;
  6404. };
  6405. /**
  6406. * Stores a right-handed perspective projection into a given matrix
  6407. * @param fov defines the horizontal field of view
  6408. * @param aspect defines the aspect ratio
  6409. * @param znear defines the near clip plane
  6410. * @param zfar defines the far clip plane
  6411. * @param result defines the target matrix
  6412. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6413. */
  6414. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6415. //alternatively this could be expressed as:
  6416. // m = PerspectiveFovLHToRef
  6417. // m[10] *= -1.0;
  6418. // m[11] *= -1.0;
  6419. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6420. var n = znear;
  6421. var f = zfar;
  6422. var t = 1.0 / (Math.tan(fov * 0.5));
  6423. var a = isVerticalFovFixed ? (t / aspect) : t;
  6424. var b = isVerticalFovFixed ? t : (t * aspect);
  6425. var c = -(f + n) / (f - n);
  6426. var d = -2 * f * n / (f - n);
  6427. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6428. };
  6429. /**
  6430. * Stores a perspective projection for WebVR info a given matrix
  6431. * @param fov defines the field of view
  6432. * @param znear defines the near clip plane
  6433. * @param zfar defines the far clip plane
  6434. * @param result defines the target matrix
  6435. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6436. */
  6437. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6438. if (rightHanded === void 0) { rightHanded = false; }
  6439. var rightHandedFactor = rightHanded ? -1 : 1;
  6440. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6441. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6442. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6443. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6444. var xScale = 2.0 / (leftTan + rightTan);
  6445. var yScale = 2.0 / (upTan + downTan);
  6446. result.m[0] = xScale;
  6447. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6448. result.m[5] = yScale;
  6449. result.m[6] = result.m[7] = 0.0;
  6450. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6451. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6452. result.m[10] = -zfar / (znear - zfar);
  6453. result.m[11] = 1.0 * rightHandedFactor;
  6454. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6455. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6456. result._markAsUpdated();
  6457. };
  6458. /**
  6459. * Computes a complete transformation matrix
  6460. * @param viewport defines the viewport to use
  6461. * @param world defines the world matrix
  6462. * @param view defines the view matrix
  6463. * @param projection defines the projection matrix
  6464. * @param zmin defines the near clip plane
  6465. * @param zmax defines the far clip plane
  6466. * @returns the transformation matrix
  6467. */
  6468. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6469. var cw = viewport.width;
  6470. var ch = viewport.height;
  6471. var cx = viewport.x;
  6472. var cy = viewport.y;
  6473. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6474. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6475. };
  6476. /**
  6477. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6478. * @param matrix defines the matrix to use
  6479. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6480. */
  6481. Matrix.GetAsMatrix2x2 = function (matrix) {
  6482. return new Float32Array([
  6483. matrix.m[0], matrix.m[1],
  6484. matrix.m[4], matrix.m[5]
  6485. ]);
  6486. };
  6487. /**
  6488. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6489. * @param matrix defines the matrix to use
  6490. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6491. */
  6492. Matrix.GetAsMatrix3x3 = function (matrix) {
  6493. return new Float32Array([
  6494. matrix.m[0], matrix.m[1], matrix.m[2],
  6495. matrix.m[4], matrix.m[5], matrix.m[6],
  6496. matrix.m[8], matrix.m[9], matrix.m[10]
  6497. ]);
  6498. };
  6499. /**
  6500. * Compute the transpose of a given matrix
  6501. * @param matrix defines the matrix to transpose
  6502. * @returns the new matrix
  6503. */
  6504. Matrix.Transpose = function (matrix) {
  6505. var result = new Matrix();
  6506. Matrix.TransposeToRef(matrix, result);
  6507. return result;
  6508. };
  6509. /**
  6510. * Compute the transpose of a matrix and store it in a target matrix
  6511. * @param matrix defines the matrix to transpose
  6512. * @param result defines the target matrix
  6513. */
  6514. Matrix.TransposeToRef = function (matrix, result) {
  6515. result.m[0] = matrix.m[0];
  6516. result.m[1] = matrix.m[4];
  6517. result.m[2] = matrix.m[8];
  6518. result.m[3] = matrix.m[12];
  6519. result.m[4] = matrix.m[1];
  6520. result.m[5] = matrix.m[5];
  6521. result.m[6] = matrix.m[9];
  6522. result.m[7] = matrix.m[13];
  6523. result.m[8] = matrix.m[2];
  6524. result.m[9] = matrix.m[6];
  6525. result.m[10] = matrix.m[10];
  6526. result.m[11] = matrix.m[14];
  6527. result.m[12] = matrix.m[3];
  6528. result.m[13] = matrix.m[7];
  6529. result.m[14] = matrix.m[11];
  6530. result.m[15] = matrix.m[15];
  6531. };
  6532. /**
  6533. * Computes a reflection matrix from a plane
  6534. * @param plane defines the reflection plane
  6535. * @returns a new matrix
  6536. */
  6537. Matrix.Reflection = function (plane) {
  6538. var matrix = new Matrix();
  6539. Matrix.ReflectionToRef(plane, matrix);
  6540. return matrix;
  6541. };
  6542. /**
  6543. * Computes a reflection matrix from a plane
  6544. * @param plane defines the reflection plane
  6545. * @param result defines the target matrix
  6546. */
  6547. Matrix.ReflectionToRef = function (plane, result) {
  6548. plane.normalize();
  6549. var x = plane.normal.x;
  6550. var y = plane.normal.y;
  6551. var z = plane.normal.z;
  6552. var temp = -2 * x;
  6553. var temp2 = -2 * y;
  6554. var temp3 = -2 * z;
  6555. result.m[0] = (temp * x) + 1;
  6556. result.m[1] = temp2 * x;
  6557. result.m[2] = temp3 * x;
  6558. result.m[3] = 0.0;
  6559. result.m[4] = temp * y;
  6560. result.m[5] = (temp2 * y) + 1;
  6561. result.m[6] = temp3 * y;
  6562. result.m[7] = 0.0;
  6563. result.m[8] = temp * z;
  6564. result.m[9] = temp2 * z;
  6565. result.m[10] = (temp3 * z) + 1;
  6566. result.m[11] = 0.0;
  6567. result.m[12] = temp * plane.d;
  6568. result.m[13] = temp2 * plane.d;
  6569. result.m[14] = temp3 * plane.d;
  6570. result.m[15] = 1.0;
  6571. result._markAsUpdated();
  6572. };
  6573. /**
  6574. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6575. * @param xaxis defines the value of the 1st axis
  6576. * @param yaxis defines the value of the 2nd axis
  6577. * @param zaxis defines the value of the 3rd axis
  6578. * @param result defines the target matrix
  6579. */
  6580. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6581. result.m[0] = xaxis.x;
  6582. result.m[1] = xaxis.y;
  6583. result.m[2] = xaxis.z;
  6584. result.m[3] = 0.0;
  6585. result.m[4] = yaxis.x;
  6586. result.m[5] = yaxis.y;
  6587. result.m[6] = yaxis.z;
  6588. result.m[7] = 0.0;
  6589. result.m[8] = zaxis.x;
  6590. result.m[9] = zaxis.y;
  6591. result.m[10] = zaxis.z;
  6592. result.m[11] = 0.0;
  6593. result.m[12] = 0.0;
  6594. result.m[13] = 0.0;
  6595. result.m[14] = 0.0;
  6596. result.m[15] = 1.0;
  6597. result._markAsUpdated();
  6598. };
  6599. /**
  6600. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6601. * @param quat defines the quaternion to use
  6602. * @param result defines the target matrix
  6603. */
  6604. Matrix.FromQuaternionToRef = function (quat, result) {
  6605. var xx = quat.x * quat.x;
  6606. var yy = quat.y * quat.y;
  6607. var zz = quat.z * quat.z;
  6608. var xy = quat.x * quat.y;
  6609. var zw = quat.z * quat.w;
  6610. var zx = quat.z * quat.x;
  6611. var yw = quat.y * quat.w;
  6612. var yz = quat.y * quat.z;
  6613. var xw = quat.x * quat.w;
  6614. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6615. result.m[1] = 2.0 * (xy + zw);
  6616. result.m[2] = 2.0 * (zx - yw);
  6617. result.m[3] = 0.0;
  6618. result.m[4] = 2.0 * (xy - zw);
  6619. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6620. result.m[6] = 2.0 * (yz + xw);
  6621. result.m[7] = 0.0;
  6622. result.m[8] = 2.0 * (zx + yw);
  6623. result.m[9] = 2.0 * (yz - xw);
  6624. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6625. result.m[11] = 0.0;
  6626. result.m[12] = 0.0;
  6627. result.m[13] = 0.0;
  6628. result.m[14] = 0.0;
  6629. result.m[15] = 1.0;
  6630. result._markAsUpdated();
  6631. };
  6632. Matrix._tempQuaternion = new Quaternion();
  6633. Matrix._xAxis = Vector3.Zero();
  6634. Matrix._yAxis = Vector3.Zero();
  6635. Matrix._zAxis = Vector3.Zero();
  6636. Matrix._updateFlagSeed = 0;
  6637. Matrix._identityReadOnly = Matrix.Identity();
  6638. return Matrix;
  6639. }());
  6640. BABYLON.Matrix = Matrix;
  6641. var Plane = /** @class */ (function () {
  6642. /**
  6643. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6644. */
  6645. function Plane(a, b, c, d) {
  6646. this.normal = new Vector3(a, b, c);
  6647. this.d = d;
  6648. }
  6649. /**
  6650. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6651. */
  6652. Plane.prototype.asArray = function () {
  6653. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6654. };
  6655. // Methods
  6656. /**
  6657. * Returns a new plane copied from the current Plane.
  6658. */
  6659. Plane.prototype.clone = function () {
  6660. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6661. };
  6662. /**
  6663. * Returns the string "Plane".
  6664. */
  6665. Plane.prototype.getClassName = function () {
  6666. return "Plane";
  6667. };
  6668. /**
  6669. * Returns the Plane hash code.
  6670. */
  6671. Plane.prototype.getHashCode = function () {
  6672. var hash = this.normal.getHashCode();
  6673. hash = (hash * 397) ^ (this.d || 0);
  6674. return hash;
  6675. };
  6676. /**
  6677. * Normalize the current Plane in place.
  6678. * Returns the updated Plane.
  6679. */
  6680. Plane.prototype.normalize = function () {
  6681. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6682. var magnitude = 0.0;
  6683. if (norm !== 0) {
  6684. magnitude = 1.0 / norm;
  6685. }
  6686. this.normal.x *= magnitude;
  6687. this.normal.y *= magnitude;
  6688. this.normal.z *= magnitude;
  6689. this.d *= magnitude;
  6690. return this;
  6691. };
  6692. /**
  6693. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6694. */
  6695. Plane.prototype.transform = function (transformation) {
  6696. var transposedMatrix = Matrix.Transpose(transformation);
  6697. var x = this.normal.x;
  6698. var y = this.normal.y;
  6699. var z = this.normal.z;
  6700. var d = this.d;
  6701. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6702. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6703. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6704. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6705. return new Plane(normalX, normalY, normalZ, finalD);
  6706. };
  6707. /**
  6708. * Returns the dot product (float) of the point coordinates and the plane normal.
  6709. */
  6710. Plane.prototype.dotCoordinate = function (point) {
  6711. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6712. };
  6713. /**
  6714. * Updates the current Plane from the plane defined by the three given points.
  6715. * Returns the updated Plane.
  6716. */
  6717. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6718. var x1 = point2.x - point1.x;
  6719. var y1 = point2.y - point1.y;
  6720. var z1 = point2.z - point1.z;
  6721. var x2 = point3.x - point1.x;
  6722. var y2 = point3.y - point1.y;
  6723. var z2 = point3.z - point1.z;
  6724. var yz = (y1 * z2) - (z1 * y2);
  6725. var xz = (z1 * x2) - (x1 * z2);
  6726. var xy = (x1 * y2) - (y1 * x2);
  6727. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6728. var invPyth;
  6729. if (pyth !== 0) {
  6730. invPyth = 1.0 / pyth;
  6731. }
  6732. else {
  6733. invPyth = 0.0;
  6734. }
  6735. this.normal.x = yz * invPyth;
  6736. this.normal.y = xz * invPyth;
  6737. this.normal.z = xy * invPyth;
  6738. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6739. return this;
  6740. };
  6741. /**
  6742. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6743. */
  6744. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6745. var dot = Vector3.Dot(this.normal, direction);
  6746. return (dot <= epsilon);
  6747. };
  6748. /**
  6749. * Returns the signed distance (float) from the given point to the Plane.
  6750. */
  6751. Plane.prototype.signedDistanceTo = function (point) {
  6752. return Vector3.Dot(point, this.normal) + this.d;
  6753. };
  6754. // Statics
  6755. /**
  6756. * Returns a new Plane from the given array.
  6757. */
  6758. Plane.FromArray = function (array) {
  6759. return new Plane(array[0], array[1], array[2], array[3]);
  6760. };
  6761. /**
  6762. * Returns a new Plane defined by the three given points.
  6763. */
  6764. Plane.FromPoints = function (point1, point2, point3) {
  6765. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6766. result.copyFromPoints(point1, point2, point3);
  6767. return result;
  6768. };
  6769. /**
  6770. * Returns a new Plane the normal vector to this plane at the given origin point.
  6771. * Note : the vector "normal" is updated because normalized.
  6772. */
  6773. Plane.FromPositionAndNormal = function (origin, normal) {
  6774. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6775. normal.normalize();
  6776. result.normal = normal;
  6777. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6778. return result;
  6779. };
  6780. /**
  6781. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6782. */
  6783. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6784. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6785. return Vector3.Dot(point, normal) + d;
  6786. };
  6787. return Plane;
  6788. }());
  6789. BABYLON.Plane = Plane;
  6790. var Viewport = /** @class */ (function () {
  6791. /**
  6792. * Creates a Viewport object located at (x, y) and sized (width, height).
  6793. */
  6794. function Viewport(x, y, width, height) {
  6795. this.x = x;
  6796. this.y = y;
  6797. this.width = width;
  6798. this.height = height;
  6799. }
  6800. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6801. if (renderWidthOrEngine.getRenderWidth) {
  6802. var engine = renderWidthOrEngine;
  6803. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6804. }
  6805. var renderWidth = renderWidthOrEngine;
  6806. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6807. };
  6808. /**
  6809. * Returns a new Viewport copied from the current one.
  6810. */
  6811. Viewport.prototype.clone = function () {
  6812. return new Viewport(this.x, this.y, this.width, this.height);
  6813. };
  6814. return Viewport;
  6815. }());
  6816. BABYLON.Viewport = Viewport;
  6817. var Frustum = /** @class */ (function () {
  6818. function Frustum() {
  6819. }
  6820. /**
  6821. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6822. */
  6823. Frustum.GetPlanes = function (transform) {
  6824. var frustumPlanes = [];
  6825. for (var index = 0; index < 6; index++) {
  6826. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6827. }
  6828. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6829. return frustumPlanes;
  6830. };
  6831. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6832. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6833. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6834. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6835. frustumPlane.d = transform.m[15] + transform.m[14];
  6836. frustumPlane.normalize();
  6837. };
  6838. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6839. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6840. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6841. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6842. frustumPlane.d = transform.m[15] - transform.m[14];
  6843. frustumPlane.normalize();
  6844. };
  6845. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6846. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6847. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6848. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6849. frustumPlane.d = transform.m[15] + transform.m[12];
  6850. frustumPlane.normalize();
  6851. };
  6852. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6854. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6855. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6856. frustumPlane.d = transform.m[15] - transform.m[12];
  6857. frustumPlane.normalize();
  6858. };
  6859. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6860. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6861. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6862. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6863. frustumPlane.d = transform.m[15] - transform.m[13];
  6864. frustumPlane.normalize();
  6865. };
  6866. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6867. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6868. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6869. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6870. frustumPlane.d = transform.m[15] + transform.m[13];
  6871. frustumPlane.normalize();
  6872. };
  6873. /**
  6874. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6875. */
  6876. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6877. // Near
  6878. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6879. // Far
  6880. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6881. // Left
  6882. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6883. // Right
  6884. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6885. // Top
  6886. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6887. // Bottom
  6888. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6889. };
  6890. return Frustum;
  6891. }());
  6892. BABYLON.Frustum = Frustum;
  6893. /** Defines supported spaces */
  6894. var Space;
  6895. (function (Space) {
  6896. /** Local (object) space */
  6897. Space[Space["LOCAL"] = 0] = "LOCAL";
  6898. /** World space */
  6899. Space[Space["WORLD"] = 1] = "WORLD";
  6900. /** Bone space */
  6901. Space[Space["BONE"] = 2] = "BONE";
  6902. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6903. /** Defines the 3 main axes */
  6904. var Axis = /** @class */ (function () {
  6905. function Axis() {
  6906. }
  6907. /** X axis */
  6908. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6909. /** Y axis */
  6910. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6911. /** Z axis */
  6912. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6913. return Axis;
  6914. }());
  6915. BABYLON.Axis = Axis;
  6916. ;
  6917. var BezierCurve = /** @class */ (function () {
  6918. function BezierCurve() {
  6919. }
  6920. /**
  6921. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6922. */
  6923. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6924. // Extract X (which is equal to time here)
  6925. var f0 = 1 - 3 * x2 + 3 * x1;
  6926. var f1 = 3 * x2 - 6 * x1;
  6927. var f2 = 3 * x1;
  6928. var refinedT = t;
  6929. for (var i = 0; i < 5; i++) {
  6930. var refinedT2 = refinedT * refinedT;
  6931. var refinedT3 = refinedT2 * refinedT;
  6932. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6933. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6934. refinedT -= (x - t) * slope;
  6935. refinedT = Math.min(1, Math.max(0, refinedT));
  6936. }
  6937. // Resolve cubic bezier for the given x
  6938. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6939. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6940. Math.pow(refinedT, 3);
  6941. };
  6942. return BezierCurve;
  6943. }());
  6944. BABYLON.BezierCurve = BezierCurve;
  6945. /**
  6946. * Defines potential orientation for back face culling
  6947. */
  6948. var Orientation;
  6949. (function (Orientation) {
  6950. /**
  6951. * Clockwise
  6952. */
  6953. Orientation[Orientation["CW"] = 0] = "CW";
  6954. /** Counter clockwise */
  6955. Orientation[Orientation["CCW"] = 1] = "CCW";
  6956. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6957. /**
  6958. * Defines angle representation
  6959. */
  6960. var Angle = /** @class */ (function () {
  6961. /**
  6962. * Creates an Angle object of "radians" radians (float).
  6963. */
  6964. function Angle(radians) {
  6965. this._radians = radians;
  6966. if (this._radians < 0.0)
  6967. this._radians += (2.0 * Math.PI);
  6968. }
  6969. /**
  6970. * Get value in degrees
  6971. * @returns the Angle value in degrees (float)
  6972. */
  6973. Angle.prototype.degrees = function () {
  6974. return this._radians * 180.0 / Math.PI;
  6975. };
  6976. /**
  6977. * Get value in radians
  6978. * @returns the Angle value in radians (float)
  6979. */
  6980. Angle.prototype.radians = function () {
  6981. return this._radians;
  6982. };
  6983. /**
  6984. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6985. * @param a defines first vector
  6986. * @param b defines second vector
  6987. * @returns a new Angle
  6988. */
  6989. Angle.BetweenTwoPoints = function (a, b) {
  6990. var delta = b.subtract(a);
  6991. var theta = Math.atan2(delta.y, delta.x);
  6992. return new Angle(theta);
  6993. };
  6994. /**
  6995. * Gets a new Angle object from the given float in radians
  6996. * @param radians defines the angle value in radians
  6997. * @returns a new Angle
  6998. */
  6999. Angle.FromRadians = function (radians) {
  7000. return new Angle(radians);
  7001. };
  7002. /**
  7003. * Gets a new Angle object from the given float in degrees
  7004. * @param degrees defines the angle value in degrees
  7005. * @returns a new Angle
  7006. */
  7007. Angle.FromDegrees = function (degrees) {
  7008. return new Angle(degrees * Math.PI / 180.0);
  7009. };
  7010. return Angle;
  7011. }());
  7012. BABYLON.Angle = Angle;
  7013. var Arc2 = /** @class */ (function () {
  7014. /**
  7015. * Creates an Arc object from the three given points : start, middle and end.
  7016. */
  7017. function Arc2(startPoint, midPoint, endPoint) {
  7018. this.startPoint = startPoint;
  7019. this.midPoint = midPoint;
  7020. this.endPoint = endPoint;
  7021. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7022. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7023. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7024. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7025. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  7026. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7027. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7028. var a1 = this.startAngle.degrees();
  7029. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7030. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7031. // angles correction
  7032. if (a2 - a1 > +180.0)
  7033. a2 -= 360.0;
  7034. if (a2 - a1 < -180.0)
  7035. a2 += 360.0;
  7036. if (a3 - a2 > +180.0)
  7037. a3 -= 360.0;
  7038. if (a3 - a2 < -180.0)
  7039. a3 += 360.0;
  7040. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7041. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7042. }
  7043. return Arc2;
  7044. }());
  7045. BABYLON.Arc2 = Arc2;
  7046. var Path2 = /** @class */ (function () {
  7047. /**
  7048. * Creates a Path2 object from the starting 2D coordinates x and y.
  7049. */
  7050. function Path2(x, y) {
  7051. this._points = new Array();
  7052. this._length = 0.0;
  7053. this.closed = false;
  7054. this._points.push(new Vector2(x, y));
  7055. }
  7056. /**
  7057. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7058. * Returns the updated Path2.
  7059. */
  7060. Path2.prototype.addLineTo = function (x, y) {
  7061. if (this.closed) {
  7062. return this;
  7063. }
  7064. var newPoint = new Vector2(x, y);
  7065. var previousPoint = this._points[this._points.length - 1];
  7066. this._points.push(newPoint);
  7067. this._length += newPoint.subtract(previousPoint).length();
  7068. return this;
  7069. };
  7070. /**
  7071. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  7072. * Returns the updated Path2.
  7073. */
  7074. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7075. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7076. if (this.closed) {
  7077. return this;
  7078. }
  7079. var startPoint = this._points[this._points.length - 1];
  7080. var midPoint = new Vector2(midX, midY);
  7081. var endPoint = new Vector2(endX, endY);
  7082. var arc = new Arc2(startPoint, midPoint, endPoint);
  7083. var increment = arc.angle.radians() / numberOfSegments;
  7084. if (arc.orientation === Orientation.CW)
  7085. increment *= -1;
  7086. var currentAngle = arc.startAngle.radians() + increment;
  7087. for (var i = 0; i < numberOfSegments; i++) {
  7088. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7089. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7090. this.addLineTo(x, y);
  7091. currentAngle += increment;
  7092. }
  7093. return this;
  7094. };
  7095. /**
  7096. * Closes the Path2.
  7097. * Returns the Path2.
  7098. */
  7099. Path2.prototype.close = function () {
  7100. this.closed = true;
  7101. return this;
  7102. };
  7103. /**
  7104. * Returns the Path2 total length (float).
  7105. */
  7106. Path2.prototype.length = function () {
  7107. var result = this._length;
  7108. if (!this.closed) {
  7109. var lastPoint = this._points[this._points.length - 1];
  7110. var firstPoint = this._points[0];
  7111. result += (firstPoint.subtract(lastPoint).length());
  7112. }
  7113. return result;
  7114. };
  7115. /**
  7116. * Returns the Path2 internal array of points.
  7117. */
  7118. Path2.prototype.getPoints = function () {
  7119. return this._points;
  7120. };
  7121. /**
  7122. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7123. */
  7124. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7125. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7126. return Vector2.Zero();
  7127. }
  7128. var lengthPosition = normalizedLengthPosition * this.length();
  7129. var previousOffset = 0;
  7130. for (var i = 0; i < this._points.length; i++) {
  7131. var j = (i + 1) % this._points.length;
  7132. var a = this._points[i];
  7133. var b = this._points[j];
  7134. var bToA = b.subtract(a);
  7135. var nextOffset = (bToA.length() + previousOffset);
  7136. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7137. var dir = bToA.normalize();
  7138. var localOffset = lengthPosition - previousOffset;
  7139. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7140. }
  7141. previousOffset = nextOffset;
  7142. }
  7143. return Vector2.Zero();
  7144. };
  7145. /**
  7146. * Returns a new Path2 starting at the coordinates (x, y).
  7147. */
  7148. Path2.StartingAt = function (x, y) {
  7149. return new Path2(x, y);
  7150. };
  7151. return Path2;
  7152. }());
  7153. BABYLON.Path2 = Path2;
  7154. var Path3D = /** @class */ (function () {
  7155. /**
  7156. * new Path3D(path, normal, raw)
  7157. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7158. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7159. * path : an array of Vector3, the curve axis of the Path3D
  7160. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7161. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7162. */
  7163. function Path3D(path, firstNormal, raw) {
  7164. if (firstNormal === void 0) { firstNormal = null; }
  7165. this.path = path;
  7166. this._curve = new Array();
  7167. this._distances = new Array();
  7168. this._tangents = new Array();
  7169. this._normals = new Array();
  7170. this._binormals = new Array();
  7171. for (var p = 0; p < path.length; p++) {
  7172. this._curve[p] = path[p].clone(); // hard copy
  7173. }
  7174. this._raw = raw || false;
  7175. this._compute(firstNormal);
  7176. }
  7177. /**
  7178. * Returns the Path3D array of successive Vector3 designing its curve.
  7179. */
  7180. Path3D.prototype.getCurve = function () {
  7181. return this._curve;
  7182. };
  7183. /**
  7184. * Returns an array populated with tangent vectors on each Path3D curve point.
  7185. */
  7186. Path3D.prototype.getTangents = function () {
  7187. return this._tangents;
  7188. };
  7189. /**
  7190. * Returns an array populated with normal vectors on each Path3D curve point.
  7191. */
  7192. Path3D.prototype.getNormals = function () {
  7193. return this._normals;
  7194. };
  7195. /**
  7196. * Returns an array populated with binormal vectors on each Path3D curve point.
  7197. */
  7198. Path3D.prototype.getBinormals = function () {
  7199. return this._binormals;
  7200. };
  7201. /**
  7202. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7203. */
  7204. Path3D.prototype.getDistances = function () {
  7205. return this._distances;
  7206. };
  7207. /**
  7208. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7209. * Returns the same object updated.
  7210. */
  7211. Path3D.prototype.update = function (path, firstNormal) {
  7212. if (firstNormal === void 0) { firstNormal = null; }
  7213. for (var p = 0; p < path.length; p++) {
  7214. this._curve[p].x = path[p].x;
  7215. this._curve[p].y = path[p].y;
  7216. this._curve[p].z = path[p].z;
  7217. }
  7218. this._compute(firstNormal);
  7219. return this;
  7220. };
  7221. // private function compute() : computes tangents, normals and binormals
  7222. Path3D.prototype._compute = function (firstNormal) {
  7223. var l = this._curve.length;
  7224. // first and last tangents
  7225. this._tangents[0] = this._getFirstNonNullVector(0);
  7226. if (!this._raw) {
  7227. this._tangents[0].normalize();
  7228. }
  7229. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7230. if (!this._raw) {
  7231. this._tangents[l - 1].normalize();
  7232. }
  7233. // normals and binormals at first point : arbitrary vector with _normalVector()
  7234. var tg0 = this._tangents[0];
  7235. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7236. this._normals[0] = pp0;
  7237. if (!this._raw) {
  7238. this._normals[0].normalize();
  7239. }
  7240. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7241. if (!this._raw) {
  7242. this._binormals[0].normalize();
  7243. }
  7244. this._distances[0] = 0.0;
  7245. // normals and binormals : next points
  7246. var prev; // previous vector (segment)
  7247. var cur; // current vector (segment)
  7248. var curTang; // current tangent
  7249. // previous normal
  7250. var prevBinor; // previous binormal
  7251. for (var i = 1; i < l; i++) {
  7252. // tangents
  7253. prev = this._getLastNonNullVector(i);
  7254. if (i < l - 1) {
  7255. cur = this._getFirstNonNullVector(i);
  7256. this._tangents[i] = prev.add(cur);
  7257. this._tangents[i].normalize();
  7258. }
  7259. this._distances[i] = this._distances[i - 1] + prev.length();
  7260. // normals and binormals
  7261. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7262. curTang = this._tangents[i];
  7263. prevBinor = this._binormals[i - 1];
  7264. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7265. if (!this._raw) {
  7266. this._normals[i].normalize();
  7267. }
  7268. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7269. if (!this._raw) {
  7270. this._binormals[i].normalize();
  7271. }
  7272. }
  7273. };
  7274. // private function getFirstNonNullVector(index)
  7275. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7276. Path3D.prototype._getFirstNonNullVector = function (index) {
  7277. var i = 1;
  7278. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7279. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7280. i++;
  7281. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7282. }
  7283. return nNVector;
  7284. };
  7285. // private function getLastNonNullVector(index)
  7286. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7287. Path3D.prototype._getLastNonNullVector = function (index) {
  7288. var i = 1;
  7289. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7290. while (nLVector.length() === 0 && index > i + 1) {
  7291. i++;
  7292. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7293. }
  7294. return nLVector;
  7295. };
  7296. // private function normalVector(v0, vt, va) :
  7297. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7298. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7299. Path3D.prototype._normalVector = function (v0, vt, va) {
  7300. var normal0;
  7301. var tgl = vt.length();
  7302. if (tgl === 0.0) {
  7303. tgl = 1.0;
  7304. }
  7305. if (va === undefined || va === null) {
  7306. var point;
  7307. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7308. point = new Vector3(0.0, -1.0, 0.0);
  7309. }
  7310. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7311. point = new Vector3(1.0, 0.0, 0.0);
  7312. }
  7313. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7314. point = new Vector3(0.0, 0.0, 1.0);
  7315. }
  7316. else {
  7317. point = Vector3.Zero();
  7318. }
  7319. normal0 = Vector3.Cross(vt, point);
  7320. }
  7321. else {
  7322. normal0 = Vector3.Cross(vt, va);
  7323. Vector3.CrossToRef(normal0, vt, normal0);
  7324. }
  7325. normal0.normalize();
  7326. return normal0;
  7327. };
  7328. return Path3D;
  7329. }());
  7330. BABYLON.Path3D = Path3D;
  7331. var Curve3 = /** @class */ (function () {
  7332. /**
  7333. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7334. * A Curve3 is designed from a series of successive Vector3.
  7335. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7336. */
  7337. function Curve3(points) {
  7338. this._length = 0.0;
  7339. this._points = points;
  7340. this._length = this._computeLength(points);
  7341. }
  7342. /**
  7343. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7344. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7345. * @param v1 (Vector3) the control point
  7346. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7347. * @param nbPoints (integer) the wanted number of points in the curve
  7348. */
  7349. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7350. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7351. var bez = new Array();
  7352. var equation = function (t, val0, val1, val2) {
  7353. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7354. return res;
  7355. };
  7356. for (var i = 0; i <= nbPoints; i++) {
  7357. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7358. }
  7359. return new Curve3(bez);
  7360. };
  7361. /**
  7362. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7363. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7364. * @param v1 (Vector3) the first control point
  7365. * @param v2 (Vector3) the second control point
  7366. * @param v3 (Vector3) the end point of the Cubic Bezier
  7367. * @param nbPoints (integer) the wanted number of points in the curve
  7368. */
  7369. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7370. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7371. var bez = new Array();
  7372. var equation = function (t, val0, val1, val2, val3) {
  7373. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7374. return res;
  7375. };
  7376. for (var i = 0; i <= nbPoints; i++) {
  7377. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7378. }
  7379. return new Curve3(bez);
  7380. };
  7381. /**
  7382. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7383. * @param p1 (Vector3) the origin point of the Hermite Spline
  7384. * @param t1 (Vector3) the tangent vector at the origin point
  7385. * @param p2 (Vector3) the end point of the Hermite Spline
  7386. * @param t2 (Vector3) the tangent vector at the end point
  7387. * @param nbPoints (integer) the wanted number of points in the curve
  7388. */
  7389. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7390. var hermite = new Array();
  7391. var step = 1.0 / nbPoints;
  7392. for (var i = 0; i <= nbPoints; i++) {
  7393. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7394. }
  7395. return new Curve3(hermite);
  7396. };
  7397. /**
  7398. * Returns a Curve3 object along a CatmullRom Spline curve :
  7399. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7400. * @param nbPoints (integer) the wanted number of points between each curve control points
  7401. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7402. */
  7403. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7404. var catmullRom = new Array();
  7405. var step = 1.0 / nbPoints;
  7406. var amount = 0.0;
  7407. if (closed) {
  7408. var pointsCount = points.length;
  7409. for (var i = 0; i < pointsCount; i++) {
  7410. amount = 0;
  7411. for (var c = 0; c < nbPoints; c++) {
  7412. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7413. amount += step;
  7414. }
  7415. }
  7416. catmullRom.push(catmullRom[0]);
  7417. }
  7418. else {
  7419. var totalPoints = new Array();
  7420. totalPoints.push(points[0].clone());
  7421. Array.prototype.push.apply(totalPoints, points);
  7422. totalPoints.push(points[points.length - 1].clone());
  7423. for (var i = 0; i < totalPoints.length - 3; i++) {
  7424. amount = 0;
  7425. for (var c = 0; c < nbPoints; c++) {
  7426. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7427. amount += step;
  7428. }
  7429. }
  7430. i--;
  7431. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7432. }
  7433. return new Curve3(catmullRom);
  7434. };
  7435. /**
  7436. * Returns the Curve3 stored array of successive Vector3
  7437. */
  7438. Curve3.prototype.getPoints = function () {
  7439. return this._points;
  7440. };
  7441. /**
  7442. * Returns the computed length (float) of the curve.
  7443. */
  7444. Curve3.prototype.length = function () {
  7445. return this._length;
  7446. };
  7447. /**
  7448. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7449. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7450. * curveA and curveB keep unchanged.
  7451. */
  7452. Curve3.prototype.continue = function (curve) {
  7453. var lastPoint = this._points[this._points.length - 1];
  7454. var continuedPoints = this._points.slice();
  7455. var curvePoints = curve.getPoints();
  7456. for (var i = 1; i < curvePoints.length; i++) {
  7457. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7458. }
  7459. var continuedCurve = new Curve3(continuedPoints);
  7460. return continuedCurve;
  7461. };
  7462. Curve3.prototype._computeLength = function (path) {
  7463. var l = 0;
  7464. for (var i = 1; i < path.length; i++) {
  7465. l += (path[i].subtract(path[i - 1])).length();
  7466. }
  7467. return l;
  7468. };
  7469. return Curve3;
  7470. }());
  7471. BABYLON.Curve3 = Curve3;
  7472. // Vertex formats
  7473. var PositionNormalVertex = /** @class */ (function () {
  7474. function PositionNormalVertex(position, normal) {
  7475. if (position === void 0) { position = Vector3.Zero(); }
  7476. if (normal === void 0) { normal = Vector3.Up(); }
  7477. this.position = position;
  7478. this.normal = normal;
  7479. }
  7480. PositionNormalVertex.prototype.clone = function () {
  7481. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7482. };
  7483. return PositionNormalVertex;
  7484. }());
  7485. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7486. var PositionNormalTextureVertex = /** @class */ (function () {
  7487. function PositionNormalTextureVertex(position, normal, uv) {
  7488. if (position === void 0) { position = Vector3.Zero(); }
  7489. if (normal === void 0) { normal = Vector3.Up(); }
  7490. if (uv === void 0) { uv = Vector2.Zero(); }
  7491. this.position = position;
  7492. this.normal = normal;
  7493. this.uv = uv;
  7494. }
  7495. PositionNormalTextureVertex.prototype.clone = function () {
  7496. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7497. };
  7498. return PositionNormalTextureVertex;
  7499. }());
  7500. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7501. // Temporary pre-allocated objects for engine internal use
  7502. // usage in any internal function :
  7503. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7504. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7505. var Tmp = /** @class */ (function () {
  7506. function Tmp() {
  7507. }
  7508. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7509. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7510. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7511. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7512. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7513. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7514. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7515. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7516. Matrix.Zero(), Matrix.Zero(),
  7517. Matrix.Zero(), Matrix.Zero(),
  7518. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7519. return Tmp;
  7520. }());
  7521. BABYLON.Tmp = Tmp;
  7522. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7523. var MathTmp = /** @class */ (function () {
  7524. function MathTmp() {
  7525. }
  7526. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7527. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7528. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7529. return MathTmp;
  7530. }());
  7531. })(BABYLON || (BABYLON = {}));
  7532. //# sourceMappingURL=babylon.math.js.map
  7533. var BABYLON;
  7534. (function (BABYLON) {
  7535. var Scalar = /** @class */ (function () {
  7536. function Scalar() {
  7537. }
  7538. /**
  7539. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7540. */
  7541. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7542. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7543. var num = a - b;
  7544. return -epsilon <= num && num <= epsilon;
  7545. };
  7546. /**
  7547. * Returns a string : the upper case translation of the number i to hexadecimal.
  7548. */
  7549. Scalar.ToHex = function (i) {
  7550. var str = i.toString(16);
  7551. if (i <= 15) {
  7552. return ("0" + str).toUpperCase();
  7553. }
  7554. return str.toUpperCase();
  7555. };
  7556. /**
  7557. * Returns -1 if value is negative and +1 is value is positive.
  7558. * Returns the value itself if it's equal to zero.
  7559. */
  7560. Scalar.Sign = function (value) {
  7561. value = +value; // convert to a number
  7562. if (value === 0 || isNaN(value))
  7563. return value;
  7564. return value > 0 ? 1 : -1;
  7565. };
  7566. /**
  7567. * Returns the value itself if it's between min and max.
  7568. * Returns min if the value is lower than min.
  7569. * Returns max if the value is greater than max.
  7570. */
  7571. Scalar.Clamp = function (value, min, max) {
  7572. if (min === void 0) { min = 0; }
  7573. if (max === void 0) { max = 1; }
  7574. return Math.min(max, Math.max(min, value));
  7575. };
  7576. /**
  7577. * Returns the log2 of value.
  7578. */
  7579. Scalar.Log2 = function (value) {
  7580. return Math.log(value) * Math.LOG2E;
  7581. };
  7582. /**
  7583. * Loops the value, so that it is never larger than length and never smaller than 0.
  7584. *
  7585. * This is similar to the modulo operator but it works with floating point numbers.
  7586. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7587. * With t = 5 and length = 2.5, the result would be 0.0.
  7588. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7589. */
  7590. Scalar.Repeat = function (value, length) {
  7591. return value - Math.floor(value / length) * length;
  7592. };
  7593. /**
  7594. * Normalize the value between 0.0 and 1.0 using min and max values
  7595. */
  7596. Scalar.Normalize = function (value, min, max) {
  7597. return (value - min) / (max - min);
  7598. };
  7599. /**
  7600. * Denormalize the value from 0.0 and 1.0 using min and max values
  7601. */
  7602. Scalar.Denormalize = function (normalized, min, max) {
  7603. return (normalized * (max - min) + min);
  7604. };
  7605. /**
  7606. * Calculates the shortest difference between two given angles given in degrees.
  7607. */
  7608. Scalar.DeltaAngle = function (current, target) {
  7609. var num = Scalar.Repeat(target - current, 360.0);
  7610. if (num > 180.0) {
  7611. num -= 360.0;
  7612. }
  7613. return num;
  7614. };
  7615. /**
  7616. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7617. *
  7618. * The returned value will move back and forth between 0 and length
  7619. */
  7620. Scalar.PingPong = function (tx, length) {
  7621. var t = Scalar.Repeat(tx, length * 2.0);
  7622. return length - Math.abs(t - length);
  7623. };
  7624. /**
  7625. * Interpolates between min and max with smoothing at the limits.
  7626. *
  7627. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7628. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7629. */
  7630. Scalar.SmoothStep = function (from, to, tx) {
  7631. var t = Scalar.Clamp(tx);
  7632. t = -2.0 * t * t * t + 3.0 * t * t;
  7633. return to * t + from * (1.0 - t);
  7634. };
  7635. /**
  7636. * Moves a value current towards target.
  7637. *
  7638. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7639. * Negative values of maxDelta pushes the value away from target.
  7640. */
  7641. Scalar.MoveTowards = function (current, target, maxDelta) {
  7642. var result = 0;
  7643. if (Math.abs(target - current) <= maxDelta) {
  7644. result = target;
  7645. }
  7646. else {
  7647. result = current + Scalar.Sign(target - current) * maxDelta;
  7648. }
  7649. return result;
  7650. };
  7651. /**
  7652. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7653. *
  7654. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7655. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7656. */
  7657. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7658. var num = Scalar.DeltaAngle(current, target);
  7659. var result = 0;
  7660. if (-maxDelta < num && num < maxDelta) {
  7661. result = target;
  7662. }
  7663. else {
  7664. target = current + num;
  7665. result = Scalar.MoveTowards(current, target, maxDelta);
  7666. }
  7667. return result;
  7668. };
  7669. /**
  7670. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7671. */
  7672. Scalar.Lerp = function (start, end, amount) {
  7673. return start + ((end - start) * amount);
  7674. };
  7675. /**
  7676. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7677. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7678. */
  7679. Scalar.LerpAngle = function (start, end, amount) {
  7680. var num = Scalar.Repeat(end - start, 360.0);
  7681. if (num > 180.0) {
  7682. num -= 360.0;
  7683. }
  7684. return start + num * Scalar.Clamp(amount);
  7685. };
  7686. /**
  7687. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7688. */
  7689. Scalar.InverseLerp = function (a, b, value) {
  7690. var result = 0;
  7691. if (a != b) {
  7692. result = Scalar.Clamp((value - a) / (b - a));
  7693. }
  7694. else {
  7695. result = 0.0;
  7696. }
  7697. return result;
  7698. };
  7699. /**
  7700. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7701. */
  7702. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7703. var squared = amount * amount;
  7704. var cubed = amount * squared;
  7705. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7706. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7707. var part3 = (cubed - (2.0 * squared)) + amount;
  7708. var part4 = cubed - squared;
  7709. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7710. };
  7711. /**
  7712. * Returns a random float number between and min and max values
  7713. */
  7714. Scalar.RandomRange = function (min, max) {
  7715. if (min === max)
  7716. return min;
  7717. return ((Math.random() * (max - min)) + min);
  7718. };
  7719. /**
  7720. * This function returns percentage of a number in a given range.
  7721. *
  7722. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7723. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7724. */
  7725. Scalar.RangeToPercent = function (number, min, max) {
  7726. return ((number - min) / (max - min));
  7727. };
  7728. /**
  7729. * This function returns number that corresponds to the percentage in a given range.
  7730. *
  7731. * PercentToRange(0.34,0,100) will return 34.
  7732. */
  7733. Scalar.PercentToRange = function (percent, min, max) {
  7734. return ((max - min) * percent + min);
  7735. };
  7736. /**
  7737. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7738. * @param angle The angle to normalize in radian.
  7739. * @return The converted angle.
  7740. */
  7741. Scalar.NormalizeRadians = function (angle) {
  7742. // More precise but slower version kept for reference.
  7743. // angle = angle % Tools.TwoPi;
  7744. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7745. //if (angle > Math.PI) {
  7746. // angle -= Tools.TwoPi;
  7747. //}
  7748. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7749. return angle;
  7750. };
  7751. /**
  7752. * Two pi constants convenient for computation.
  7753. */
  7754. Scalar.TwoPi = Math.PI * 2;
  7755. return Scalar;
  7756. }());
  7757. BABYLON.Scalar = Scalar;
  7758. })(BABYLON || (BABYLON = {}));
  7759. //# sourceMappingURL=babylon.math.scalar.js.map
  7760. //# sourceMappingURL=babylon.mixins.js.map
  7761. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7762. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7763. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7764. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7765. //# sourceMappingURL=babylon.webgl2.js.map
  7766. var BABYLON;
  7767. (function (BABYLON) {
  7768. var __decoratorInitialStore = {};
  7769. var __mergedStore = {};
  7770. var _copySource = function (creationFunction, source, instanciate) {
  7771. var destination = creationFunction();
  7772. // Tags
  7773. if (BABYLON.Tags) {
  7774. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7775. }
  7776. var classStore = getMergedStore(destination);
  7777. // Properties
  7778. for (var property in classStore) {
  7779. var propertyDescriptor = classStore[property];
  7780. var sourceProperty = source[property];
  7781. var propertyType = propertyDescriptor.type;
  7782. if (sourceProperty !== undefined && sourceProperty !== null) {
  7783. switch (propertyType) {
  7784. case 0: // Value
  7785. case 6: // Mesh reference
  7786. case 11: // Camera reference
  7787. destination[property] = sourceProperty;
  7788. break;
  7789. case 1: // Texture
  7790. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7791. break;
  7792. case 2: // Color3
  7793. case 3: // FresnelParameters
  7794. case 4: // Vector2
  7795. case 5: // Vector3
  7796. case 7: // Color Curves
  7797. case 10: // Quaternion
  7798. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7799. break;
  7800. }
  7801. }
  7802. }
  7803. return destination;
  7804. };
  7805. function getDirectStore(target) {
  7806. var classKey = target.getClassName();
  7807. if (!__decoratorInitialStore[classKey]) {
  7808. __decoratorInitialStore[classKey] = {};
  7809. }
  7810. return __decoratorInitialStore[classKey];
  7811. }
  7812. /**
  7813. * Return the list of properties flagged as serializable
  7814. * @param target: host object
  7815. */
  7816. function getMergedStore(target) {
  7817. var classKey = target.getClassName();
  7818. if (__mergedStore[classKey]) {
  7819. return __mergedStore[classKey];
  7820. }
  7821. __mergedStore[classKey] = {};
  7822. var store = __mergedStore[classKey];
  7823. var currentTarget = target;
  7824. var currentKey = classKey;
  7825. while (currentKey) {
  7826. var initialStore = __decoratorInitialStore[currentKey];
  7827. for (var property in initialStore) {
  7828. store[property] = initialStore[property];
  7829. }
  7830. var parent_1 = void 0;
  7831. var done = false;
  7832. do {
  7833. parent_1 = Object.getPrototypeOf(currentTarget);
  7834. if (!parent_1.getClassName) {
  7835. done = true;
  7836. break;
  7837. }
  7838. if (parent_1.getClassName() !== currentKey) {
  7839. break;
  7840. }
  7841. currentTarget = parent_1;
  7842. } while (parent_1);
  7843. if (done) {
  7844. break;
  7845. }
  7846. currentKey = parent_1.getClassName();
  7847. currentTarget = parent_1;
  7848. }
  7849. return store;
  7850. }
  7851. function generateSerializableMember(type, sourceName) {
  7852. return function (target, propertyKey) {
  7853. var classStore = getDirectStore(target);
  7854. if (!classStore[propertyKey]) {
  7855. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7856. }
  7857. };
  7858. }
  7859. function generateExpandMember(setCallback, targetKey) {
  7860. if (targetKey === void 0) { targetKey = null; }
  7861. return function (target, propertyKey) {
  7862. var key = targetKey || ("_" + propertyKey);
  7863. Object.defineProperty(target, propertyKey, {
  7864. get: function () {
  7865. return this[key];
  7866. },
  7867. set: function (value) {
  7868. if (this[key] === value) {
  7869. return;
  7870. }
  7871. this[key] = value;
  7872. target[setCallback].apply(this);
  7873. },
  7874. enumerable: true,
  7875. configurable: true
  7876. });
  7877. };
  7878. }
  7879. function expandToProperty(callback, targetKey) {
  7880. if (targetKey === void 0) { targetKey = null; }
  7881. return generateExpandMember(callback, targetKey);
  7882. }
  7883. BABYLON.expandToProperty = expandToProperty;
  7884. function serialize(sourceName) {
  7885. return generateSerializableMember(0, sourceName); // value member
  7886. }
  7887. BABYLON.serialize = serialize;
  7888. function serializeAsTexture(sourceName) {
  7889. return generateSerializableMember(1, sourceName); // texture member
  7890. }
  7891. BABYLON.serializeAsTexture = serializeAsTexture;
  7892. function serializeAsColor3(sourceName) {
  7893. return generateSerializableMember(2, sourceName); // color3 member
  7894. }
  7895. BABYLON.serializeAsColor3 = serializeAsColor3;
  7896. function serializeAsFresnelParameters(sourceName) {
  7897. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7898. }
  7899. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7900. function serializeAsVector2(sourceName) {
  7901. return generateSerializableMember(4, sourceName); // vector2 member
  7902. }
  7903. BABYLON.serializeAsVector2 = serializeAsVector2;
  7904. function serializeAsVector3(sourceName) {
  7905. return generateSerializableMember(5, sourceName); // vector3 member
  7906. }
  7907. BABYLON.serializeAsVector3 = serializeAsVector3;
  7908. function serializeAsMeshReference(sourceName) {
  7909. return generateSerializableMember(6, sourceName); // mesh reference member
  7910. }
  7911. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7912. function serializeAsColorCurves(sourceName) {
  7913. return generateSerializableMember(7, sourceName); // color curves
  7914. }
  7915. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7916. function serializeAsColor4(sourceName) {
  7917. return generateSerializableMember(8, sourceName); // color 4
  7918. }
  7919. BABYLON.serializeAsColor4 = serializeAsColor4;
  7920. function serializeAsImageProcessingConfiguration(sourceName) {
  7921. return generateSerializableMember(9, sourceName); // image processing
  7922. }
  7923. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7924. function serializeAsQuaternion(sourceName) {
  7925. return generateSerializableMember(10, sourceName); // quaternion member
  7926. }
  7927. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7928. /**
  7929. * Decorator used to define property that can be serialized as reference to a camera
  7930. * @param sourceName defines the name of the property to decorate
  7931. */
  7932. function serializeAsCameraReference(sourceName) {
  7933. return generateSerializableMember(11, sourceName); // camera reference member
  7934. }
  7935. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7936. var SerializationHelper = /** @class */ (function () {
  7937. function SerializationHelper() {
  7938. }
  7939. SerializationHelper.Serialize = function (entity, serializationObject) {
  7940. if (!serializationObject) {
  7941. serializationObject = {};
  7942. }
  7943. // Tags
  7944. if (BABYLON.Tags) {
  7945. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7946. }
  7947. var serializedProperties = getMergedStore(entity);
  7948. // Properties
  7949. for (var property in serializedProperties) {
  7950. var propertyDescriptor = serializedProperties[property];
  7951. var targetPropertyName = propertyDescriptor.sourceName || property;
  7952. var propertyType = propertyDescriptor.type;
  7953. var sourceProperty = entity[property];
  7954. if (sourceProperty !== undefined && sourceProperty !== null) {
  7955. switch (propertyType) {
  7956. case 0: // Value
  7957. serializationObject[targetPropertyName] = sourceProperty;
  7958. break;
  7959. case 1: // Texture
  7960. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7961. break;
  7962. case 2: // Color3
  7963. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7964. break;
  7965. case 3: // FresnelParameters
  7966. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7967. break;
  7968. case 4: // Vector2
  7969. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7970. break;
  7971. case 5: // Vector3
  7972. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7973. break;
  7974. case 6: // Mesh reference
  7975. serializationObject[targetPropertyName] = sourceProperty.id;
  7976. break;
  7977. case 7: // Color Curves
  7978. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7979. break;
  7980. case 8: // Color 4
  7981. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7982. break;
  7983. case 9: // Image Processing
  7984. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7985. break;
  7986. case 10: // Quaternion
  7987. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7988. break;
  7989. case 11: // Camera reference
  7990. serializationObject[targetPropertyName] = sourceProperty.id;
  7991. break;
  7992. }
  7993. }
  7994. }
  7995. return serializationObject;
  7996. };
  7997. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7998. if (rootUrl === void 0) { rootUrl = null; }
  7999. var destination = creationFunction();
  8000. if (!rootUrl) {
  8001. rootUrl = "";
  8002. }
  8003. // Tags
  8004. if (BABYLON.Tags) {
  8005. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8006. }
  8007. var classStore = getMergedStore(destination);
  8008. // Properties
  8009. for (var property in classStore) {
  8010. var propertyDescriptor = classStore[property];
  8011. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8012. var propertyType = propertyDescriptor.type;
  8013. if (sourceProperty !== undefined && sourceProperty !== null) {
  8014. var dest = destination;
  8015. switch (propertyType) {
  8016. case 0: // Value
  8017. dest[property] = sourceProperty;
  8018. break;
  8019. case 1: // Texture
  8020. if (scene) {
  8021. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8022. }
  8023. break;
  8024. case 2: // Color3
  8025. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8026. break;
  8027. case 3: // FresnelParameters
  8028. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8029. break;
  8030. case 4: // Vector2
  8031. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8032. break;
  8033. case 5: // Vector3
  8034. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8035. break;
  8036. case 6: // Mesh reference
  8037. if (scene) {
  8038. dest[property] = scene.getLastMeshByID(sourceProperty);
  8039. }
  8040. break;
  8041. case 7: // Color Curves
  8042. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8043. break;
  8044. case 8: // Color 4
  8045. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8046. break;
  8047. case 9: // Image Processing
  8048. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8049. break;
  8050. case 10: // Quaternion
  8051. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8052. break;
  8053. case 11: // Camera reference
  8054. if (scene) {
  8055. dest[property] = scene.getCameraByID(sourceProperty);
  8056. }
  8057. break;
  8058. }
  8059. }
  8060. }
  8061. return destination;
  8062. };
  8063. SerializationHelper.Clone = function (creationFunction, source) {
  8064. return _copySource(creationFunction, source, false);
  8065. };
  8066. SerializationHelper.Instanciate = function (creationFunction, source) {
  8067. return _copySource(creationFunction, source, true);
  8068. };
  8069. return SerializationHelper;
  8070. }());
  8071. BABYLON.SerializationHelper = SerializationHelper;
  8072. })(BABYLON || (BABYLON = {}));
  8073. //# sourceMappingURL=babylon.decorators.js.map
  8074. var BABYLON;
  8075. (function (BABYLON) {
  8076. /**
  8077. * Wrapper class for promise with external resolve and reject.
  8078. */
  8079. var Deferred = /** @class */ (function () {
  8080. /**
  8081. * Constructor for this deferred object.
  8082. */
  8083. function Deferred() {
  8084. var _this = this;
  8085. this.promise = new Promise(function (resolve, reject) {
  8086. _this._resolve = resolve;
  8087. _this._reject = reject;
  8088. });
  8089. }
  8090. Object.defineProperty(Deferred.prototype, "resolve", {
  8091. /**
  8092. * The resolve method of the promise associated with this deferred object.
  8093. */
  8094. get: function () {
  8095. return this._resolve;
  8096. },
  8097. enumerable: true,
  8098. configurable: true
  8099. });
  8100. Object.defineProperty(Deferred.prototype, "reject", {
  8101. /**
  8102. * The reject method of the promise associated with this deferred object.
  8103. */
  8104. get: function () {
  8105. return this._reject;
  8106. },
  8107. enumerable: true,
  8108. configurable: true
  8109. });
  8110. return Deferred;
  8111. }());
  8112. BABYLON.Deferred = Deferred;
  8113. })(BABYLON || (BABYLON = {}));
  8114. //# sourceMappingURL=babylon.deferred.js.map
  8115. var BABYLON;
  8116. (function (BABYLON) {
  8117. /**
  8118. * A class serves as a medium between the observable and its observers
  8119. */
  8120. var EventState = /** @class */ (function () {
  8121. /**
  8122. * Create a new EventState
  8123. * @param mask defines the mask associated with this state
  8124. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8125. * @param target defines the original target of the state
  8126. * @param currentTarget defines the current target of the state
  8127. */
  8128. function EventState(mask, skipNextObservers, target, currentTarget) {
  8129. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8130. this.initalize(mask, skipNextObservers, target, currentTarget);
  8131. }
  8132. /**
  8133. * Initialize the current event state
  8134. * @param mask defines the mask associated with this state
  8135. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8136. * @param target defines the original target of the state
  8137. * @param currentTarget defines the current target of the state
  8138. * @returns the current event state
  8139. */
  8140. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8141. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8142. this.mask = mask;
  8143. this.skipNextObservers = skipNextObservers;
  8144. this.target = target;
  8145. this.currentTarget = currentTarget;
  8146. return this;
  8147. };
  8148. return EventState;
  8149. }());
  8150. BABYLON.EventState = EventState;
  8151. /**
  8152. * Represent an Observer registered to a given Observable object.
  8153. */
  8154. var Observer = /** @class */ (function () {
  8155. /**
  8156. * Creates a new observer
  8157. * @param callback defines the callback to call when the observer is notified
  8158. * @param mask defines the mask of the observer (used to filter notifications)
  8159. * @param scope defines the current scope used to restore the JS context
  8160. */
  8161. function Observer(
  8162. /**
  8163. * Defines the callback to call when the observer is notified
  8164. */
  8165. callback,
  8166. /**
  8167. * Defines the mask of the observer (used to filter notifications)
  8168. */
  8169. mask,
  8170. /**
  8171. * Defines the current scope used to restore the JS context
  8172. */
  8173. scope) {
  8174. if (scope === void 0) { scope = null; }
  8175. this.callback = callback;
  8176. this.mask = mask;
  8177. this.scope = scope;
  8178. /** @hidden */
  8179. this._willBeUnregistered = false;
  8180. /**
  8181. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8182. */
  8183. this.unregisterOnNextCall = false;
  8184. }
  8185. return Observer;
  8186. }());
  8187. BABYLON.Observer = Observer;
  8188. /**
  8189. * Represent a list of observers registered to multiple Observables object.
  8190. */
  8191. var MultiObserver = /** @class */ (function () {
  8192. function MultiObserver() {
  8193. }
  8194. /**
  8195. * Release associated resources
  8196. */
  8197. MultiObserver.prototype.dispose = function () {
  8198. if (this._observers && this._observables) {
  8199. for (var index = 0; index < this._observers.length; index++) {
  8200. this._observables[index].remove(this._observers[index]);
  8201. }
  8202. }
  8203. this._observers = null;
  8204. this._observables = null;
  8205. };
  8206. /**
  8207. * Raise a callback when one of the observable will notify
  8208. * @param observables defines a list of observables to watch
  8209. * @param callback defines the callback to call on notification
  8210. * @param mask defines the mask used to filter notifications
  8211. * @param scope defines the current scope used to restore the JS context
  8212. * @returns the new MultiObserver
  8213. */
  8214. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8215. if (mask === void 0) { mask = -1; }
  8216. if (scope === void 0) { scope = null; }
  8217. var result = new MultiObserver();
  8218. result._observers = new Array();
  8219. result._observables = observables;
  8220. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8221. var observable = observables_1[_i];
  8222. var observer = observable.add(callback, mask, false, scope);
  8223. if (observer) {
  8224. result._observers.push(observer);
  8225. }
  8226. }
  8227. return result;
  8228. };
  8229. return MultiObserver;
  8230. }());
  8231. BABYLON.MultiObserver = MultiObserver;
  8232. /**
  8233. * The Observable class is a simple implementation of the Observable pattern.
  8234. *
  8235. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8236. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8237. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8238. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8239. */
  8240. var Observable = /** @class */ (function () {
  8241. /**
  8242. * Creates a new observable
  8243. * @param onObserverAdded defines a callback to call when a new observer is added
  8244. */
  8245. function Observable(onObserverAdded) {
  8246. this._observers = new Array();
  8247. this._eventState = new EventState(0);
  8248. if (onObserverAdded) {
  8249. this._onObserverAdded = onObserverAdded;
  8250. }
  8251. }
  8252. /**
  8253. * Create a new Observer with the specified callback
  8254. * @param callback the callback that will be executed for that Observer
  8255. * @param mask the mask used to filter observers
  8256. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8257. * @param scope optional scope for the callback to be called from
  8258. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8259. * @returns the new observer created for the callback
  8260. */
  8261. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8262. if (mask === void 0) { mask = -1; }
  8263. if (insertFirst === void 0) { insertFirst = false; }
  8264. if (scope === void 0) { scope = null; }
  8265. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8266. if (!callback) {
  8267. return null;
  8268. }
  8269. var observer = new Observer(callback, mask, scope);
  8270. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8271. if (insertFirst) {
  8272. this._observers.unshift(observer);
  8273. }
  8274. else {
  8275. this._observers.push(observer);
  8276. }
  8277. if (this._onObserverAdded) {
  8278. this._onObserverAdded(observer);
  8279. }
  8280. return observer;
  8281. };
  8282. /**
  8283. * Create a new Observer with the specified callback and unregisters after the next notification
  8284. * @param callback the callback that will be executed for that Observer
  8285. * @returns the new observer created for the callback
  8286. */
  8287. Observable.prototype.addOnce = function (callback) {
  8288. return this.add(callback, undefined, undefined, undefined, true);
  8289. };
  8290. /**
  8291. * Remove an Observer from the Observable object
  8292. * @param observer the instance of the Observer to remove
  8293. * @returns false if it doesn't belong to this Observable
  8294. */
  8295. Observable.prototype.remove = function (observer) {
  8296. if (!observer) {
  8297. return false;
  8298. }
  8299. var index = this._observers.indexOf(observer);
  8300. if (index !== -1) {
  8301. this._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 (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 () {
  9206. if (!aborted) {
  9207. requestFile();
  9208. }
  9209. };
  9210. var loadFromIndexedDB = function () {
  9211. // TODO: database needs to support aborting and should return a IFileRequest
  9212. if (aborted) {
  9213. return;
  9214. }
  9215. if (database) {
  9216. database.loadFileFromDB(url, function (data) {
  9217. if (!aborted) {
  9218. onSuccess(data);
  9219. }
  9220. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9221. }, onProgress ? function (event) {
  9222. if (!aborted) {
  9223. onProgress(event);
  9224. }
  9225. } : undefined, noIndexedDB_1, useArrayBuffer);
  9226. }
  9227. };
  9228. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9229. }
  9230. else {
  9231. requestFile();
  9232. }
  9233. return fileRequest;
  9234. };
  9235. /**
  9236. * Load a script (identified by an url). When the url returns, the
  9237. * content of this file is added into a new script element, attached to the DOM (body element)
  9238. */
  9239. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9240. var head = document.getElementsByTagName('head')[0];
  9241. var script = document.createElement('script');
  9242. script.type = 'text/javascript';
  9243. script.src = scriptUrl;
  9244. script.onload = function () {
  9245. if (onSuccess) {
  9246. onSuccess();
  9247. }
  9248. };
  9249. script.onerror = function (e) {
  9250. if (onError) {
  9251. onError("Unable to load script '" + scriptUrl + "'", e);
  9252. }
  9253. };
  9254. head.appendChild(script);
  9255. };
  9256. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9257. var reader = new FileReader();
  9258. var request = {
  9259. onCompleteObservable: new BABYLON.Observable(),
  9260. abort: function () { return reader.abort(); },
  9261. };
  9262. reader.onloadend = function (e) {
  9263. request.onCompleteObservable.notifyObservers(request);
  9264. };
  9265. reader.onload = function (e) {
  9266. //target doesn't have result from ts 1.3
  9267. callback(e.target['result']);
  9268. };
  9269. reader.onprogress = progressCallback;
  9270. reader.readAsDataURL(fileToLoad);
  9271. return request;
  9272. };
  9273. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9274. var reader = new FileReader();
  9275. var request = {
  9276. onCompleteObservable: new BABYLON.Observable(),
  9277. abort: function () { return reader.abort(); },
  9278. };
  9279. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9280. reader.onerror = function (e) {
  9281. Tools.Log("Error while reading file: " + fileToLoad.name);
  9282. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9283. };
  9284. reader.onload = function (e) {
  9285. //target doesn't have result from ts 1.3
  9286. callback(e.target['result']);
  9287. };
  9288. if (progressCallBack) {
  9289. reader.onprogress = progressCallBack;
  9290. }
  9291. if (!useArrayBuffer) {
  9292. // Asynchronous read
  9293. reader.readAsText(fileToLoad);
  9294. }
  9295. else {
  9296. reader.readAsArrayBuffer(fileToLoad);
  9297. }
  9298. return request;
  9299. };
  9300. //returns a downloadable url to a file content.
  9301. Tools.FileAsURL = function (content) {
  9302. var fileBlob = new Blob([content]);
  9303. var url = window.URL || window.webkitURL;
  9304. var link = url.createObjectURL(fileBlob);
  9305. return link;
  9306. };
  9307. // Misc.
  9308. Tools.Format = function (value, decimals) {
  9309. if (decimals === void 0) { decimals = 2; }
  9310. return value.toFixed(decimals);
  9311. };
  9312. Tools.CheckExtends = function (v, min, max) {
  9313. if (v.x < min.x)
  9314. min.x = v.x;
  9315. if (v.y < min.y)
  9316. min.y = v.y;
  9317. if (v.z < min.z)
  9318. min.z = v.z;
  9319. if (v.x > max.x)
  9320. max.x = v.x;
  9321. if (v.y > max.y)
  9322. max.y = v.y;
  9323. if (v.z > max.z)
  9324. max.z = v.z;
  9325. };
  9326. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9327. for (var prop in source) {
  9328. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9329. continue;
  9330. }
  9331. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9332. continue;
  9333. }
  9334. var sourceValue = source[prop];
  9335. var typeOfSourceValue = typeof sourceValue;
  9336. if (typeOfSourceValue === "function") {
  9337. continue;
  9338. }
  9339. try {
  9340. if (typeOfSourceValue === "object") {
  9341. if (sourceValue instanceof Array) {
  9342. destination[prop] = [];
  9343. if (sourceValue.length > 0) {
  9344. if (typeof sourceValue[0] == "object") {
  9345. for (var index = 0; index < sourceValue.length; index++) {
  9346. var clonedValue = cloneValue(sourceValue[index], destination);
  9347. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9348. destination[prop].push(clonedValue);
  9349. }
  9350. }
  9351. }
  9352. else {
  9353. destination[prop] = sourceValue.slice(0);
  9354. }
  9355. }
  9356. }
  9357. else {
  9358. destination[prop] = cloneValue(sourceValue, destination);
  9359. }
  9360. }
  9361. else {
  9362. destination[prop] = sourceValue;
  9363. }
  9364. }
  9365. catch (e) {
  9366. // Just ignore error (it could be because of a read-only property)
  9367. }
  9368. }
  9369. };
  9370. Tools.IsEmpty = function (obj) {
  9371. for (var i in obj) {
  9372. if (obj.hasOwnProperty(i)) {
  9373. return false;
  9374. }
  9375. }
  9376. return true;
  9377. };
  9378. Tools.RegisterTopRootEvents = function (events) {
  9379. for (var index = 0; index < events.length; index++) {
  9380. var event = events[index];
  9381. window.addEventListener(event.name, event.handler, false);
  9382. try {
  9383. if (window.parent) {
  9384. window.parent.addEventListener(event.name, event.handler, false);
  9385. }
  9386. }
  9387. catch (e) {
  9388. // Silently fails...
  9389. }
  9390. }
  9391. };
  9392. Tools.UnregisterTopRootEvents = function (events) {
  9393. for (var index = 0; index < events.length; index++) {
  9394. var event = events[index];
  9395. window.removeEventListener(event.name, event.handler);
  9396. try {
  9397. if (window.parent) {
  9398. window.parent.removeEventListener(event.name, event.handler);
  9399. }
  9400. }
  9401. catch (e) {
  9402. // Silently fails...
  9403. }
  9404. }
  9405. };
  9406. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9407. if (mimeType === void 0) { mimeType = "image/png"; }
  9408. // Read the contents of the framebuffer
  9409. var numberOfChannelsByLine = width * 4;
  9410. var halfHeight = height / 2;
  9411. //Reading datas from WebGL
  9412. var data = engine.readPixels(0, 0, width, height);
  9413. //To flip image on Y axis.
  9414. for (var i = 0; i < halfHeight; i++) {
  9415. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9416. var currentCell = j + i * numberOfChannelsByLine;
  9417. var targetLine = height - i - 1;
  9418. var targetCell = j + targetLine * numberOfChannelsByLine;
  9419. var temp = data[currentCell];
  9420. data[currentCell] = data[targetCell];
  9421. data[targetCell] = temp;
  9422. }
  9423. }
  9424. // Create a 2D canvas to store the result
  9425. if (!screenshotCanvas) {
  9426. screenshotCanvas = document.createElement('canvas');
  9427. }
  9428. screenshotCanvas.width = width;
  9429. screenshotCanvas.height = height;
  9430. var context = screenshotCanvas.getContext('2d');
  9431. if (context) {
  9432. // Copy the pixels to a 2D canvas
  9433. var imageData = context.createImageData(width, height);
  9434. var castData = (imageData.data);
  9435. castData.set(data);
  9436. context.putImageData(imageData, 0, 0);
  9437. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9438. }
  9439. };
  9440. /**
  9441. * Converts the canvas data to blob.
  9442. * This acts as a polyfill for browsers not supporting the to blob function.
  9443. * @param canvas Defines the canvas to extract the data from
  9444. * @param successCallback Defines the callback triggered once the data are available
  9445. * @param mimeType Defines the mime type of the result
  9446. */
  9447. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9448. if (mimeType === void 0) { mimeType = "image/png"; }
  9449. // We need HTMLCanvasElement.toBlob for HD screenshots
  9450. if (!canvas.toBlob) {
  9451. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9452. canvas.toBlob = function (callback, type, quality) {
  9453. var _this = this;
  9454. setTimeout(function () {
  9455. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9456. for (var i = 0; i < len; i++) {
  9457. arr[i] = binStr.charCodeAt(i);
  9458. }
  9459. callback(new Blob([arr]));
  9460. });
  9461. };
  9462. }
  9463. canvas.toBlob(function (blob) {
  9464. successCallback(blob);
  9465. }, mimeType);
  9466. };
  9467. /**
  9468. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9469. * @param successCallback Defines the callback triggered once the data are available
  9470. * @param mimeType Defines the mime type of the result
  9471. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9472. */
  9473. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9474. if (mimeType === void 0) { mimeType = "image/png"; }
  9475. if (successCallback) {
  9476. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9477. successCallback(base64Image);
  9478. }
  9479. else {
  9480. this.ToBlob(screenshotCanvas, function (blob) {
  9481. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9482. if (("download" in document.createElement("a"))) {
  9483. if (!fileName) {
  9484. var date = new Date();
  9485. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9486. fileName = "screenshot_" + stringDate + ".png";
  9487. }
  9488. Tools.Download(blob, fileName);
  9489. }
  9490. else {
  9491. var url = URL.createObjectURL(blob);
  9492. var newWindow = window.open("");
  9493. if (!newWindow)
  9494. return;
  9495. var img = newWindow.document.createElement("img");
  9496. img.onload = function () {
  9497. // no longer need to read the blob so it's revoked
  9498. URL.revokeObjectURL(url);
  9499. };
  9500. img.src = url;
  9501. newWindow.document.body.appendChild(img);
  9502. }
  9503. }, mimeType);
  9504. }
  9505. };
  9506. /**
  9507. * Downloads a blob in the browser
  9508. * @param blob defines the blob to download
  9509. * @param fileName defines the name of the downloaded file
  9510. */
  9511. Tools.Download = function (blob, fileName) {
  9512. var url = window.URL.createObjectURL(blob);
  9513. var a = document.createElement("a");
  9514. document.body.appendChild(a);
  9515. a.style.display = "none";
  9516. a.href = url;
  9517. a.download = fileName;
  9518. a.addEventListener("click", function () {
  9519. if (a.parentElement) {
  9520. a.parentElement.removeChild(a);
  9521. }
  9522. });
  9523. a.click();
  9524. window.URL.revokeObjectURL(url);
  9525. };
  9526. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9527. if (mimeType === void 0) { mimeType = "image/png"; }
  9528. var width;
  9529. var height;
  9530. // If a precision value is specified
  9531. if (size.precision) {
  9532. width = Math.round(engine.getRenderWidth() * size.precision);
  9533. height = Math.round(width / engine.getAspectRatio(camera));
  9534. }
  9535. else if (size.width && size.height) {
  9536. width = size.width;
  9537. height = size.height;
  9538. }
  9539. //If passing only width, computing height to keep display canvas ratio.
  9540. else if (size.width && !size.height) {
  9541. width = size.width;
  9542. height = Math.round(width / engine.getAspectRatio(camera));
  9543. }
  9544. //If passing only height, computing width to keep display canvas ratio.
  9545. else if (size.height && !size.width) {
  9546. height = size.height;
  9547. width = Math.round(height * engine.getAspectRatio(camera));
  9548. }
  9549. //Assuming here that "size" parameter is a number
  9550. else if (!isNaN(size)) {
  9551. height = size;
  9552. width = size;
  9553. }
  9554. else {
  9555. Tools.Error("Invalid 'size' parameter !");
  9556. return;
  9557. }
  9558. if (!screenshotCanvas) {
  9559. screenshotCanvas = document.createElement('canvas');
  9560. }
  9561. screenshotCanvas.width = width;
  9562. screenshotCanvas.height = height;
  9563. var renderContext = screenshotCanvas.getContext("2d");
  9564. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9565. var newWidth = width;
  9566. var newHeight = newWidth / ratio;
  9567. if (newHeight > height) {
  9568. newHeight = height;
  9569. newWidth = newHeight * ratio;
  9570. }
  9571. var offsetX = Math.max(0, width - newWidth) / 2;
  9572. var offsetY = Math.max(0, height - newHeight) / 2;
  9573. var renderingCanvas = engine.getRenderingCanvas();
  9574. if (renderContext && renderingCanvas) {
  9575. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9576. }
  9577. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9578. };
  9579. /**
  9580. * Generates an image screenshot from the specified camera.
  9581. *
  9582. * @param engine The engine to use for rendering
  9583. * @param camera The camera to use for rendering
  9584. * @param size This parameter can be set to a single number or to an object with the
  9585. * following (optional) properties: precision, width, height. If a single number is passed,
  9586. * it will be used for both width and height. If an object is passed, the screenshot size
  9587. * will be derived from the parameters. The precision property is a multiplier allowing
  9588. * rendering at a higher or lower resolution.
  9589. * @param successCallback The callback receives a single parameter which contains the
  9590. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9591. * src parameter of an <img> to display it.
  9592. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9593. * Check your browser for supported MIME types.
  9594. * @param samples Texture samples (default: 1)
  9595. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9596. * @param fileName A name for for the downloaded file.
  9597. * @constructor
  9598. */
  9599. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9600. if (mimeType === void 0) { mimeType = "image/png"; }
  9601. if (samples === void 0) { samples = 1; }
  9602. if (antialiasing === void 0) { antialiasing = false; }
  9603. var width;
  9604. var height;
  9605. //If a precision value is specified
  9606. if (size.precision) {
  9607. width = Math.round(engine.getRenderWidth() * size.precision);
  9608. height = Math.round(width / engine.getAspectRatio(camera));
  9609. size = { width: width, height: height };
  9610. }
  9611. else if (size.width && size.height) {
  9612. width = size.width;
  9613. height = size.height;
  9614. }
  9615. //If passing only width, computing height to keep display canvas ratio.
  9616. else if (size.width && !size.height) {
  9617. width = size.width;
  9618. height = Math.round(width / engine.getAspectRatio(camera));
  9619. size = { width: width, height: height };
  9620. }
  9621. //If passing only height, computing width to keep display canvas ratio.
  9622. else if (size.height && !size.width) {
  9623. height = size.height;
  9624. width = Math.round(height * engine.getAspectRatio(camera));
  9625. size = { width: width, height: height };
  9626. }
  9627. //Assuming here that "size" parameter is a number
  9628. else if (!isNaN(size)) {
  9629. height = size;
  9630. width = size;
  9631. }
  9632. else {
  9633. Tools.Error("Invalid 'size' parameter !");
  9634. return;
  9635. }
  9636. var scene = camera.getScene();
  9637. var previousCamera = null;
  9638. if (scene.activeCamera !== camera) {
  9639. previousCamera = scene.activeCamera;
  9640. scene.activeCamera = camera;
  9641. }
  9642. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9643. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9644. texture.renderList = null;
  9645. texture.samples = samples;
  9646. if (antialiasing) {
  9647. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9648. }
  9649. texture.onAfterRenderObservable.add(function () {
  9650. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9651. });
  9652. scene.incrementRenderId();
  9653. scene.resetCachedMaterial();
  9654. texture.render(true);
  9655. texture.dispose();
  9656. if (previousCamera) {
  9657. scene.activeCamera = previousCamera;
  9658. }
  9659. camera.getProjectionMatrix(true); // Force cache refresh;
  9660. };
  9661. // XHR response validator for local file scenario
  9662. Tools.ValidateXHRData = function (xhr, dataType) {
  9663. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9664. if (dataType === void 0) { dataType = 7; }
  9665. try {
  9666. if (dataType & 1) {
  9667. if (xhr.responseText && xhr.responseText.length > 0) {
  9668. return true;
  9669. }
  9670. else if (dataType === 1) {
  9671. return false;
  9672. }
  9673. }
  9674. if (dataType & 2) {
  9675. // Check header width and height since there is no "TGA" magic number
  9676. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9677. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9678. return true;
  9679. }
  9680. else if (dataType === 2) {
  9681. return false;
  9682. }
  9683. }
  9684. if (dataType & 4) {
  9685. // Check for the "DDS" magic number
  9686. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9687. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9688. return true;
  9689. }
  9690. else {
  9691. return false;
  9692. }
  9693. }
  9694. }
  9695. catch (e) {
  9696. // Global protection
  9697. }
  9698. return false;
  9699. };
  9700. /**
  9701. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9702. * Be aware Math.random() could cause collisions, but:
  9703. * "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"
  9704. */
  9705. Tools.RandomId = function () {
  9706. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9707. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9708. return v.toString(16);
  9709. });
  9710. };
  9711. /**
  9712. * Test if the given uri is a base64 string.
  9713. * @param uri The uri to test
  9714. * @return True if the uri is a base64 string or false otherwise.
  9715. */
  9716. Tools.IsBase64 = function (uri) {
  9717. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9718. };
  9719. /**
  9720. * Decode the given base64 uri.
  9721. * @param uri The uri to decode
  9722. * @return The decoded base64 data.
  9723. */
  9724. Tools.DecodeBase64 = function (uri) {
  9725. var decodedString = atob(uri.split(",")[1]);
  9726. var bufferLength = decodedString.length;
  9727. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9728. for (var i = 0; i < bufferLength; i++) {
  9729. bufferView[i] = decodedString.charCodeAt(i);
  9730. }
  9731. return bufferView.buffer;
  9732. };
  9733. Object.defineProperty(Tools, "NoneLogLevel", {
  9734. get: function () {
  9735. return Tools._NoneLogLevel;
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Object.defineProperty(Tools, "MessageLogLevel", {
  9741. get: function () {
  9742. return Tools._MessageLogLevel;
  9743. },
  9744. enumerable: true,
  9745. configurable: true
  9746. });
  9747. Object.defineProperty(Tools, "WarningLogLevel", {
  9748. get: function () {
  9749. return Tools._WarningLogLevel;
  9750. },
  9751. enumerable: true,
  9752. configurable: true
  9753. });
  9754. Object.defineProperty(Tools, "ErrorLogLevel", {
  9755. get: function () {
  9756. return Tools._ErrorLogLevel;
  9757. },
  9758. enumerable: true,
  9759. configurable: true
  9760. });
  9761. Object.defineProperty(Tools, "AllLogLevel", {
  9762. get: function () {
  9763. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9764. },
  9765. enumerable: true,
  9766. configurable: true
  9767. });
  9768. Tools._AddLogEntry = function (entry) {
  9769. Tools._LogCache = entry + Tools._LogCache;
  9770. if (Tools.OnNewCacheEntry) {
  9771. Tools.OnNewCacheEntry(entry);
  9772. }
  9773. };
  9774. Tools._FormatMessage = function (message) {
  9775. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9776. var date = new Date();
  9777. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9778. };
  9779. Tools._LogDisabled = function (message) {
  9780. // nothing to do
  9781. };
  9782. Tools._LogEnabled = function (message) {
  9783. var formattedMessage = Tools._FormatMessage(message);
  9784. console.log("BJS - " + formattedMessage);
  9785. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9786. Tools._AddLogEntry(entry);
  9787. };
  9788. Tools._WarnDisabled = function (message) {
  9789. // nothing to do
  9790. };
  9791. Tools._WarnEnabled = function (message) {
  9792. var formattedMessage = Tools._FormatMessage(message);
  9793. console.warn("BJS - " + formattedMessage);
  9794. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9795. Tools._AddLogEntry(entry);
  9796. };
  9797. Tools._ErrorDisabled = function (message) {
  9798. // nothing to do
  9799. };
  9800. Tools._ErrorEnabled = function (message) {
  9801. Tools.errorsCount++;
  9802. var formattedMessage = Tools._FormatMessage(message);
  9803. console.error("BJS - " + formattedMessage);
  9804. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9805. Tools._AddLogEntry(entry);
  9806. };
  9807. Object.defineProperty(Tools, "LogCache", {
  9808. get: function () {
  9809. return Tools._LogCache;
  9810. },
  9811. enumerable: true,
  9812. configurable: true
  9813. });
  9814. Tools.ClearLogCache = function () {
  9815. Tools._LogCache = "";
  9816. Tools.errorsCount = 0;
  9817. };
  9818. Object.defineProperty(Tools, "LogLevels", {
  9819. set: function (level) {
  9820. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9821. Tools.Log = Tools._LogEnabled;
  9822. }
  9823. else {
  9824. Tools.Log = Tools._LogDisabled;
  9825. }
  9826. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9827. Tools.Warn = Tools._WarnEnabled;
  9828. }
  9829. else {
  9830. Tools.Warn = Tools._WarnDisabled;
  9831. }
  9832. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9833. Tools.Error = Tools._ErrorEnabled;
  9834. }
  9835. else {
  9836. Tools.Error = Tools._ErrorDisabled;
  9837. }
  9838. },
  9839. enumerable: true,
  9840. configurable: true
  9841. });
  9842. Tools.IsWindowObjectExist = function () {
  9843. return (typeof window) !== "undefined";
  9844. };
  9845. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9846. get: function () {
  9847. return Tools._PerformanceNoneLogLevel;
  9848. },
  9849. enumerable: true,
  9850. configurable: true
  9851. });
  9852. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9853. get: function () {
  9854. return Tools._PerformanceUserMarkLogLevel;
  9855. },
  9856. enumerable: true,
  9857. configurable: true
  9858. });
  9859. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9860. get: function () {
  9861. return Tools._PerformanceConsoleLogLevel;
  9862. },
  9863. enumerable: true,
  9864. configurable: true
  9865. });
  9866. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9867. set: function (level) {
  9868. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9869. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9870. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9871. return;
  9872. }
  9873. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9874. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9875. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9876. return;
  9877. }
  9878. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9879. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9885. };
  9886. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9887. };
  9888. Tools._StartUserMark = function (counterName, condition) {
  9889. if (condition === void 0) { condition = true; }
  9890. if (!Tools._performance) {
  9891. if (!Tools.IsWindowObjectExist()) {
  9892. return;
  9893. }
  9894. Tools._performance = window.performance;
  9895. }
  9896. if (!condition || !Tools._performance.mark) {
  9897. return;
  9898. }
  9899. Tools._performance.mark(counterName + "-Begin");
  9900. };
  9901. Tools._EndUserMark = function (counterName, condition) {
  9902. if (condition === void 0) { condition = true; }
  9903. if (!condition || !Tools._performance.mark) {
  9904. return;
  9905. }
  9906. Tools._performance.mark(counterName + "-End");
  9907. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9908. };
  9909. Tools._StartPerformanceConsole = function (counterName, condition) {
  9910. if (condition === void 0) { condition = true; }
  9911. if (!condition) {
  9912. return;
  9913. }
  9914. Tools._StartUserMark(counterName, condition);
  9915. if (console.time) {
  9916. console.time(counterName);
  9917. }
  9918. };
  9919. Tools._EndPerformanceConsole = function (counterName, condition) {
  9920. if (condition === void 0) { condition = true; }
  9921. if (!condition) {
  9922. return;
  9923. }
  9924. Tools._EndUserMark(counterName, condition);
  9925. if (console.time) {
  9926. console.timeEnd(counterName);
  9927. }
  9928. };
  9929. Object.defineProperty(Tools, "Now", {
  9930. get: function () {
  9931. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9932. return window.performance.now();
  9933. }
  9934. return Date.now();
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. /**
  9940. * This method will return the name of the class used to create the instance of the given object.
  9941. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9942. * @param object the object to get the class name from
  9943. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9944. */
  9945. Tools.GetClassName = function (object, isType) {
  9946. if (isType === void 0) { isType = false; }
  9947. var name = null;
  9948. if (!isType && object.getClassName) {
  9949. name = object.getClassName();
  9950. }
  9951. else {
  9952. if (object instanceof Object) {
  9953. var classObj = isType ? object : Object.getPrototypeOf(object);
  9954. name = classObj.constructor["__bjsclassName__"];
  9955. }
  9956. if (!name) {
  9957. name = typeof object;
  9958. }
  9959. }
  9960. return name;
  9961. };
  9962. Tools.First = function (array, predicate) {
  9963. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9964. var el = array_1[_i];
  9965. if (predicate(el)) {
  9966. return el;
  9967. }
  9968. }
  9969. return null;
  9970. };
  9971. /**
  9972. * This method will return the name of the full name of the class, including its owning module (if any).
  9973. * 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).
  9974. * @param object the object to get the class name from
  9975. * @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.
  9976. */
  9977. Tools.getFullClassName = function (object, isType) {
  9978. if (isType === void 0) { isType = false; }
  9979. var className = null;
  9980. var moduleName = null;
  9981. if (!isType && object.getClassName) {
  9982. className = object.getClassName();
  9983. }
  9984. else {
  9985. if (object instanceof Object) {
  9986. var classObj = isType ? object : Object.getPrototypeOf(object);
  9987. className = classObj.constructor["__bjsclassName__"];
  9988. moduleName = classObj.constructor["__bjsmoduleName__"];
  9989. }
  9990. if (!className) {
  9991. className = typeof object;
  9992. }
  9993. }
  9994. if (!className) {
  9995. return null;
  9996. }
  9997. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9998. };
  9999. /**
  10000. * 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.
  10001. * @param array
  10002. */
  10003. Tools.arrayOrStringFeeder = function (array) {
  10004. return function (index) {
  10005. if (index >= array.length) {
  10006. return null;
  10007. }
  10008. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10009. if (val && val.getHashCode) {
  10010. val = val.getHashCode();
  10011. }
  10012. if (typeof val === "string") {
  10013. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10014. }
  10015. return val;
  10016. };
  10017. };
  10018. /**
  10019. * Compute the hashCode of a stream of number
  10020. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10021. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10022. * @return the hash code computed
  10023. */
  10024. Tools.hashCodeFromStream = function (feeder) {
  10025. // Based from here: http://stackoverflow.com/a/7616484/802124
  10026. var hash = 0;
  10027. var index = 0;
  10028. var chr = feeder(index++);
  10029. while (chr != null) {
  10030. hash = ((hash << 5) - hash) + chr;
  10031. hash |= 0; // Convert to 32bit integer
  10032. chr = feeder(index++);
  10033. }
  10034. return hash;
  10035. };
  10036. /**
  10037. * Returns a promise that resolves after the given amount of time.
  10038. * @param delay Number of milliseconds to delay
  10039. * @returns Promise that resolves after the given amount of time
  10040. */
  10041. Tools.DelayAsync = function (delay) {
  10042. return new Promise(function (resolve) {
  10043. setTimeout(function () {
  10044. resolve();
  10045. }, delay);
  10046. });
  10047. };
  10048. /**
  10049. * Gets the current gradient from an array of IValueGradient
  10050. * @param ratio defines the current ratio to get
  10051. * @param gradients defines the array of IValueGradient
  10052. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10053. */
  10054. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10055. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10056. var currentGradient = gradients[gradientIndex];
  10057. var nextGradient = gradients[gradientIndex + 1];
  10058. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10059. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10060. updateFunc(currentGradient, nextGradient, scale);
  10061. }
  10062. }
  10063. };
  10064. Tools.BaseUrl = "";
  10065. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10066. /**
  10067. * Default behaviour for cors in the application.
  10068. * It can be a string if the expected behavior is identical in the entire app.
  10069. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10070. */
  10071. Tools.CorsBehavior = "anonymous";
  10072. Tools.UseFallbackTexture = true;
  10073. /**
  10074. * Use this object to register external classes like custom textures or material
  10075. * to allow the laoders to instantiate them
  10076. */
  10077. Tools.RegisteredExternalClasses = {};
  10078. // Used in case of a texture loading problem
  10079. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUW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iiivhT++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";
  10080. Tools._tmpFloatArray = new Float32Array(1);
  10081. Tools.PreprocessUrl = function (url) {
  10082. return url;
  10083. };
  10084. // Logs
  10085. Tools._NoneLogLevel = 0;
  10086. Tools._MessageLogLevel = 1;
  10087. Tools._WarningLogLevel = 2;
  10088. Tools._ErrorLogLevel = 4;
  10089. Tools._LogCache = "";
  10090. Tools.errorsCount = 0;
  10091. Tools.Log = Tools._LogEnabled;
  10092. Tools.Warn = Tools._WarnEnabled;
  10093. Tools.Error = Tools._ErrorEnabled;
  10094. // Performances
  10095. Tools._PerformanceNoneLogLevel = 0;
  10096. Tools._PerformanceUserMarkLogLevel = 1;
  10097. Tools._PerformanceConsoleLogLevel = 2;
  10098. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10099. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10100. return Tools;
  10101. }());
  10102. BABYLON.Tools = Tools;
  10103. /**
  10104. * This class is used to track a performance counter which is number based.
  10105. * The user has access to many properties which give statistics of different nature
  10106. *
  10107. * The implementer can track two kinds of Performance Counter: time and count
  10108. * 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.
  10109. * 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.
  10110. */
  10111. var PerfCounter = /** @class */ (function () {
  10112. function PerfCounter() {
  10113. this._startMonitoringTime = 0;
  10114. this._min = 0;
  10115. this._max = 0;
  10116. this._average = 0;
  10117. this._lastSecAverage = 0;
  10118. this._current = 0;
  10119. this._totalValueCount = 0;
  10120. this._totalAccumulated = 0;
  10121. this._lastSecAccumulated = 0;
  10122. this._lastSecTime = 0;
  10123. this._lastSecValueCount = 0;
  10124. }
  10125. Object.defineProperty(PerfCounter.prototype, "min", {
  10126. /**
  10127. * Returns the smallest value ever
  10128. */
  10129. get: function () {
  10130. return this._min;
  10131. },
  10132. enumerable: true,
  10133. configurable: true
  10134. });
  10135. Object.defineProperty(PerfCounter.prototype, "max", {
  10136. /**
  10137. * Returns the biggest value ever
  10138. */
  10139. get: function () {
  10140. return this._max;
  10141. },
  10142. enumerable: true,
  10143. configurable: true
  10144. });
  10145. Object.defineProperty(PerfCounter.prototype, "average", {
  10146. /**
  10147. * Returns the average value since the performance counter is running
  10148. */
  10149. get: function () {
  10150. return this._average;
  10151. },
  10152. enumerable: true,
  10153. configurable: true
  10154. });
  10155. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10156. /**
  10157. * Returns the average value of the last second the counter was monitored
  10158. */
  10159. get: function () {
  10160. return this._lastSecAverage;
  10161. },
  10162. enumerable: true,
  10163. configurable: true
  10164. });
  10165. Object.defineProperty(PerfCounter.prototype, "current", {
  10166. /**
  10167. * Returns the current value
  10168. */
  10169. get: function () {
  10170. return this._current;
  10171. },
  10172. enumerable: true,
  10173. configurable: true
  10174. });
  10175. Object.defineProperty(PerfCounter.prototype, "total", {
  10176. get: function () {
  10177. return this._totalAccumulated;
  10178. },
  10179. enumerable: true,
  10180. configurable: true
  10181. });
  10182. Object.defineProperty(PerfCounter.prototype, "count", {
  10183. get: function () {
  10184. return this._totalValueCount;
  10185. },
  10186. enumerable: true,
  10187. configurable: true
  10188. });
  10189. /**
  10190. * Call this method to start monitoring a new frame.
  10191. * 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.
  10192. */
  10193. PerfCounter.prototype.fetchNewFrame = function () {
  10194. this._totalValueCount++;
  10195. this._current = 0;
  10196. this._lastSecValueCount++;
  10197. };
  10198. /**
  10199. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10200. * @param newCount the count value to add to the monitored count
  10201. * @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.
  10202. */
  10203. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10204. if (!PerfCounter.Enabled) {
  10205. return;
  10206. }
  10207. this._current += newCount;
  10208. if (fetchResult) {
  10209. this._fetchResult();
  10210. }
  10211. };
  10212. /**
  10213. * Start monitoring this performance counter
  10214. */
  10215. PerfCounter.prototype.beginMonitoring = function () {
  10216. if (!PerfCounter.Enabled) {
  10217. return;
  10218. }
  10219. this._startMonitoringTime = Tools.Now;
  10220. };
  10221. /**
  10222. * Compute the time lapsed since the previous beginMonitoring() call.
  10223. * @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
  10224. */
  10225. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10226. if (newFrame === void 0) { newFrame = true; }
  10227. if (!PerfCounter.Enabled) {
  10228. return;
  10229. }
  10230. if (newFrame) {
  10231. this.fetchNewFrame();
  10232. }
  10233. var currentTime = Tools.Now;
  10234. this._current = currentTime - this._startMonitoringTime;
  10235. if (newFrame) {
  10236. this._fetchResult();
  10237. }
  10238. };
  10239. PerfCounter.prototype._fetchResult = function () {
  10240. this._totalAccumulated += this._current;
  10241. this._lastSecAccumulated += this._current;
  10242. // Min/Max update
  10243. this._min = Math.min(this._min, this._current);
  10244. this._max = Math.max(this._max, this._current);
  10245. this._average = this._totalAccumulated / this._totalValueCount;
  10246. // Reset last sec?
  10247. var now = Tools.Now;
  10248. if ((now - this._lastSecTime) > 1000) {
  10249. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10250. this._lastSecTime = now;
  10251. this._lastSecAccumulated = 0;
  10252. this._lastSecValueCount = 0;
  10253. }
  10254. };
  10255. PerfCounter.Enabled = true;
  10256. return PerfCounter;
  10257. }());
  10258. BABYLON.PerfCounter = PerfCounter;
  10259. /**
  10260. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10261. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10262. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10263. * @param name The name of the class, case should be preserved
  10264. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10265. */
  10266. function className(name, module) {
  10267. return function (target) {
  10268. target["__bjsclassName__"] = name;
  10269. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10270. };
  10271. }
  10272. BABYLON.className = className;
  10273. /**
  10274. * An implementation of a loop for asynchronous functions.
  10275. */
  10276. var AsyncLoop = /** @class */ (function () {
  10277. /**
  10278. * Constroctor.
  10279. * @param iterations the number of iterations.
  10280. * @param _fn the function to run each iteration
  10281. * @param _successCallback the callback that will be called upon succesful execution
  10282. * @param offset starting offset.
  10283. */
  10284. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10285. if (offset === void 0) { offset = 0; }
  10286. this.iterations = iterations;
  10287. this._fn = _fn;
  10288. this._successCallback = _successCallback;
  10289. this.index = offset - 1;
  10290. this._done = false;
  10291. }
  10292. /**
  10293. * Execute the next iteration. Must be called after the last iteration was finished.
  10294. */
  10295. AsyncLoop.prototype.executeNext = function () {
  10296. if (!this._done) {
  10297. if (this.index + 1 < this.iterations) {
  10298. ++this.index;
  10299. this._fn(this);
  10300. }
  10301. else {
  10302. this.breakLoop();
  10303. }
  10304. }
  10305. };
  10306. /**
  10307. * Break the loop and run the success callback.
  10308. */
  10309. AsyncLoop.prototype.breakLoop = function () {
  10310. this._done = true;
  10311. this._successCallback();
  10312. };
  10313. /**
  10314. * Helper function
  10315. */
  10316. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10317. if (offset === void 0) { offset = 0; }
  10318. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10319. loop.executeNext();
  10320. return loop;
  10321. };
  10322. /**
  10323. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10324. * @param iterations total number of iterations
  10325. * @param syncedIterations number of synchronous iterations in each async iteration.
  10326. * @param fn the function to call each iteration.
  10327. * @param callback a success call back that will be called when iterating stops.
  10328. * @param breakFunction a break condition (optional)
  10329. * @param timeout timeout settings for the setTimeout function. default - 0.
  10330. * @constructor
  10331. */
  10332. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10333. if (timeout === void 0) { timeout = 0; }
  10334. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10335. if (breakFunction && breakFunction())
  10336. loop.breakLoop();
  10337. else {
  10338. setTimeout(function () {
  10339. for (var i = 0; i < syncedIterations; ++i) {
  10340. var iteration = (loop.index * syncedIterations) + i;
  10341. if (iteration >= iterations)
  10342. break;
  10343. fn(iteration);
  10344. if (breakFunction && breakFunction()) {
  10345. loop.breakLoop();
  10346. break;
  10347. }
  10348. }
  10349. loop.executeNext();
  10350. }, timeout);
  10351. }
  10352. }, callback);
  10353. };
  10354. return AsyncLoop;
  10355. }());
  10356. BABYLON.AsyncLoop = AsyncLoop;
  10357. })(BABYLON || (BABYLON = {}));
  10358. //# sourceMappingURL=babylon.tools.js.map
  10359. var BABYLON;
  10360. (function (BABYLON) {
  10361. var PromiseStates;
  10362. (function (PromiseStates) {
  10363. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10364. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10365. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10366. })(PromiseStates || (PromiseStates = {}));
  10367. var FulFillmentAgregator = /** @class */ (function () {
  10368. function FulFillmentAgregator() {
  10369. this.count = 0;
  10370. this.target = 0;
  10371. this.results = [];
  10372. }
  10373. return FulFillmentAgregator;
  10374. }());
  10375. var InternalPromise = /** @class */ (function () {
  10376. function InternalPromise(resolver) {
  10377. var _this = this;
  10378. this._state = PromiseStates.Pending;
  10379. this._children = new Array();
  10380. this._rejectWasConsumed = false;
  10381. if (!resolver) {
  10382. return;
  10383. }
  10384. try {
  10385. resolver(function (value) {
  10386. _this._resolve(value);
  10387. }, function (reason) {
  10388. _this._reject(reason);
  10389. });
  10390. }
  10391. catch (e) {
  10392. this._reject(e);
  10393. }
  10394. }
  10395. Object.defineProperty(InternalPromise.prototype, "_result", {
  10396. get: function () {
  10397. return this._resultValue;
  10398. },
  10399. set: function (value) {
  10400. this._resultValue = value;
  10401. if (this._parent && this._parent._result === undefined) {
  10402. this._parent._result = value;
  10403. }
  10404. },
  10405. enumerable: true,
  10406. configurable: true
  10407. });
  10408. InternalPromise.prototype.catch = function (onRejected) {
  10409. return this.then(undefined, onRejected);
  10410. };
  10411. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10412. var _this = this;
  10413. var newPromise = new InternalPromise();
  10414. newPromise._onFulfilled = onFulfilled;
  10415. newPromise._onRejected = onRejected;
  10416. // Composition
  10417. this._children.push(newPromise);
  10418. newPromise._parent = this;
  10419. if (this._state !== PromiseStates.Pending) {
  10420. BABYLON.Tools.SetImmediate(function () {
  10421. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10422. var returnedValue = newPromise._resolve(_this._result);
  10423. if (returnedValue !== undefined && returnedValue !== null) {
  10424. if (returnedValue._state !== undefined) {
  10425. var returnedPromise = returnedValue;
  10426. newPromise._children.push(returnedPromise);
  10427. returnedPromise._parent = newPromise;
  10428. newPromise = returnedPromise;
  10429. }
  10430. else {
  10431. newPromise._result = returnedValue;
  10432. }
  10433. }
  10434. }
  10435. else {
  10436. newPromise._reject(_this._reason);
  10437. }
  10438. });
  10439. }
  10440. return newPromise;
  10441. };
  10442. InternalPromise.prototype._moveChildren = function (children) {
  10443. var _this = this;
  10444. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10445. this._children.forEach(function (child) {
  10446. child._parent = _this;
  10447. });
  10448. if (this._state === PromiseStates.Fulfilled) {
  10449. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10450. var child = _b[_i];
  10451. child._resolve(this._result);
  10452. }
  10453. }
  10454. else if (this._state === PromiseStates.Rejected) {
  10455. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10456. var child = _d[_c];
  10457. child._reject(this._reason);
  10458. }
  10459. }
  10460. var _a;
  10461. };
  10462. InternalPromise.prototype._resolve = function (value) {
  10463. try {
  10464. this._state = PromiseStates.Fulfilled;
  10465. var returnedValue = null;
  10466. if (this._onFulfilled) {
  10467. returnedValue = this._onFulfilled(value);
  10468. }
  10469. if (returnedValue !== undefined && returnedValue !== null) {
  10470. if (returnedValue._state !== undefined) {
  10471. // Transmit children
  10472. var returnedPromise = returnedValue;
  10473. returnedPromise._parent = this;
  10474. returnedPromise._moveChildren(this._children);
  10475. value = returnedPromise._result;
  10476. }
  10477. else {
  10478. value = returnedValue;
  10479. }
  10480. }
  10481. this._result = value;
  10482. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10483. var child = _a[_i];
  10484. child._resolve(value);
  10485. }
  10486. this._children.length = 0;
  10487. delete this._onFulfilled;
  10488. delete this._onRejected;
  10489. }
  10490. catch (e) {
  10491. this._reject(e, true);
  10492. }
  10493. };
  10494. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10495. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10496. this._state = PromiseStates.Rejected;
  10497. this._reason = reason;
  10498. if (this._onRejected && !onLocalThrow) {
  10499. try {
  10500. this._onRejected(reason);
  10501. this._rejectWasConsumed = true;
  10502. }
  10503. catch (e) {
  10504. reason = e;
  10505. }
  10506. }
  10507. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10508. var child = _a[_i];
  10509. if (this._rejectWasConsumed) {
  10510. child._resolve(null);
  10511. }
  10512. else {
  10513. child._reject(reason);
  10514. }
  10515. }
  10516. this._children.length = 0;
  10517. delete this._onFulfilled;
  10518. delete this._onRejected;
  10519. };
  10520. InternalPromise.resolve = function (value) {
  10521. var newPromise = new InternalPromise();
  10522. newPromise._resolve(value);
  10523. return newPromise;
  10524. };
  10525. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10526. promise.then(function (value) {
  10527. agregator.results[index] = value;
  10528. agregator.count++;
  10529. if (agregator.count === agregator.target) {
  10530. agregator.rootPromise._resolve(agregator.results);
  10531. }
  10532. return null;
  10533. }, function (reason) {
  10534. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10535. agregator.rootPromise._reject(reason);
  10536. }
  10537. });
  10538. };
  10539. InternalPromise.all = function (promises) {
  10540. var newPromise = new InternalPromise();
  10541. var agregator = new FulFillmentAgregator();
  10542. agregator.target = promises.length;
  10543. agregator.rootPromise = newPromise;
  10544. if (promises.length) {
  10545. for (var index = 0; index < promises.length; index++) {
  10546. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10547. }
  10548. }
  10549. else {
  10550. newPromise._resolve([]);
  10551. }
  10552. return newPromise;
  10553. };
  10554. InternalPromise.race = function (promises) {
  10555. var newPromise = new InternalPromise();
  10556. if (promises.length) {
  10557. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10558. var promise = promises_1[_i];
  10559. promise.then(function (value) {
  10560. if (newPromise) {
  10561. newPromise._resolve(value);
  10562. newPromise = null;
  10563. }
  10564. return null;
  10565. }, function (reason) {
  10566. if (newPromise) {
  10567. newPromise._reject(reason);
  10568. newPromise = null;
  10569. }
  10570. });
  10571. }
  10572. }
  10573. return newPromise;
  10574. };
  10575. return InternalPromise;
  10576. }());
  10577. /**
  10578. * Helper class that provides a small promise polyfill
  10579. */
  10580. var PromisePolyfill = /** @class */ (function () {
  10581. function PromisePolyfill() {
  10582. }
  10583. /**
  10584. * Static function used to check if the polyfill is required
  10585. * If this is the case then the function will inject the polyfill to window.Promise
  10586. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10587. */
  10588. PromisePolyfill.Apply = function (force) {
  10589. if (force === void 0) { force = false; }
  10590. if (force || typeof Promise === 'undefined') {
  10591. var root = window;
  10592. root.Promise = InternalPromise;
  10593. }
  10594. };
  10595. return PromisePolyfill;
  10596. }());
  10597. BABYLON.PromisePolyfill = PromisePolyfill;
  10598. })(BABYLON || (BABYLON = {}));
  10599. //# sourceMappingURL=babylon.promise.js.map
  10600. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10601. var BABYLON;
  10602. (function (BABYLON) {
  10603. /**
  10604. * Helper class to push actions to a pool of workers.
  10605. */
  10606. var WorkerPool = /** @class */ (function () {
  10607. /**
  10608. * Constructor
  10609. * @param workers Array of workers to use for actions
  10610. */
  10611. function WorkerPool(workers) {
  10612. this._pendingActions = new Array();
  10613. this._workerInfos = workers.map(function (worker) { return ({
  10614. worker: worker,
  10615. active: false
  10616. }); });
  10617. }
  10618. /**
  10619. * Terminates all workers and clears any pending actions.
  10620. */
  10621. WorkerPool.prototype.dispose = function () {
  10622. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10623. var workerInfo = _a[_i];
  10624. workerInfo.worker.terminate();
  10625. }
  10626. delete this._workerInfos;
  10627. delete this._pendingActions;
  10628. };
  10629. /**
  10630. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10631. * pended until a worker has completed its action.
  10632. * @param action The action to perform. Call onComplete when the action is complete.
  10633. */
  10634. WorkerPool.prototype.push = function (action) {
  10635. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10636. var workerInfo = _a[_i];
  10637. if (!workerInfo.active) {
  10638. this._execute(workerInfo, action);
  10639. return;
  10640. }
  10641. }
  10642. this._pendingActions.push(action);
  10643. };
  10644. WorkerPool.prototype._execute = function (workerInfo, action) {
  10645. var _this = this;
  10646. workerInfo.active = true;
  10647. action(workerInfo.worker, function () {
  10648. workerInfo.active = false;
  10649. var nextAction = _this._pendingActions.shift();
  10650. if (nextAction) {
  10651. _this._execute(workerInfo, nextAction);
  10652. }
  10653. });
  10654. };
  10655. return WorkerPool;
  10656. }());
  10657. BABYLON.WorkerPool = WorkerPool;
  10658. })(BABYLON || (BABYLON = {}));
  10659. //# sourceMappingURL=babylon.workerPool.js.map
  10660. var BABYLON;
  10661. (function (BABYLON) {
  10662. /**
  10663. * @hidden
  10664. **/
  10665. var _AlphaState = /** @class */ (function () {
  10666. /**
  10667. * Initializes the state.
  10668. */
  10669. function _AlphaState() {
  10670. this._isAlphaBlendDirty = false;
  10671. this._isBlendFunctionParametersDirty = false;
  10672. this._isBlendEquationParametersDirty = false;
  10673. this._isBlendConstantsDirty = false;
  10674. this._alphaBlend = false;
  10675. this._blendFunctionParameters = new Array(4);
  10676. this._blendEquationParameters = new Array(2);
  10677. this._blendConstants = new Array(4);
  10678. this.reset();
  10679. }
  10680. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10681. get: function () {
  10682. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10683. },
  10684. enumerable: true,
  10685. configurable: true
  10686. });
  10687. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10688. get: function () {
  10689. return this._alphaBlend;
  10690. },
  10691. set: function (value) {
  10692. if (this._alphaBlend === value) {
  10693. return;
  10694. }
  10695. this._alphaBlend = value;
  10696. this._isAlphaBlendDirty = true;
  10697. },
  10698. enumerable: true,
  10699. configurable: true
  10700. });
  10701. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10702. if (this._blendConstants[0] === r &&
  10703. this._blendConstants[1] === g &&
  10704. this._blendConstants[2] === b &&
  10705. this._blendConstants[3] === a) {
  10706. return;
  10707. }
  10708. this._blendConstants[0] = r;
  10709. this._blendConstants[1] = g;
  10710. this._blendConstants[2] = b;
  10711. this._blendConstants[3] = a;
  10712. this._isBlendConstantsDirty = true;
  10713. };
  10714. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10715. if (this._blendFunctionParameters[0] === value0 &&
  10716. this._blendFunctionParameters[1] === value1 &&
  10717. this._blendFunctionParameters[2] === value2 &&
  10718. this._blendFunctionParameters[3] === value3) {
  10719. return;
  10720. }
  10721. this._blendFunctionParameters[0] = value0;
  10722. this._blendFunctionParameters[1] = value1;
  10723. this._blendFunctionParameters[2] = value2;
  10724. this._blendFunctionParameters[3] = value3;
  10725. this._isBlendFunctionParametersDirty = true;
  10726. };
  10727. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10728. if (this._blendEquationParameters[0] === rgb &&
  10729. this._blendEquationParameters[1] === alpha) {
  10730. return;
  10731. }
  10732. this._blendEquationParameters[0] = rgb;
  10733. this._blendEquationParameters[1] = alpha;
  10734. this._isBlendEquationParametersDirty = true;
  10735. };
  10736. _AlphaState.prototype.reset = function () {
  10737. this._alphaBlend = false;
  10738. this._blendFunctionParameters[0] = null;
  10739. this._blendFunctionParameters[1] = null;
  10740. this._blendFunctionParameters[2] = null;
  10741. this._blendFunctionParameters[3] = null;
  10742. this._blendEquationParameters[0] = null;
  10743. this._blendEquationParameters[1] = null;
  10744. this._blendConstants[0] = null;
  10745. this._blendConstants[1] = null;
  10746. this._blendConstants[2] = null;
  10747. this._blendConstants[3] = null;
  10748. this._isAlphaBlendDirty = true;
  10749. this._isBlendFunctionParametersDirty = false;
  10750. this._isBlendEquationParametersDirty = false;
  10751. this._isBlendConstantsDirty = false;
  10752. };
  10753. _AlphaState.prototype.apply = function (gl) {
  10754. if (!this.isDirty) {
  10755. return;
  10756. }
  10757. // Alpha blend
  10758. if (this._isAlphaBlendDirty) {
  10759. if (this._alphaBlend) {
  10760. gl.enable(gl.BLEND);
  10761. }
  10762. else {
  10763. gl.disable(gl.BLEND);
  10764. }
  10765. this._isAlphaBlendDirty = false;
  10766. }
  10767. // Alpha function
  10768. if (this._isBlendFunctionParametersDirty) {
  10769. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10770. this._isBlendFunctionParametersDirty = false;
  10771. }
  10772. // Alpha equation
  10773. if (this._isBlendEquationParametersDirty) {
  10774. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10775. this._isBlendEquationParametersDirty = false;
  10776. }
  10777. // Constants
  10778. if (this._isBlendConstantsDirty) {
  10779. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10780. this._isBlendConstantsDirty = false;
  10781. }
  10782. };
  10783. return _AlphaState;
  10784. }());
  10785. BABYLON._AlphaState = _AlphaState;
  10786. })(BABYLON || (BABYLON = {}));
  10787. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10788. var BABYLON;
  10789. (function (BABYLON) {
  10790. /**
  10791. * @hidden
  10792. **/
  10793. var _DepthCullingState = /** @class */ (function () {
  10794. /**
  10795. * Initializes the state.
  10796. */
  10797. function _DepthCullingState() {
  10798. this._isDepthTestDirty = false;
  10799. this._isDepthMaskDirty = false;
  10800. this._isDepthFuncDirty = false;
  10801. this._isCullFaceDirty = false;
  10802. this._isCullDirty = false;
  10803. this._isZOffsetDirty = false;
  10804. this._isFrontFaceDirty = false;
  10805. this.reset();
  10806. }
  10807. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10808. get: function () {
  10809. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10810. },
  10811. enumerable: true,
  10812. configurable: true
  10813. });
  10814. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10815. get: function () {
  10816. return this._zOffset;
  10817. },
  10818. set: function (value) {
  10819. if (this._zOffset === value) {
  10820. return;
  10821. }
  10822. this._zOffset = value;
  10823. this._isZOffsetDirty = true;
  10824. },
  10825. enumerable: true,
  10826. configurable: true
  10827. });
  10828. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10829. get: function () {
  10830. return this._cullFace;
  10831. },
  10832. set: function (value) {
  10833. if (this._cullFace === value) {
  10834. return;
  10835. }
  10836. this._cullFace = value;
  10837. this._isCullFaceDirty = true;
  10838. },
  10839. enumerable: true,
  10840. configurable: true
  10841. });
  10842. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10843. get: function () {
  10844. return this._cull;
  10845. },
  10846. set: function (value) {
  10847. if (this._cull === value) {
  10848. return;
  10849. }
  10850. this._cull = value;
  10851. this._isCullDirty = true;
  10852. },
  10853. enumerable: true,
  10854. configurable: true
  10855. });
  10856. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10857. get: function () {
  10858. return this._depthFunc;
  10859. },
  10860. set: function (value) {
  10861. if (this._depthFunc === value) {
  10862. return;
  10863. }
  10864. this._depthFunc = value;
  10865. this._isDepthFuncDirty = true;
  10866. },
  10867. enumerable: true,
  10868. configurable: true
  10869. });
  10870. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10871. get: function () {
  10872. return this._depthMask;
  10873. },
  10874. set: function (value) {
  10875. if (this._depthMask === value) {
  10876. return;
  10877. }
  10878. this._depthMask = value;
  10879. this._isDepthMaskDirty = true;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10885. get: function () {
  10886. return this._depthTest;
  10887. },
  10888. set: function (value) {
  10889. if (this._depthTest === value) {
  10890. return;
  10891. }
  10892. this._depthTest = value;
  10893. this._isDepthTestDirty = true;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10899. get: function () {
  10900. return this._frontFace;
  10901. },
  10902. set: function (value) {
  10903. if (this._frontFace === value) {
  10904. return;
  10905. }
  10906. this._frontFace = value;
  10907. this._isFrontFaceDirty = true;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. _DepthCullingState.prototype.reset = function () {
  10913. this._depthMask = true;
  10914. this._depthTest = true;
  10915. this._depthFunc = null;
  10916. this._cullFace = null;
  10917. this._cull = null;
  10918. this._zOffset = 0;
  10919. this._frontFace = null;
  10920. this._isDepthTestDirty = true;
  10921. this._isDepthMaskDirty = true;
  10922. this._isDepthFuncDirty = false;
  10923. this._isCullFaceDirty = false;
  10924. this._isCullDirty = false;
  10925. this._isZOffsetDirty = false;
  10926. this._isFrontFaceDirty = false;
  10927. };
  10928. _DepthCullingState.prototype.apply = function (gl) {
  10929. if (!this.isDirty) {
  10930. return;
  10931. }
  10932. // Cull
  10933. if (this._isCullDirty) {
  10934. if (this.cull) {
  10935. gl.enable(gl.CULL_FACE);
  10936. }
  10937. else {
  10938. gl.disable(gl.CULL_FACE);
  10939. }
  10940. this._isCullDirty = false;
  10941. }
  10942. // Cull face
  10943. if (this._isCullFaceDirty) {
  10944. gl.cullFace(this.cullFace);
  10945. this._isCullFaceDirty = false;
  10946. }
  10947. // Depth mask
  10948. if (this._isDepthMaskDirty) {
  10949. gl.depthMask(this.depthMask);
  10950. this._isDepthMaskDirty = false;
  10951. }
  10952. // Depth test
  10953. if (this._isDepthTestDirty) {
  10954. if (this.depthTest) {
  10955. gl.enable(gl.DEPTH_TEST);
  10956. }
  10957. else {
  10958. gl.disable(gl.DEPTH_TEST);
  10959. }
  10960. this._isDepthTestDirty = false;
  10961. }
  10962. // Depth func
  10963. if (this._isDepthFuncDirty) {
  10964. gl.depthFunc(this.depthFunc);
  10965. this._isDepthFuncDirty = false;
  10966. }
  10967. // zOffset
  10968. if (this._isZOffsetDirty) {
  10969. if (this.zOffset) {
  10970. gl.enable(gl.POLYGON_OFFSET_FILL);
  10971. gl.polygonOffset(this.zOffset, 0);
  10972. }
  10973. else {
  10974. gl.disable(gl.POLYGON_OFFSET_FILL);
  10975. }
  10976. this._isZOffsetDirty = false;
  10977. }
  10978. // Front face
  10979. if (this._isFrontFaceDirty) {
  10980. gl.frontFace(this.frontFace);
  10981. this._isFrontFaceDirty = false;
  10982. }
  10983. };
  10984. return _DepthCullingState;
  10985. }());
  10986. BABYLON._DepthCullingState = _DepthCullingState;
  10987. })(BABYLON || (BABYLON = {}));
  10988. //# sourceMappingURL=babylon.depthCullingState.js.map
  10989. var BABYLON;
  10990. (function (BABYLON) {
  10991. /**
  10992. * @hidden
  10993. **/
  10994. var _StencilState = /** @class */ (function () {
  10995. function _StencilState() {
  10996. this._isStencilTestDirty = false;
  10997. this._isStencilMaskDirty = false;
  10998. this._isStencilFuncDirty = false;
  10999. this._isStencilOpDirty = false;
  11000. this.reset();
  11001. }
  11002. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11003. get: function () {
  11004. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11005. },
  11006. enumerable: true,
  11007. configurable: true
  11008. });
  11009. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11010. get: function () {
  11011. return this._stencilFunc;
  11012. },
  11013. set: function (value) {
  11014. if (this._stencilFunc === value) {
  11015. return;
  11016. }
  11017. this._stencilFunc = value;
  11018. this._isStencilFuncDirty = true;
  11019. },
  11020. enumerable: true,
  11021. configurable: true
  11022. });
  11023. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11024. get: function () {
  11025. return this._stencilFuncRef;
  11026. },
  11027. set: function (value) {
  11028. if (this._stencilFuncRef === value) {
  11029. return;
  11030. }
  11031. this._stencilFuncRef = value;
  11032. this._isStencilFuncDirty = true;
  11033. },
  11034. enumerable: true,
  11035. configurable: true
  11036. });
  11037. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11038. get: function () {
  11039. return this._stencilFuncMask;
  11040. },
  11041. set: function (value) {
  11042. if (this._stencilFuncMask === value) {
  11043. return;
  11044. }
  11045. this._stencilFuncMask = value;
  11046. this._isStencilFuncDirty = true;
  11047. },
  11048. enumerable: true,
  11049. configurable: true
  11050. });
  11051. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11052. get: function () {
  11053. return this._stencilOpStencilFail;
  11054. },
  11055. set: function (value) {
  11056. if (this._stencilOpStencilFail === value) {
  11057. return;
  11058. }
  11059. this._stencilOpStencilFail = value;
  11060. this._isStencilOpDirty = true;
  11061. },
  11062. enumerable: true,
  11063. configurable: true
  11064. });
  11065. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11066. get: function () {
  11067. return this._stencilOpDepthFail;
  11068. },
  11069. set: function (value) {
  11070. if (this._stencilOpDepthFail === value) {
  11071. return;
  11072. }
  11073. this._stencilOpDepthFail = value;
  11074. this._isStencilOpDirty = true;
  11075. },
  11076. enumerable: true,
  11077. configurable: true
  11078. });
  11079. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11080. get: function () {
  11081. return this._stencilOpStencilDepthPass;
  11082. },
  11083. set: function (value) {
  11084. if (this._stencilOpStencilDepthPass === value) {
  11085. return;
  11086. }
  11087. this._stencilOpStencilDepthPass = value;
  11088. this._isStencilOpDirty = true;
  11089. },
  11090. enumerable: true,
  11091. configurable: true
  11092. });
  11093. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11094. get: function () {
  11095. return this._stencilMask;
  11096. },
  11097. set: function (value) {
  11098. if (this._stencilMask === value) {
  11099. return;
  11100. }
  11101. this._stencilMask = value;
  11102. this._isStencilMaskDirty = true;
  11103. },
  11104. enumerable: true,
  11105. configurable: true
  11106. });
  11107. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11108. get: function () {
  11109. return this._stencilTest;
  11110. },
  11111. set: function (value) {
  11112. if (this._stencilTest === value) {
  11113. return;
  11114. }
  11115. this._stencilTest = value;
  11116. this._isStencilTestDirty = true;
  11117. },
  11118. enumerable: true,
  11119. configurable: true
  11120. });
  11121. _StencilState.prototype.reset = function () {
  11122. this._stencilTest = false;
  11123. this._stencilMask = 0xFF;
  11124. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11125. this._stencilFuncRef = 1;
  11126. this._stencilFuncMask = 0xFF;
  11127. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11128. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11129. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11130. this._isStencilTestDirty = true;
  11131. this._isStencilMaskDirty = true;
  11132. this._isStencilFuncDirty = true;
  11133. this._isStencilOpDirty = true;
  11134. };
  11135. _StencilState.prototype.apply = function (gl) {
  11136. if (!this.isDirty) {
  11137. return;
  11138. }
  11139. // Stencil test
  11140. if (this._isStencilTestDirty) {
  11141. if (this.stencilTest) {
  11142. gl.enable(gl.STENCIL_TEST);
  11143. }
  11144. else {
  11145. gl.disable(gl.STENCIL_TEST);
  11146. }
  11147. this._isStencilTestDirty = false;
  11148. }
  11149. // Stencil mask
  11150. if (this._isStencilMaskDirty) {
  11151. gl.stencilMask(this.stencilMask);
  11152. this._isStencilMaskDirty = false;
  11153. }
  11154. // Stencil func
  11155. if (this._isStencilFuncDirty) {
  11156. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11157. this._isStencilFuncDirty = false;
  11158. }
  11159. // Stencil op
  11160. if (this._isStencilOpDirty) {
  11161. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11162. this._isStencilOpDirty = false;
  11163. }
  11164. };
  11165. return _StencilState;
  11166. }());
  11167. BABYLON._StencilState = _StencilState;
  11168. })(BABYLON || (BABYLON = {}));
  11169. //# sourceMappingURL=babylon.stencilState.js.map
  11170. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11171. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11172. s = arguments[i];
  11173. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11174. t[p] = s[p];
  11175. }
  11176. return t;
  11177. };
  11178. var BABYLON;
  11179. (function (BABYLON) {
  11180. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11181. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11182. };
  11183. var compileRawShader = function (gl, source, type) {
  11184. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11185. gl.shaderSource(shader, source);
  11186. gl.compileShader(shader);
  11187. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11188. var log = gl.getShaderInfoLog(shader);
  11189. if (log) {
  11190. throw new Error(log);
  11191. }
  11192. }
  11193. if (!shader) {
  11194. throw new Error("Something went wrong while compile the shader.");
  11195. }
  11196. return shader;
  11197. };
  11198. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11199. var magFilter = gl.NEAREST;
  11200. var minFilter = gl.NEAREST;
  11201. switch (samplingMode) {
  11202. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11203. magFilter = gl.LINEAR;
  11204. if (generateMipMaps) {
  11205. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11206. }
  11207. else {
  11208. minFilter = gl.LINEAR;
  11209. }
  11210. break;
  11211. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11212. magFilter = gl.LINEAR;
  11213. if (generateMipMaps) {
  11214. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11215. }
  11216. else {
  11217. minFilter = gl.LINEAR;
  11218. }
  11219. break;
  11220. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11221. magFilter = gl.NEAREST;
  11222. if (generateMipMaps) {
  11223. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11224. }
  11225. else {
  11226. minFilter = gl.NEAREST;
  11227. }
  11228. break;
  11229. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11230. magFilter = gl.NEAREST;
  11231. if (generateMipMaps) {
  11232. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11233. }
  11234. else {
  11235. minFilter = gl.NEAREST;
  11236. }
  11237. break;
  11238. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11239. magFilter = gl.NEAREST;
  11240. if (generateMipMaps) {
  11241. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11242. }
  11243. else {
  11244. minFilter = gl.LINEAR;
  11245. }
  11246. break;
  11247. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11248. magFilter = gl.NEAREST;
  11249. if (generateMipMaps) {
  11250. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11251. }
  11252. else {
  11253. minFilter = gl.LINEAR;
  11254. }
  11255. break;
  11256. case BABYLON.Texture.NEAREST_LINEAR:
  11257. magFilter = gl.NEAREST;
  11258. minFilter = gl.LINEAR;
  11259. break;
  11260. case BABYLON.Texture.NEAREST_NEAREST:
  11261. magFilter = gl.NEAREST;
  11262. minFilter = gl.NEAREST;
  11263. break;
  11264. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11265. magFilter = gl.LINEAR;
  11266. if (generateMipMaps) {
  11267. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11268. }
  11269. else {
  11270. minFilter = gl.NEAREST;
  11271. }
  11272. break;
  11273. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11274. magFilter = gl.LINEAR;
  11275. if (generateMipMaps) {
  11276. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11277. }
  11278. else {
  11279. minFilter = gl.NEAREST;
  11280. }
  11281. break;
  11282. case BABYLON.Texture.LINEAR_LINEAR:
  11283. magFilter = gl.LINEAR;
  11284. minFilter = gl.LINEAR;
  11285. break;
  11286. case BABYLON.Texture.LINEAR_NEAREST:
  11287. magFilter = gl.LINEAR;
  11288. minFilter = gl.NEAREST;
  11289. break;
  11290. }
  11291. return {
  11292. min: minFilter,
  11293. mag: magFilter
  11294. };
  11295. };
  11296. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11297. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11298. var img;
  11299. var onload = function () {
  11300. loadedImages[index] = img;
  11301. loadedImages._internalCount++;
  11302. if (scene) {
  11303. scene._removePendingData(img);
  11304. }
  11305. if (loadedImages._internalCount === 6) {
  11306. onfinish(loadedImages);
  11307. }
  11308. };
  11309. var onerror = function (message, exception) {
  11310. if (scene) {
  11311. scene._removePendingData(img);
  11312. }
  11313. if (onErrorCallBack) {
  11314. onErrorCallBack(message, exception);
  11315. }
  11316. };
  11317. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11318. if (scene) {
  11319. scene._addPendingData(img);
  11320. }
  11321. };
  11322. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11323. if (onError === void 0) { onError = null; }
  11324. var loadedImages = [];
  11325. loadedImages._internalCount = 0;
  11326. for (var index = 0; index < 6; index++) {
  11327. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11328. }
  11329. };
  11330. var BufferPointer = /** @class */ (function () {
  11331. function BufferPointer() {
  11332. }
  11333. return BufferPointer;
  11334. }());
  11335. /**
  11336. * Interface for attribute information associated with buffer instanciation
  11337. */
  11338. var InstancingAttributeInfo = /** @class */ (function () {
  11339. function InstancingAttributeInfo() {
  11340. }
  11341. return InstancingAttributeInfo;
  11342. }());
  11343. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11344. /**
  11345. * Define options used to create a render target texture
  11346. */
  11347. var RenderTargetCreationOptions = /** @class */ (function () {
  11348. function RenderTargetCreationOptions() {
  11349. }
  11350. return RenderTargetCreationOptions;
  11351. }());
  11352. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11353. /**
  11354. * Define options used to create a depth texture
  11355. */
  11356. var DepthTextureCreationOptions = /** @class */ (function () {
  11357. function DepthTextureCreationOptions() {
  11358. }
  11359. return DepthTextureCreationOptions;
  11360. }());
  11361. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11362. /**
  11363. * Class used to describe the capabilities of the engine relatively to the current browser
  11364. */
  11365. var EngineCapabilities = /** @class */ (function () {
  11366. function EngineCapabilities() {
  11367. }
  11368. return EngineCapabilities;
  11369. }());
  11370. BABYLON.EngineCapabilities = EngineCapabilities;
  11371. /**
  11372. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11373. */
  11374. var Engine = /** @class */ (function () {
  11375. /**
  11376. * Creates a new engine
  11377. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11378. * @param antialias defines enable antialiasing (default: false)
  11379. * @param options defines further options to be sent to the getContext() function
  11380. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11381. */
  11382. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11383. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11384. var _this = this;
  11385. // Public members
  11386. /**
  11387. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11388. */
  11389. this.forcePOTTextures = false;
  11390. /**
  11391. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11392. */
  11393. this.isFullscreen = false;
  11394. /**
  11395. * Gets a boolean indicating if the pointer is currently locked
  11396. */
  11397. this.isPointerLock = false;
  11398. /**
  11399. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11400. */
  11401. this.cullBackFaces = true;
  11402. /**
  11403. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11404. */
  11405. this.renderEvenInBackground = true;
  11406. /**
  11407. * Gets or sets a boolean indicating that cache can be kept between frames
  11408. */
  11409. this.preventCacheWipeBetweenFrames = false;
  11410. /**
  11411. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11412. **/
  11413. this.enableOfflineSupport = false;
  11414. /**
  11415. * 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)
  11416. **/
  11417. this.disableManifestCheck = false;
  11418. /**
  11419. * Gets the list of created scenes
  11420. */
  11421. this.scenes = new Array();
  11422. /**
  11423. * Gets the list of created postprocesses
  11424. */
  11425. this.postProcesses = new Array();
  11426. // Observables
  11427. /**
  11428. * Observable event triggered each time the rendering canvas is resized
  11429. */
  11430. this.onResizeObservable = new BABYLON.Observable();
  11431. /**
  11432. * Observable event triggered each time the canvas loses focus
  11433. */
  11434. this.onCanvasBlurObservable = new BABYLON.Observable();
  11435. /**
  11436. * Observable event triggered each time the canvas gains focus
  11437. */
  11438. this.onCanvasFocusObservable = new BABYLON.Observable();
  11439. /**
  11440. * Observable event triggered each time the canvas receives pointerout event
  11441. */
  11442. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11443. /**
  11444. * Observable event triggered before each texture is initialized
  11445. */
  11446. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11447. //WebVR
  11448. this._vrDisplay = undefined;
  11449. this._vrSupported = false;
  11450. this._vrExclusivePointerMode = false;
  11451. // Uniform buffers list
  11452. /**
  11453. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11454. */
  11455. this.disableUniformBuffers = false;
  11456. /** @hidden */
  11457. this._uniformBuffers = new Array();
  11458. // Observables
  11459. /**
  11460. * Observable raised when the engine begins a new frame
  11461. */
  11462. this.onBeginFrameObservable = new BABYLON.Observable();
  11463. /**
  11464. * Observable raised when the engine ends the current frame
  11465. */
  11466. this.onEndFrameObservable = new BABYLON.Observable();
  11467. /**
  11468. * Observable raised when the engine is about to compile a shader
  11469. */
  11470. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11471. /**
  11472. * Observable raised when the engine has jsut compiled a shader
  11473. */
  11474. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11475. this._windowIsBackground = false;
  11476. this._webGLVersion = 1.0;
  11477. /** @hidden */
  11478. this._badOS = false;
  11479. /** @hidden */
  11480. this._badDesktopOS = false;
  11481. /**
  11482. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11483. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11484. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11485. */
  11486. this.disableTextureBindingOptimization = false;
  11487. /**
  11488. * Observable signaled when VR display mode changes
  11489. */
  11490. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11491. /**
  11492. * Observable signaled when VR request present is complete
  11493. */
  11494. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11495. /**
  11496. * Observable signaled when VR request present starts
  11497. */
  11498. this.onVRRequestPresentStart = new BABYLON.Observable();
  11499. this._colorWrite = true;
  11500. /** @hidden */
  11501. this._drawCalls = new BABYLON.PerfCounter();
  11502. /** @hidden */
  11503. this._textureCollisions = new BABYLON.PerfCounter();
  11504. this._renderingQueueLaunched = false;
  11505. this._activeRenderLoops = new Array();
  11506. // Deterministic lockstepMaxSteps
  11507. this._deterministicLockstep = false;
  11508. this._lockstepMaxSteps = 4;
  11509. // Lost context
  11510. /**
  11511. * Observable signaled when a context lost event is raised
  11512. */
  11513. this.onContextLostObservable = new BABYLON.Observable();
  11514. /**
  11515. * Observable signaled when a context restored event is raised
  11516. */
  11517. this.onContextRestoredObservable = new BABYLON.Observable();
  11518. this._contextWasLost = false;
  11519. this._doNotHandleContextLost = false;
  11520. // FPS
  11521. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11522. this._fps = 60;
  11523. this._deltaTime = 0;
  11524. /**
  11525. * Turn this value on if you want to pause FPS computation when in background
  11526. */
  11527. this.disablePerformanceMonitorInBackground = false;
  11528. // States
  11529. /** @hidden */
  11530. this._depthCullingState = new BABYLON._DepthCullingState();
  11531. /** @hidden */
  11532. this._stencilState = new BABYLON._StencilState();
  11533. /** @hidden */
  11534. this._alphaState = new BABYLON._AlphaState();
  11535. /** @hidden */
  11536. this._alphaMode = Engine.ALPHA_DISABLE;
  11537. // Cache
  11538. this._internalTexturesCache = new Array();
  11539. /** @hidden */
  11540. this._activeChannel = 0;
  11541. this._currentTextureChannel = -1;
  11542. /** @hidden */
  11543. this._boundTexturesCache = {};
  11544. this._compiledEffects = {};
  11545. this._vertexAttribArraysEnabled = [];
  11546. this._uintIndicesCurrentlySet = false;
  11547. this._currentBoundBuffer = new Array();
  11548. /** @hidden */
  11549. this._currentFramebuffer = null;
  11550. this._currentBufferPointers = new Array();
  11551. this._currentInstanceLocations = new Array();
  11552. this._currentInstanceBuffers = new Array();
  11553. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11554. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11555. this._vaoRecordInProgress = false;
  11556. this._mustWipeVertexAttributes = false;
  11557. this._nextFreeTextureSlots = new Array();
  11558. this._maxSimultaneousTextures = 0;
  11559. this._activeRequests = new Array();
  11560. // Hardware supported Compressed Textures
  11561. this._texturesSupported = new Array();
  11562. /**
  11563. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11564. */
  11565. this.premultipliedAlpha = true;
  11566. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11567. this._onVRFullScreenTriggered = function () {
  11568. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11569. //get the old size before we change
  11570. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11571. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11572. //get the width and height, change the render size
  11573. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11574. _this.setHardwareScalingLevel(1);
  11575. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11576. }
  11577. else {
  11578. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11579. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11580. }
  11581. };
  11582. this._unpackFlipYCached = null;
  11583. this._boundUniforms = {};
  11584. // Register promises
  11585. BABYLON.PromisePolyfill.Apply();
  11586. var canvas = null;
  11587. Engine.Instances.push(this);
  11588. if (!canvasOrContext) {
  11589. return;
  11590. }
  11591. options = options || {};
  11592. if (canvasOrContext.getContext) {
  11593. canvas = canvasOrContext;
  11594. this._renderingCanvas = canvas;
  11595. if (antialias != null) {
  11596. options.antialias = antialias;
  11597. }
  11598. if (options.deterministicLockstep === undefined) {
  11599. options.deterministicLockstep = false;
  11600. }
  11601. if (options.lockstepMaxSteps === undefined) {
  11602. options.lockstepMaxSteps = 4;
  11603. }
  11604. if (options.preserveDrawingBuffer === undefined) {
  11605. options.preserveDrawingBuffer = false;
  11606. }
  11607. if (options.audioEngine === undefined) {
  11608. options.audioEngine = true;
  11609. }
  11610. if (options.stencil === undefined) {
  11611. options.stencil = true;
  11612. }
  11613. if (options.premultipliedAlpha === false) {
  11614. this.premultipliedAlpha = false;
  11615. }
  11616. this._deterministicLockstep = options.deterministicLockstep;
  11617. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11618. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11619. // Exceptions
  11620. if (navigator && navigator.userAgent) {
  11621. var ua = navigator.userAgent;
  11622. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11623. var exception = _a[_i];
  11624. var key = exception.key;
  11625. var targets = exception.targets;
  11626. if (ua.indexOf(key) > -1) {
  11627. if (exception.capture && exception.captureConstraint) {
  11628. var capture = exception.capture;
  11629. var constraint = exception.captureConstraint;
  11630. var regex = new RegExp(capture);
  11631. var matches = regex.exec(ua);
  11632. if (matches && matches.length > 0) {
  11633. var capturedValue = parseInt(matches[matches.length - 1]);
  11634. if (capturedValue >= constraint) {
  11635. continue;
  11636. }
  11637. }
  11638. }
  11639. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11640. var target = targets_1[_b];
  11641. switch (target) {
  11642. case "uniformBuffer":
  11643. this.disableUniformBuffers = true;
  11644. break;
  11645. case "textureBindingOptimization":
  11646. this.disableTextureBindingOptimization = true;
  11647. break;
  11648. }
  11649. }
  11650. }
  11651. }
  11652. }
  11653. // GL
  11654. if (!options.disableWebGL2Support) {
  11655. try {
  11656. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11657. if (this._gl) {
  11658. this._webGLVersion = 2.0;
  11659. }
  11660. }
  11661. catch (e) {
  11662. // Do nothing
  11663. }
  11664. }
  11665. if (!this._gl) {
  11666. if (!canvas) {
  11667. throw new Error("The provided canvas is null or undefined.");
  11668. }
  11669. try {
  11670. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11671. }
  11672. catch (e) {
  11673. throw new Error("WebGL not supported");
  11674. }
  11675. }
  11676. if (!this._gl) {
  11677. throw new Error("WebGL not supported");
  11678. }
  11679. this._onCanvasFocus = function () {
  11680. _this.onCanvasFocusObservable.notifyObservers(_this);
  11681. };
  11682. this._onCanvasBlur = function () {
  11683. _this.onCanvasBlurObservable.notifyObservers(_this);
  11684. };
  11685. canvas.addEventListener("focus", this._onCanvasFocus);
  11686. canvas.addEventListener("blur", this._onCanvasBlur);
  11687. this._onBlur = function () {
  11688. if (_this.disablePerformanceMonitorInBackground) {
  11689. _this._performanceMonitor.disable();
  11690. }
  11691. _this._windowIsBackground = true;
  11692. };
  11693. this._onFocus = function () {
  11694. if (_this.disablePerformanceMonitorInBackground) {
  11695. _this._performanceMonitor.enable();
  11696. }
  11697. _this._windowIsBackground = false;
  11698. };
  11699. this._onCanvasPointerOut = function (ev) {
  11700. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11701. };
  11702. window.addEventListener("blur", this._onBlur);
  11703. window.addEventListener("focus", this._onFocus);
  11704. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11705. // Context lost
  11706. if (!this._doNotHandleContextLost) {
  11707. this._onContextLost = function (evt) {
  11708. evt.preventDefault();
  11709. _this._contextWasLost = true;
  11710. BABYLON.Tools.Warn("WebGL context lost.");
  11711. _this.onContextLostObservable.notifyObservers(_this);
  11712. };
  11713. this._onContextRestored = function (evt) {
  11714. // Adding a timeout to avoid race condition at browser level
  11715. setTimeout(function () {
  11716. // Rebuild gl context
  11717. _this._initGLContext();
  11718. // Rebuild effects
  11719. _this._rebuildEffects();
  11720. // Rebuild textures
  11721. _this._rebuildInternalTextures();
  11722. // Rebuild buffers
  11723. _this._rebuildBuffers();
  11724. // Cache
  11725. _this.wipeCaches(true);
  11726. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11727. _this.onContextRestoredObservable.notifyObservers(_this);
  11728. _this._contextWasLost = false;
  11729. }, 0);
  11730. };
  11731. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11732. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11733. }
  11734. }
  11735. else {
  11736. this._gl = canvasOrContext;
  11737. this._renderingCanvas = this._gl.canvas;
  11738. if (this._gl.renderbufferStorageMultisample) {
  11739. this._webGLVersion = 2.0;
  11740. }
  11741. options.stencil = this._gl.getContextAttributes().stencil;
  11742. }
  11743. // Viewport
  11744. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11745. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11746. this.resize();
  11747. this._isStencilEnable = options.stencil ? true : false;
  11748. this._initGLContext();
  11749. if (canvas) {
  11750. // Fullscreen
  11751. this._onFullscreenChange = function () {
  11752. if (document.fullscreen !== undefined) {
  11753. _this.isFullscreen = document.fullscreen;
  11754. }
  11755. else if (document.mozFullScreen !== undefined) {
  11756. _this.isFullscreen = document.mozFullScreen;
  11757. }
  11758. else if (document.webkitIsFullScreen !== undefined) {
  11759. _this.isFullscreen = document.webkitIsFullScreen;
  11760. }
  11761. else if (document.msIsFullScreen !== undefined) {
  11762. _this.isFullscreen = document.msIsFullScreen;
  11763. }
  11764. // Pointer lock
  11765. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11766. canvas.requestPointerLock = canvas.requestPointerLock ||
  11767. canvas.msRequestPointerLock ||
  11768. canvas.mozRequestPointerLock ||
  11769. canvas.webkitRequestPointerLock;
  11770. if (canvas.requestPointerLock) {
  11771. canvas.requestPointerLock();
  11772. }
  11773. }
  11774. };
  11775. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11776. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11777. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11778. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11779. // Pointer lock
  11780. this._onPointerLockChange = function () {
  11781. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11782. document.webkitPointerLockElement === canvas ||
  11783. document.msPointerLockElement === canvas ||
  11784. document.pointerLockElement === canvas);
  11785. };
  11786. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11787. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11788. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11789. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11790. this._onVRDisplayPointerRestricted = function () {
  11791. if (canvas) {
  11792. canvas.requestPointerLock();
  11793. }
  11794. };
  11795. this._onVRDisplayPointerUnrestricted = function () {
  11796. document.exitPointerLock();
  11797. };
  11798. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11799. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11800. }
  11801. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11802. Engine.audioEngine = new BABYLON.AudioEngine();
  11803. }
  11804. // Prepare buffer pointers
  11805. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11806. this._currentBufferPointers[i] = new BufferPointer();
  11807. }
  11808. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11809. // Load WebVR Devices
  11810. if (options.autoEnableWebVR) {
  11811. this.initWebVR();
  11812. }
  11813. // Detect if we are running on a faulty buggy OS.
  11814. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11815. // Detect if we are running on a faulty buggy desktop OS.
  11816. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11817. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11818. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11819. }
  11820. Object.defineProperty(Engine, "LastCreatedEngine", {
  11821. /**
  11822. * Gets the latest created engine
  11823. */
  11824. get: function () {
  11825. if (Engine.Instances.length === 0) {
  11826. return null;
  11827. }
  11828. return Engine.Instances[Engine.Instances.length - 1];
  11829. },
  11830. enumerable: true,
  11831. configurable: true
  11832. });
  11833. Object.defineProperty(Engine, "LastCreatedScene", {
  11834. /**
  11835. * Gets the latest created scene
  11836. */
  11837. get: function () {
  11838. var lastCreatedEngine = Engine.LastCreatedEngine;
  11839. if (!lastCreatedEngine) {
  11840. return null;
  11841. }
  11842. if (lastCreatedEngine.scenes.length === 0) {
  11843. return null;
  11844. }
  11845. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. /**
  11851. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11852. * @param flag defines which part of the materials must be marked as dirty
  11853. * @param predicate defines a predicate used to filter which materials should be affected
  11854. */
  11855. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11856. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11857. var engine = Engine.Instances[engineIndex];
  11858. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11859. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11860. }
  11861. }
  11862. };
  11863. Object.defineProperty(Engine, "NEVER", {
  11864. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11865. get: function () {
  11866. return Engine._NEVER;
  11867. },
  11868. enumerable: true,
  11869. configurable: true
  11870. });
  11871. Object.defineProperty(Engine, "ALWAYS", {
  11872. /** 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 */
  11873. get: function () {
  11874. return Engine._ALWAYS;
  11875. },
  11876. enumerable: true,
  11877. configurable: true
  11878. });
  11879. Object.defineProperty(Engine, "LESS", {
  11880. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11881. get: function () {
  11882. return Engine._LESS;
  11883. },
  11884. enumerable: true,
  11885. configurable: true
  11886. });
  11887. Object.defineProperty(Engine, "EQUAL", {
  11888. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11889. get: function () {
  11890. return Engine._EQUAL;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(Engine, "LEQUAL", {
  11896. /** 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 */
  11897. get: function () {
  11898. return Engine._LEQUAL;
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(Engine, "GREATER", {
  11904. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11905. get: function () {
  11906. return Engine._GREATER;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(Engine, "GEQUAL", {
  11912. /** 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 */
  11913. get: function () {
  11914. return Engine._GEQUAL;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(Engine, "NOTEQUAL", {
  11920. /** 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 */
  11921. get: function () {
  11922. return Engine._NOTEQUAL;
  11923. },
  11924. enumerable: true,
  11925. configurable: true
  11926. });
  11927. Object.defineProperty(Engine, "KEEP", {
  11928. /** Passed to stencilOperation to specify that stencil value must be kept */
  11929. get: function () {
  11930. return Engine._KEEP;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Engine, "REPLACE", {
  11936. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11937. get: function () {
  11938. return Engine._REPLACE;
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(Engine, "INCR", {
  11944. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11945. get: function () {
  11946. return Engine._INCR;
  11947. },
  11948. enumerable: true,
  11949. configurable: true
  11950. });
  11951. Object.defineProperty(Engine, "DECR", {
  11952. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11953. get: function () {
  11954. return Engine._DECR;
  11955. },
  11956. enumerable: true,
  11957. configurable: true
  11958. });
  11959. Object.defineProperty(Engine, "INVERT", {
  11960. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11961. get: function () {
  11962. return Engine._INVERT;
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(Engine, "INCR_WRAP", {
  11968. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11969. get: function () {
  11970. return Engine._INCR_WRAP;
  11971. },
  11972. enumerable: true,
  11973. configurable: true
  11974. });
  11975. Object.defineProperty(Engine, "DECR_WRAP", {
  11976. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11977. get: function () {
  11978. return Engine._DECR_WRAP;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11984. // Alpha
  11985. /** Defines that alpha blending is disabled */
  11986. get: function () {
  11987. return Engine._ALPHA_DISABLE;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11993. /** Defines that alpha blending to SRC + DEST */
  11994. get: function () {
  11995. return Engine._ALPHA_ONEONE;
  11996. },
  11997. enumerable: true,
  11998. configurable: true
  11999. });
  12000. Object.defineProperty(Engine, "ALPHA_ADD", {
  12001. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  12002. get: function () {
  12003. return Engine._ALPHA_ADD;
  12004. },
  12005. enumerable: true,
  12006. configurable: true
  12007. });
  12008. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  12009. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  12010. get: function () {
  12011. return Engine._ALPHA_COMBINE;
  12012. },
  12013. enumerable: true,
  12014. configurable: true
  12015. });
  12016. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  12017. /** Defines that alpha blending to DEST - SRC * DEST */
  12018. get: function () {
  12019. return Engine._ALPHA_SUBTRACT;
  12020. },
  12021. enumerable: true,
  12022. configurable: true
  12023. });
  12024. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  12025. /** Defines that alpha blending to SRC * DEST */
  12026. get: function () {
  12027. return Engine._ALPHA_MULTIPLY;
  12028. },
  12029. enumerable: true,
  12030. configurable: true
  12031. });
  12032. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  12033. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  12034. get: function () {
  12035. return Engine._ALPHA_MAXIMIZED;
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  12041. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  12042. get: function () {
  12043. return Engine._ALPHA_PREMULTIPLIED;
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  12049. /**
  12050. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  12051. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  12052. */
  12053. get: function () {
  12054. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  12060. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  12061. get: function () {
  12062. return Engine._ALPHA_INTERPOLATE;
  12063. },
  12064. enumerable: true,
  12065. configurable: true
  12066. });
  12067. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  12068. /**
  12069. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  12070. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  12071. */
  12072. get: function () {
  12073. return Engine._ALPHA_SCREENMODE;
  12074. },
  12075. enumerable: true,
  12076. configurable: true
  12077. });
  12078. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  12079. // Delays
  12080. /** Defines that the ressource is not delayed*/
  12081. get: function () {
  12082. return Engine._DELAYLOADSTATE_NONE;
  12083. },
  12084. enumerable: true,
  12085. configurable: true
  12086. });
  12087. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  12088. /** Defines that the ressource was successfully delay loaded */
  12089. get: function () {
  12090. return Engine._DELAYLOADSTATE_LOADED;
  12091. },
  12092. enumerable: true,
  12093. configurable: true
  12094. });
  12095. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  12096. /** Defines that the ressource is currently delay loading */
  12097. get: function () {
  12098. return Engine._DELAYLOADSTATE_LOADING;
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  12104. /** Defines that the ressource is delayed and has not started loading */
  12105. get: function () {
  12106. return Engine._DELAYLOADSTATE_NOTLOADED;
  12107. },
  12108. enumerable: true,
  12109. configurable: true
  12110. });
  12111. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12112. /** ALPHA */
  12113. get: function () {
  12114. return Engine._TEXTUREFORMAT_ALPHA;
  12115. },
  12116. enumerable: true,
  12117. configurable: true
  12118. });
  12119. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12120. /** LUMINANCE */
  12121. get: function () {
  12122. return Engine._TEXTUREFORMAT_LUMINANCE;
  12123. },
  12124. enumerable: true,
  12125. configurable: true
  12126. });
  12127. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12128. /**
  12129. * R
  12130. */
  12131. get: function () {
  12132. return Engine._TEXTUREFORMAT_R;
  12133. },
  12134. enumerable: true,
  12135. configurable: true
  12136. });
  12137. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12138. /**
  12139. * RG
  12140. */
  12141. get: function () {
  12142. return Engine._TEXTUREFORMAT_RG;
  12143. },
  12144. enumerable: true,
  12145. configurable: true
  12146. });
  12147. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12148. /** LUMINANCE_ALPHA */
  12149. get: function () {
  12150. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12156. /** RGB */
  12157. get: function () {
  12158. return Engine._TEXTUREFORMAT_RGB;
  12159. },
  12160. enumerable: true,
  12161. configurable: true
  12162. });
  12163. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12164. /** RGBA */
  12165. get: function () {
  12166. return Engine._TEXTUREFORMAT_RGBA;
  12167. },
  12168. enumerable: true,
  12169. configurable: true
  12170. });
  12171. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12172. /** UNSIGNED_INT */
  12173. get: function () {
  12174. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12175. },
  12176. enumerable: true,
  12177. configurable: true
  12178. });
  12179. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12180. /** FLOAT */
  12181. get: function () {
  12182. return Engine._TEXTURETYPE_FLOAT;
  12183. },
  12184. enumerable: true,
  12185. configurable: true
  12186. });
  12187. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12188. /** HALF_FLOAT */
  12189. get: function () {
  12190. return Engine._TEXTURETYPE_HALF_FLOAT;
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12196. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12197. get: function () {
  12198. return Engine._SCALEMODE_FLOOR;
  12199. },
  12200. enumerable: true,
  12201. configurable: true
  12202. });
  12203. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12204. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12205. get: function () {
  12206. return Engine._SCALEMODE_NEAREST;
  12207. },
  12208. enumerable: true,
  12209. configurable: true
  12210. });
  12211. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12212. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12213. get: function () {
  12214. return Engine._SCALEMODE_CEILING;
  12215. },
  12216. enumerable: true,
  12217. configurable: true
  12218. });
  12219. Object.defineProperty(Engine, "Version", {
  12220. /**
  12221. * Returns the current version of the framework
  12222. */
  12223. get: function () {
  12224. return "3.3.0-alpha.9";
  12225. },
  12226. enumerable: true,
  12227. configurable: true
  12228. });
  12229. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12230. /**
  12231. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12232. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12233. */
  12234. get: function () {
  12235. return this._vrExclusivePointerMode;
  12236. },
  12237. enumerable: true,
  12238. configurable: true
  12239. });
  12240. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12241. /**
  12242. * Gets a boolean indicating that the engine supports uniform buffers
  12243. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12244. */
  12245. get: function () {
  12246. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12252. /**
  12253. * Gets a boolean indicating that only power of 2 textures are supported
  12254. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12255. */
  12256. get: function () {
  12257. return this._webGLVersion < 2 || this.forcePOTTextures;
  12258. },
  12259. enumerable: true,
  12260. configurable: true
  12261. });
  12262. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12263. /**
  12264. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12265. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12266. */
  12267. get: function () {
  12268. return this._doNotHandleContextLost;
  12269. },
  12270. set: function (value) {
  12271. this._doNotHandleContextLost = value;
  12272. },
  12273. enumerable: true,
  12274. configurable: true
  12275. });
  12276. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12277. /**
  12278. * Gets the performance monitor attached to this engine
  12279. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12280. */
  12281. get: function () {
  12282. return this._performanceMonitor;
  12283. },
  12284. enumerable: true,
  12285. configurable: true
  12286. });
  12287. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12288. /**
  12289. * Gets the list of texture formats supported
  12290. */
  12291. get: function () {
  12292. return this._texturesSupported;
  12293. },
  12294. enumerable: true,
  12295. configurable: true
  12296. });
  12297. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12298. /**
  12299. * Gets the list of texture formats in use
  12300. */
  12301. get: function () {
  12302. return this._textureFormatInUse;
  12303. },
  12304. enumerable: true,
  12305. configurable: true
  12306. });
  12307. Object.defineProperty(Engine.prototype, "currentViewport", {
  12308. /**
  12309. * Gets the current viewport
  12310. */
  12311. get: function () {
  12312. return this._cachedViewport;
  12313. },
  12314. enumerable: true,
  12315. configurable: true
  12316. });
  12317. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12318. /**
  12319. * Gets the default empty texture
  12320. */
  12321. get: function () {
  12322. if (!this._emptyTexture) {
  12323. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12324. }
  12325. return this._emptyTexture;
  12326. },
  12327. enumerable: true,
  12328. configurable: true
  12329. });
  12330. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12331. /**
  12332. * Gets the default empty 3D texture
  12333. */
  12334. get: function () {
  12335. if (!this._emptyTexture3D) {
  12336. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12337. }
  12338. return this._emptyTexture3D;
  12339. },
  12340. enumerable: true,
  12341. configurable: true
  12342. });
  12343. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12344. /**
  12345. * Gets the default empty cube texture
  12346. */
  12347. get: function () {
  12348. if (!this._emptyCubeTexture) {
  12349. var faceData = new Uint8Array(4);
  12350. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12351. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12352. }
  12353. return this._emptyCubeTexture;
  12354. },
  12355. enumerable: true,
  12356. configurable: true
  12357. });
  12358. Engine.prototype._rebuildInternalTextures = function () {
  12359. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12360. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12361. var internalTexture = currentState_1[_i];
  12362. internalTexture._rebuild();
  12363. }
  12364. };
  12365. Engine.prototype._rebuildEffects = function () {
  12366. for (var key in this._compiledEffects) {
  12367. var effect = this._compiledEffects[key];
  12368. effect._prepareEffect();
  12369. }
  12370. BABYLON.Effect.ResetCache();
  12371. };
  12372. Engine.prototype._rebuildBuffers = function () {
  12373. // Index / Vertex
  12374. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12375. var scene = _a[_i];
  12376. scene.resetCachedMaterial();
  12377. scene._rebuildGeometries();
  12378. scene._rebuildTextures();
  12379. }
  12380. // Uniforms
  12381. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12382. var uniformBuffer = _c[_b];
  12383. uniformBuffer._rebuild();
  12384. }
  12385. };
  12386. Engine.prototype._initGLContext = function () {
  12387. // Caps
  12388. this._caps = new EngineCapabilities();
  12389. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12390. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12391. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12392. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12393. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12394. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12395. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12396. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12397. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12398. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12399. // Infos
  12400. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12401. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12402. if (rendererInfo != null) {
  12403. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12404. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12405. }
  12406. if (!this._glVendor) {
  12407. this._glVendor = "Unknown vendor";
  12408. }
  12409. if (!this._glRenderer) {
  12410. this._glRenderer = "Unknown renderer";
  12411. }
  12412. // Constants
  12413. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12414. if (this._gl.RGBA16F !== 0x881A) {
  12415. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12416. }
  12417. if (this._gl.RGBA32F !== 0x8814) {
  12418. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12419. }
  12420. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12421. this._gl.DEPTH24_STENCIL8 = 35056;
  12422. }
  12423. // Extensions
  12424. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12425. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12426. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12427. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12428. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12429. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12430. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12431. 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');
  12432. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12433. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12434. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12435. this._caps.highPrecisionShaderSupported = true;
  12436. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12437. if (this._caps.timerQuery) {
  12438. if (this._webGLVersion === 1) {
  12439. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12440. }
  12441. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12442. }
  12443. // Checks if some of the format renders first to allow the use of webgl inspector.
  12444. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12445. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12446. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12447. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12448. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12449. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12450. if (this._webGLVersion > 1) {
  12451. this._gl.HALF_FLOAT_OES = 0x140B;
  12452. }
  12453. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12454. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12455. // Draw buffers
  12456. if (this._webGLVersion > 1) {
  12457. this._caps.drawBuffersExtension = true;
  12458. }
  12459. else {
  12460. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12461. if (drawBuffersExtension !== null) {
  12462. this._caps.drawBuffersExtension = true;
  12463. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12464. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12465. for (var i = 0; i < 16; i++) {
  12466. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12467. }
  12468. }
  12469. else {
  12470. this._caps.drawBuffersExtension = false;
  12471. }
  12472. }
  12473. // Depth Texture
  12474. if (this._webGLVersion > 1) {
  12475. this._caps.depthTextureExtension = true;
  12476. }
  12477. else {
  12478. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12479. if (depthTextureExtension != null) {
  12480. this._caps.depthTextureExtension = true;
  12481. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12482. }
  12483. }
  12484. // Vertex array object
  12485. if (this._webGLVersion > 1) {
  12486. this._caps.vertexArrayObject = true;
  12487. }
  12488. else {
  12489. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12490. if (vertexArrayObjectExtension != null) {
  12491. this._caps.vertexArrayObject = true;
  12492. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12493. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12494. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12495. }
  12496. else {
  12497. this._caps.vertexArrayObject = false;
  12498. }
  12499. }
  12500. // Instances count
  12501. if (this._webGLVersion > 1) {
  12502. this._caps.instancedArrays = true;
  12503. }
  12504. else {
  12505. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12506. if (instanceExtension != null) {
  12507. this._caps.instancedArrays = true;
  12508. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12509. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12510. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12511. }
  12512. else {
  12513. this._caps.instancedArrays = false;
  12514. }
  12515. }
  12516. // Intelligently add supported compressed formats in order to check for.
  12517. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12518. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12519. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12520. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12521. if (this._caps.astc)
  12522. this.texturesSupported.push('-astc.ktx');
  12523. if (this._caps.s3tc)
  12524. this.texturesSupported.push('-dxt.ktx');
  12525. if (this._caps.pvrtc)
  12526. this.texturesSupported.push('-pvrtc.ktx');
  12527. if (this._caps.etc2)
  12528. this.texturesSupported.push('-etc2.ktx');
  12529. if (this._caps.etc1)
  12530. this.texturesSupported.push('-etc1.ktx');
  12531. if (this._gl.getShaderPrecisionFormat) {
  12532. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12533. if (highp) {
  12534. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12535. }
  12536. }
  12537. // Depth buffer
  12538. this.setDepthBuffer(true);
  12539. this.setDepthFunctionToLessOrEqual();
  12540. this.setDepthWrite(true);
  12541. // Texture maps
  12542. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12543. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12544. this._nextFreeTextureSlots.push(slot);
  12545. }
  12546. };
  12547. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12548. /**
  12549. * Gets version of the current webGL context
  12550. */
  12551. get: function () {
  12552. return this._webGLVersion;
  12553. },
  12554. enumerable: true,
  12555. configurable: true
  12556. });
  12557. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12558. /**
  12559. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12560. */
  12561. get: function () {
  12562. return this._isStencilEnable;
  12563. },
  12564. enumerable: true,
  12565. configurable: true
  12566. });
  12567. Engine.prototype._prepareWorkingCanvas = function () {
  12568. if (this._workingCanvas) {
  12569. return;
  12570. }
  12571. this._workingCanvas = document.createElement("canvas");
  12572. var context = this._workingCanvas.getContext("2d");
  12573. if (context) {
  12574. this._workingContext = context;
  12575. }
  12576. };
  12577. /**
  12578. * Reset the texture cache to empty state
  12579. */
  12580. Engine.prototype.resetTextureCache = function () {
  12581. for (var key in this._boundTexturesCache) {
  12582. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12583. continue;
  12584. }
  12585. var boundTexture = this._boundTexturesCache[key];
  12586. if (boundTexture) {
  12587. this._removeDesignatedSlot(boundTexture);
  12588. }
  12589. this._boundTexturesCache[key] = null;
  12590. }
  12591. if (!this.disableTextureBindingOptimization) {
  12592. this._nextFreeTextureSlots = [];
  12593. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12594. this._nextFreeTextureSlots.push(slot);
  12595. }
  12596. }
  12597. this._currentTextureChannel = -1;
  12598. };
  12599. /**
  12600. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12601. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12602. * @returns true if engine is in deterministic lock step mode
  12603. */
  12604. Engine.prototype.isDeterministicLockStep = function () {
  12605. return this._deterministicLockstep;
  12606. };
  12607. /**
  12608. * Gets the max steps when engine is running in deterministic lock step
  12609. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12610. * @returns the max steps
  12611. */
  12612. Engine.prototype.getLockstepMaxSteps = function () {
  12613. return this._lockstepMaxSteps;
  12614. };
  12615. /**
  12616. * Gets an object containing information about the current webGL context
  12617. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12618. */
  12619. Engine.prototype.getGlInfo = function () {
  12620. return {
  12621. vendor: this._glVendor,
  12622. renderer: this._glRenderer,
  12623. version: this._glVersion
  12624. };
  12625. };
  12626. /**
  12627. * Gets current aspect ratio
  12628. * @param camera defines the camera to use to get the aspect ratio
  12629. * @param useScreen defines if screen size must be used (or the current render target if any)
  12630. * @returns a number defining the aspect ratio
  12631. */
  12632. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12633. if (useScreen === void 0) { useScreen = false; }
  12634. var viewport = camera.viewport;
  12635. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12636. };
  12637. /**
  12638. * Gets current screen aspect ratio
  12639. * @returns a number defining the aspect ratio
  12640. */
  12641. Engine.prototype.getScreenAspectRatio = function () {
  12642. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12643. };
  12644. /**
  12645. * Gets the current render width
  12646. * @param useScreen defines if screen size must be used (or the current render target if any)
  12647. * @returns a number defining the current render width
  12648. */
  12649. Engine.prototype.getRenderWidth = function (useScreen) {
  12650. if (useScreen === void 0) { useScreen = false; }
  12651. if (!useScreen && this._currentRenderTarget) {
  12652. return this._currentRenderTarget.width;
  12653. }
  12654. return this._gl.drawingBufferWidth;
  12655. };
  12656. /**
  12657. * Gets the current render height
  12658. * @param useScreen defines if screen size must be used (or the current render target if any)
  12659. * @returns a number defining the current render height
  12660. */
  12661. Engine.prototype.getRenderHeight = function (useScreen) {
  12662. if (useScreen === void 0) { useScreen = false; }
  12663. if (!useScreen && this._currentRenderTarget) {
  12664. return this._currentRenderTarget.height;
  12665. }
  12666. return this._gl.drawingBufferHeight;
  12667. };
  12668. /**
  12669. * Gets the HTML canvas attached with the current webGL context
  12670. * @returns a HTML canvas
  12671. */
  12672. Engine.prototype.getRenderingCanvas = function () {
  12673. return this._renderingCanvas;
  12674. };
  12675. /**
  12676. * Gets the client rect of the HTML canvas attached with the current webGL context
  12677. * @returns a client rectanglee
  12678. */
  12679. Engine.prototype.getRenderingCanvasClientRect = function () {
  12680. if (!this._renderingCanvas) {
  12681. return null;
  12682. }
  12683. return this._renderingCanvas.getBoundingClientRect();
  12684. };
  12685. /**
  12686. * Defines the hardware scaling level.
  12687. * By default the hardware scaling level is computed from the window device ratio.
  12688. * 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.
  12689. * @param level defines the level to use
  12690. */
  12691. Engine.prototype.setHardwareScalingLevel = function (level) {
  12692. this._hardwareScalingLevel = level;
  12693. this.resize();
  12694. };
  12695. /**
  12696. * Gets the current hardware scaling level.
  12697. * By default the hardware scaling level is computed from the window device ratio.
  12698. * 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.
  12699. * @returns a number indicating the current hardware scaling level
  12700. */
  12701. Engine.prototype.getHardwareScalingLevel = function () {
  12702. return this._hardwareScalingLevel;
  12703. };
  12704. /**
  12705. * Gets the list of loaded textures
  12706. * @returns an array containing all loaded textures
  12707. */
  12708. Engine.prototype.getLoadedTexturesCache = function () {
  12709. return this._internalTexturesCache;
  12710. };
  12711. /**
  12712. * Gets the object containing all engine capabilities
  12713. * @returns the EngineCapabilities object
  12714. */
  12715. Engine.prototype.getCaps = function () {
  12716. return this._caps;
  12717. };
  12718. Object.defineProperty(Engine.prototype, "drawCalls", {
  12719. /** @hidden */
  12720. get: function () {
  12721. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12722. return 0;
  12723. },
  12724. enumerable: true,
  12725. configurable: true
  12726. });
  12727. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12728. /** @hidden */
  12729. get: function () {
  12730. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12731. return null;
  12732. },
  12733. enumerable: true,
  12734. configurable: true
  12735. });
  12736. /**
  12737. * Gets the current depth function
  12738. * @returns a number defining the depth function
  12739. */
  12740. Engine.prototype.getDepthFunction = function () {
  12741. return this._depthCullingState.depthFunc;
  12742. };
  12743. /**
  12744. * Sets the current depth function
  12745. * @param depthFunc defines the function to use
  12746. */
  12747. Engine.prototype.setDepthFunction = function (depthFunc) {
  12748. this._depthCullingState.depthFunc = depthFunc;
  12749. };
  12750. /**
  12751. * Sets the current depth function to GREATER
  12752. */
  12753. Engine.prototype.setDepthFunctionToGreater = function () {
  12754. this._depthCullingState.depthFunc = this._gl.GREATER;
  12755. };
  12756. /**
  12757. * Sets the current depth function to GEQUAL
  12758. */
  12759. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12760. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12761. };
  12762. /**
  12763. * Sets the current depth function to LESS
  12764. */
  12765. Engine.prototype.setDepthFunctionToLess = function () {
  12766. this._depthCullingState.depthFunc = this._gl.LESS;
  12767. };
  12768. /**
  12769. * Sets the current depth function to LEQUAL
  12770. */
  12771. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12772. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12773. };
  12774. /**
  12775. * Gets a boolean indicating if stencil buffer is enabled
  12776. * @returns the current stencil buffer state
  12777. */
  12778. Engine.prototype.getStencilBuffer = function () {
  12779. return this._stencilState.stencilTest;
  12780. };
  12781. /**
  12782. * Enable or disable the stencil buffer
  12783. * @param enable defines if the stencil buffer must be enabled or disabled
  12784. */
  12785. Engine.prototype.setStencilBuffer = function (enable) {
  12786. this._stencilState.stencilTest = enable;
  12787. };
  12788. /**
  12789. * Gets the current stencil mask
  12790. * @returns a number defining the new stencil mask to use
  12791. */
  12792. Engine.prototype.getStencilMask = function () {
  12793. return this._stencilState.stencilMask;
  12794. };
  12795. /**
  12796. * Sets the current stencil mask
  12797. * @param mask defines the new stencil mask to use
  12798. */
  12799. Engine.prototype.setStencilMask = function (mask) {
  12800. this._stencilState.stencilMask = mask;
  12801. };
  12802. /**
  12803. * Gets the current stencil function
  12804. * @returns a number defining the stencil function to use
  12805. */
  12806. Engine.prototype.getStencilFunction = function () {
  12807. return this._stencilState.stencilFunc;
  12808. };
  12809. /**
  12810. * Gets the current stencil reference value
  12811. * @returns a number defining the stencil reference value to use
  12812. */
  12813. Engine.prototype.getStencilFunctionReference = function () {
  12814. return this._stencilState.stencilFuncRef;
  12815. };
  12816. /**
  12817. * Gets the current stencil mask
  12818. * @returns a number defining the stencil mask to use
  12819. */
  12820. Engine.prototype.getStencilFunctionMask = function () {
  12821. return this._stencilState.stencilFuncMask;
  12822. };
  12823. /**
  12824. * Sets the current stencil function
  12825. * @param stencilFunc defines the new stencil function to use
  12826. */
  12827. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12828. this._stencilState.stencilFunc = stencilFunc;
  12829. };
  12830. /**
  12831. * Sets the current stencil reference
  12832. * @param reference defines the new stencil reference to use
  12833. */
  12834. Engine.prototype.setStencilFunctionReference = function (reference) {
  12835. this._stencilState.stencilFuncRef = reference;
  12836. };
  12837. /**
  12838. * Sets the current stencil mask
  12839. * @param mask defines the new stencil mask to use
  12840. */
  12841. Engine.prototype.setStencilFunctionMask = function (mask) {
  12842. this._stencilState.stencilFuncMask = mask;
  12843. };
  12844. /**
  12845. * Gets the current stencil operation when stencil fails
  12846. * @returns a number defining stencil operation to use when stencil fails
  12847. */
  12848. Engine.prototype.getStencilOperationFail = function () {
  12849. return this._stencilState.stencilOpStencilFail;
  12850. };
  12851. /**
  12852. * Gets the current stencil operation when depth fails
  12853. * @returns a number defining stencil operation to use when depth fails
  12854. */
  12855. Engine.prototype.getStencilOperationDepthFail = function () {
  12856. return this._stencilState.stencilOpDepthFail;
  12857. };
  12858. /**
  12859. * Gets the current stencil operation when stencil passes
  12860. * @returns a number defining stencil operation to use when stencil passes
  12861. */
  12862. Engine.prototype.getStencilOperationPass = function () {
  12863. return this._stencilState.stencilOpStencilDepthPass;
  12864. };
  12865. /**
  12866. * Sets the stencil operation to use when stencil fails
  12867. * @param operation defines the stencil operation to use when stencil fails
  12868. */
  12869. Engine.prototype.setStencilOperationFail = function (operation) {
  12870. this._stencilState.stencilOpStencilFail = operation;
  12871. };
  12872. /**
  12873. * Sets the stencil operation to use when depth fails
  12874. * @param operation defines the stencil operation to use when depth fails
  12875. */
  12876. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12877. this._stencilState.stencilOpDepthFail = operation;
  12878. };
  12879. /**
  12880. * Sets the stencil operation to use when stencil passes
  12881. * @param operation defines the stencil operation to use when stencil passes
  12882. */
  12883. Engine.prototype.setStencilOperationPass = function (operation) {
  12884. this._stencilState.stencilOpStencilDepthPass = operation;
  12885. };
  12886. /**
  12887. * Sets a boolean indicating if the dithering state is enabled or disabled
  12888. * @param value defines the dithering state
  12889. */
  12890. Engine.prototype.setDitheringState = function (value) {
  12891. if (value) {
  12892. this._gl.enable(this._gl.DITHER);
  12893. }
  12894. else {
  12895. this._gl.disable(this._gl.DITHER);
  12896. }
  12897. };
  12898. /**
  12899. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12900. * @param value defines the rasterizer state
  12901. */
  12902. Engine.prototype.setRasterizerState = function (value) {
  12903. if (value) {
  12904. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12905. }
  12906. else {
  12907. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12908. }
  12909. };
  12910. /**
  12911. * stop executing a render loop function and remove it from the execution array
  12912. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12913. */
  12914. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12915. if (!renderFunction) {
  12916. this._activeRenderLoops = [];
  12917. return;
  12918. }
  12919. var index = this._activeRenderLoops.indexOf(renderFunction);
  12920. if (index >= 0) {
  12921. this._activeRenderLoops.splice(index, 1);
  12922. }
  12923. };
  12924. /** @hidden */
  12925. Engine.prototype._renderLoop = function () {
  12926. if (!this._contextWasLost) {
  12927. var shouldRender = true;
  12928. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12929. shouldRender = false;
  12930. }
  12931. if (shouldRender) {
  12932. // Start new frame
  12933. this.beginFrame();
  12934. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12935. var renderFunction = this._activeRenderLoops[index];
  12936. renderFunction();
  12937. }
  12938. // Present
  12939. this.endFrame();
  12940. }
  12941. }
  12942. if (this._activeRenderLoops.length > 0) {
  12943. // Register new frame
  12944. var requester = null;
  12945. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12946. requester = this._vrDisplay;
  12947. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12948. }
  12949. else {
  12950. this._renderingQueueLaunched = false;
  12951. }
  12952. };
  12953. /**
  12954. * Register and execute a render loop. The engine can have more than one render function
  12955. * @param renderFunction defines the function to continuously execute
  12956. */
  12957. Engine.prototype.runRenderLoop = function (renderFunction) {
  12958. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12959. return;
  12960. }
  12961. this._activeRenderLoops.push(renderFunction);
  12962. if (!this._renderingQueueLaunched) {
  12963. this._renderingQueueLaunched = true;
  12964. this._bindedRenderFunction = this._renderLoop.bind(this);
  12965. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12966. }
  12967. };
  12968. /**
  12969. * Toggle full screen mode
  12970. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12971. * @param options defines an option object to be sent to the requestFullscreen function
  12972. */
  12973. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12974. if (this.isFullscreen) {
  12975. BABYLON.Tools.ExitFullscreen();
  12976. }
  12977. else {
  12978. this._pointerLockRequested = requestPointerLock;
  12979. if (this._renderingCanvas) {
  12980. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12981. }
  12982. }
  12983. };
  12984. /**
  12985. * Clear the current render buffer or the current render target (if any is set up)
  12986. * @param color defines the color to use
  12987. * @param backBuffer defines if the back buffer must be cleared
  12988. * @param depth defines if the depth buffer must be cleared
  12989. * @param stencil defines if the stencil buffer must be cleared
  12990. */
  12991. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12992. if (stencil === void 0) { stencil = false; }
  12993. this.applyStates();
  12994. var mode = 0;
  12995. if (backBuffer && color) {
  12996. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12997. mode |= this._gl.COLOR_BUFFER_BIT;
  12998. }
  12999. if (depth) {
  13000. this._gl.clearDepth(1.0);
  13001. mode |= this._gl.DEPTH_BUFFER_BIT;
  13002. }
  13003. if (stencil) {
  13004. this._gl.clearStencil(0);
  13005. mode |= this._gl.STENCIL_BUFFER_BIT;
  13006. }
  13007. this._gl.clear(mode);
  13008. };
  13009. /**
  13010. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13011. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13012. * @param y defines the y-coordinate of the corner of the clear rectangle
  13013. * @param width defines the width of the clear rectangle
  13014. * @param height defines the height of the clear rectangle
  13015. * @param clearColor defines the clear color
  13016. */
  13017. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13018. var gl = this._gl;
  13019. // Save state
  13020. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13021. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13022. // Change state
  13023. gl.enable(gl.SCISSOR_TEST);
  13024. gl.scissor(x, y, width, height);
  13025. // Clear
  13026. this.clear(clearColor, true, true, true);
  13027. // Restore state
  13028. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13029. if (curScissor === true) {
  13030. gl.enable(gl.SCISSOR_TEST);
  13031. }
  13032. else {
  13033. gl.disable(gl.SCISSOR_TEST);
  13034. }
  13035. };
  13036. /** @hidden */
  13037. Engine.prototype._viewport = function (x, y, width, height) {
  13038. if (x !== this._viewportCached.x ||
  13039. y !== this._viewportCached.y ||
  13040. width !== this._viewportCached.z ||
  13041. height !== this._viewportCached.w) {
  13042. this._viewportCached.x = x;
  13043. this._viewportCached.y = y;
  13044. this._viewportCached.z = width;
  13045. this._viewportCached.w = height;
  13046. this._gl.viewport(x, y, width, height);
  13047. }
  13048. };
  13049. /**
  13050. * Set the WebGL's viewport
  13051. * @param viewport defines the viewport element to be used
  13052. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13053. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13054. */
  13055. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13056. var width = requiredWidth || this.getRenderWidth();
  13057. var height = requiredHeight || this.getRenderHeight();
  13058. var x = viewport.x || 0;
  13059. var y = viewport.y || 0;
  13060. this._cachedViewport = viewport;
  13061. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13062. };
  13063. /**
  13064. * Directly set the WebGL Viewport
  13065. * @param x defines the x coordinate of the viewport (in screen space)
  13066. * @param y defines the y coordinate of the viewport (in screen space)
  13067. * @param width defines the width of the viewport (in screen space)
  13068. * @param height defines the height of the viewport (in screen space)
  13069. * @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
  13070. */
  13071. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13072. var currentViewport = this._cachedViewport;
  13073. this._cachedViewport = null;
  13074. this._viewport(x, y, width, height);
  13075. return currentViewport;
  13076. };
  13077. /**
  13078. * Begin a new frame
  13079. */
  13080. Engine.prototype.beginFrame = function () {
  13081. this.onBeginFrameObservable.notifyObservers(this);
  13082. this._measureFps();
  13083. };
  13084. /**
  13085. * Enf the current frame
  13086. */
  13087. Engine.prototype.endFrame = function () {
  13088. // Force a flush in case we are using a bad OS.
  13089. if (this._badOS) {
  13090. this.flushFramebuffer();
  13091. }
  13092. // Submit frame to the vr device, if enabled
  13093. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13094. // TODO: We should only submit the frame if we read frameData successfully.
  13095. this._vrDisplay.submitFrame();
  13096. }
  13097. this.onEndFrameObservable.notifyObservers(this);
  13098. };
  13099. /**
  13100. * Resize the view according to the canvas' size
  13101. */
  13102. Engine.prototype.resize = function () {
  13103. // We're not resizing the size of the canvas while in VR mode & presenting
  13104. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13105. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13106. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13107. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13108. }
  13109. };
  13110. /**
  13111. * Force a specific size of the canvas
  13112. * @param width defines the new canvas' width
  13113. * @param height defines the new canvas' height
  13114. */
  13115. Engine.prototype.setSize = function (width, height) {
  13116. if (!this._renderingCanvas) {
  13117. return;
  13118. }
  13119. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13120. return;
  13121. }
  13122. this._renderingCanvas.width = width;
  13123. this._renderingCanvas.height = height;
  13124. for (var index = 0; index < this.scenes.length; index++) {
  13125. var scene = this.scenes[index];
  13126. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13127. var cam = scene.cameras[camIndex];
  13128. cam._currentRenderId = 0;
  13129. }
  13130. }
  13131. if (this.onResizeObservable.hasObservers) {
  13132. this.onResizeObservable.notifyObservers(this);
  13133. }
  13134. };
  13135. // WebVR functions
  13136. /**
  13137. * Gets a boolean indicating if a webVR device was detected
  13138. * @returns true if a webVR device was detected
  13139. */
  13140. Engine.prototype.isVRDevicePresent = function () {
  13141. return !!this._vrDisplay;
  13142. };
  13143. /**
  13144. * Gets the current webVR device
  13145. * @returns the current webVR device (or null)
  13146. */
  13147. Engine.prototype.getVRDevice = function () {
  13148. return this._vrDisplay;
  13149. };
  13150. /**
  13151. * Initializes a webVR display and starts listening to display change events
  13152. * The onVRDisplayChangedObservable will be notified upon these changes
  13153. * @returns The onVRDisplayChangedObservable
  13154. */
  13155. Engine.prototype.initWebVR = function () {
  13156. this.initWebVRAsync();
  13157. return this.onVRDisplayChangedObservable;
  13158. };
  13159. /**
  13160. * Initializes a webVR display and starts listening to display change events
  13161. * The onVRDisplayChangedObservable will be notified upon these changes
  13162. * @returns A promise containing a VRDisplay and if vr is supported
  13163. */
  13164. Engine.prototype.initWebVRAsync = function () {
  13165. var _this = this;
  13166. var notifyObservers = function () {
  13167. var eventArgs = {
  13168. vrDisplay: _this._vrDisplay,
  13169. vrSupported: _this._vrSupported
  13170. };
  13171. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13172. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13173. };
  13174. if (!this._onVrDisplayConnect) {
  13175. this._onVrDisplayConnect = function (event) {
  13176. _this._vrDisplay = event.display;
  13177. notifyObservers();
  13178. };
  13179. this._onVrDisplayDisconnect = function () {
  13180. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13181. _this._vrDisplay = undefined;
  13182. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13183. notifyObservers();
  13184. };
  13185. this._onVrDisplayPresentChange = function () {
  13186. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13187. };
  13188. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13189. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13190. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13191. }
  13192. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13193. this._webVRInitPromise.then(notifyObservers);
  13194. return this._webVRInitPromise;
  13195. };
  13196. /**
  13197. * Call this function to switch to webVR mode
  13198. * Will do nothing if webVR is not supported or if there is no webVR device
  13199. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13200. */
  13201. Engine.prototype.enableVR = function () {
  13202. var _this = this;
  13203. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13204. var onResolved = function () {
  13205. _this.onVRRequestPresentComplete.notifyObservers(true);
  13206. _this._onVRFullScreenTriggered();
  13207. };
  13208. var onRejected = function () {
  13209. _this.onVRRequestPresentComplete.notifyObservers(false);
  13210. };
  13211. this.onVRRequestPresentStart.notifyObservers(this);
  13212. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13213. }
  13214. };
  13215. /**
  13216. * Call this function to leave webVR mode
  13217. * Will do nothing if webVR is not supported or if there is no webVR device
  13218. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13219. */
  13220. Engine.prototype.disableVR = function () {
  13221. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13222. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13223. }
  13224. };
  13225. Engine.prototype._getVRDisplaysAsync = function () {
  13226. var _this = this;
  13227. return new Promise(function (res, rej) {
  13228. if (navigator.getVRDisplays) {
  13229. navigator.getVRDisplays().then(function (devices) {
  13230. _this._vrSupported = true;
  13231. // note that devices may actually be an empty array. This is fine;
  13232. // we expect this._vrDisplay to be undefined in this case.
  13233. _this._vrDisplay = devices[0];
  13234. res({
  13235. vrDisplay: _this._vrDisplay,
  13236. vrSupported: _this._vrSupported
  13237. });
  13238. });
  13239. }
  13240. else {
  13241. _this._vrDisplay = undefined;
  13242. _this._vrSupported = false;
  13243. res({
  13244. vrDisplay: _this._vrDisplay,
  13245. vrSupported: _this._vrSupported
  13246. });
  13247. }
  13248. });
  13249. };
  13250. /**
  13251. * Binds the frame buffer to the specified texture.
  13252. * @param texture The texture to render to or null for the default canvas
  13253. * @param faceIndex The face of the texture to render to in case of cube texture
  13254. * @param requiredWidth The width of the target to render to
  13255. * @param requiredHeight The height of the target to render to
  13256. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13257. * @param depthStencilTexture The depth stencil texture to use to render
  13258. * @param lodLevel defines le lod level to bind to the frame buffer
  13259. */
  13260. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13261. if (lodLevel === void 0) { lodLevel = 0; }
  13262. if (this._currentRenderTarget) {
  13263. this.unBindFramebuffer(this._currentRenderTarget);
  13264. }
  13265. this._currentRenderTarget = texture;
  13266. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13267. var gl = this._gl;
  13268. if (texture.isCube) {
  13269. if (faceIndex === undefined) {
  13270. faceIndex = 0;
  13271. }
  13272. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13273. if (depthStencilTexture) {
  13274. if (depthStencilTexture._generateStencilBuffer) {
  13275. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13276. }
  13277. else {
  13278. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13279. }
  13280. }
  13281. }
  13282. if (this._cachedViewport && !forceFullscreenViewport) {
  13283. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13284. }
  13285. else {
  13286. if (!requiredWidth) {
  13287. requiredWidth = texture.width;
  13288. if (lodLevel) {
  13289. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13290. }
  13291. }
  13292. if (!requiredHeight) {
  13293. requiredHeight = texture.height;
  13294. if (lodLevel) {
  13295. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13296. }
  13297. }
  13298. this._viewport(0, 0, requiredWidth, requiredHeight);
  13299. }
  13300. this.wipeCaches();
  13301. };
  13302. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13303. if (this._currentFramebuffer !== framebuffer) {
  13304. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13305. this._currentFramebuffer = framebuffer;
  13306. }
  13307. };
  13308. /**
  13309. * Unbind the current render target texture from the webGL context
  13310. * @param texture defines the render target texture to unbind
  13311. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13312. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13313. */
  13314. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13315. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13316. this._currentRenderTarget = null;
  13317. // If MSAA, we need to bitblt back to main texture
  13318. var gl = this._gl;
  13319. if (texture._MSAAFramebuffer) {
  13320. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13321. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13322. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13323. }
  13324. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13325. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13326. gl.generateMipmap(gl.TEXTURE_2D);
  13327. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13328. }
  13329. if (onBeforeUnbind) {
  13330. if (texture._MSAAFramebuffer) {
  13331. // Bind the correct framebuffer
  13332. this.bindUnboundFramebuffer(texture._framebuffer);
  13333. }
  13334. onBeforeUnbind();
  13335. }
  13336. this.bindUnboundFramebuffer(null);
  13337. };
  13338. /**
  13339. * Unbind a list of render target textures from the webGL context
  13340. * This is used only when drawBuffer extension or webGL2 are active
  13341. * @param textures defines the render target textures to unbind
  13342. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13343. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13344. */
  13345. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13346. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13347. this._currentRenderTarget = null;
  13348. // If MSAA, we need to bitblt back to main texture
  13349. var gl = this._gl;
  13350. if (textures[0]._MSAAFramebuffer) {
  13351. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13352. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13353. var attachments = textures[0]._attachments;
  13354. if (!attachments) {
  13355. attachments = new Array(textures.length);
  13356. textures[0]._attachments = attachments;
  13357. }
  13358. for (var i = 0; i < textures.length; i++) {
  13359. var texture = textures[i];
  13360. for (var j = 0; j < attachments.length; j++) {
  13361. attachments[j] = gl.NONE;
  13362. }
  13363. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13364. gl.readBuffer(attachments[i]);
  13365. gl.drawBuffers(attachments);
  13366. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13367. }
  13368. for (var i = 0; i < attachments.length; i++) {
  13369. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13370. }
  13371. gl.drawBuffers(attachments);
  13372. }
  13373. for (var i = 0; i < textures.length; i++) {
  13374. var texture = textures[i];
  13375. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13376. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13377. gl.generateMipmap(gl.TEXTURE_2D);
  13378. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13379. }
  13380. }
  13381. if (onBeforeUnbind) {
  13382. if (textures[0]._MSAAFramebuffer) {
  13383. // Bind the correct framebuffer
  13384. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13385. }
  13386. onBeforeUnbind();
  13387. }
  13388. this.bindUnboundFramebuffer(null);
  13389. };
  13390. /**
  13391. * Force the mipmap generation for the given render target texture
  13392. * @param texture defines the render target texture to use
  13393. */
  13394. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13395. if (texture.generateMipMaps) {
  13396. var gl = this._gl;
  13397. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13398. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13399. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13400. }
  13401. };
  13402. /**
  13403. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13404. */
  13405. Engine.prototype.flushFramebuffer = function () {
  13406. this._gl.flush();
  13407. };
  13408. /**
  13409. * Unbind the current render target and bind the default framebuffer
  13410. */
  13411. Engine.prototype.restoreDefaultFramebuffer = function () {
  13412. if (this._currentRenderTarget) {
  13413. this.unBindFramebuffer(this._currentRenderTarget);
  13414. }
  13415. else {
  13416. this.bindUnboundFramebuffer(null);
  13417. }
  13418. if (this._cachedViewport) {
  13419. this.setViewport(this._cachedViewport);
  13420. }
  13421. this.wipeCaches();
  13422. };
  13423. // UBOs
  13424. /**
  13425. * Create an uniform buffer
  13426. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13427. * @param elements defines the content of the uniform buffer
  13428. * @returns the webGL uniform buffer
  13429. */
  13430. Engine.prototype.createUniformBuffer = function (elements) {
  13431. var ubo = this._gl.createBuffer();
  13432. if (!ubo) {
  13433. throw new Error("Unable to create uniform buffer");
  13434. }
  13435. this.bindUniformBuffer(ubo);
  13436. if (elements instanceof Float32Array) {
  13437. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13438. }
  13439. else {
  13440. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13441. }
  13442. this.bindUniformBuffer(null);
  13443. ubo.references = 1;
  13444. return ubo;
  13445. };
  13446. /**
  13447. * Create a dynamic uniform buffer
  13448. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13449. * @param elements defines the content of the uniform buffer
  13450. * @returns the webGL uniform buffer
  13451. */
  13452. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13453. var ubo = this._gl.createBuffer();
  13454. if (!ubo) {
  13455. throw new Error("Unable to create dynamic uniform buffer");
  13456. }
  13457. this.bindUniformBuffer(ubo);
  13458. if (elements instanceof Float32Array) {
  13459. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13460. }
  13461. else {
  13462. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13463. }
  13464. this.bindUniformBuffer(null);
  13465. ubo.references = 1;
  13466. return ubo;
  13467. };
  13468. /**
  13469. * Update an existing uniform buffer
  13470. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13471. * @param uniformBuffer defines the target uniform buffer
  13472. * @param elements defines the content to update
  13473. * @param offset defines the offset in the uniform buffer where update should start
  13474. * @param count defines the size of the data to update
  13475. */
  13476. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13477. this.bindUniformBuffer(uniformBuffer);
  13478. if (offset === undefined) {
  13479. offset = 0;
  13480. }
  13481. if (count === undefined) {
  13482. if (elements instanceof Float32Array) {
  13483. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13484. }
  13485. else {
  13486. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13487. }
  13488. }
  13489. else {
  13490. if (elements instanceof Float32Array) {
  13491. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13492. }
  13493. else {
  13494. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13495. }
  13496. }
  13497. this.bindUniformBuffer(null);
  13498. };
  13499. // VBOs
  13500. Engine.prototype._resetVertexBufferBinding = function () {
  13501. this.bindArrayBuffer(null);
  13502. this._cachedVertexBuffers = null;
  13503. };
  13504. /**
  13505. * Creates a vertex buffer
  13506. * @param data the data for the vertex buffer
  13507. * @returns the new WebGL static buffer
  13508. */
  13509. Engine.prototype.createVertexBuffer = function (data) {
  13510. var vbo = this._gl.createBuffer();
  13511. if (!vbo) {
  13512. throw new Error("Unable to create vertex buffer");
  13513. }
  13514. this.bindArrayBuffer(vbo);
  13515. if (data instanceof Array) {
  13516. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13517. }
  13518. else {
  13519. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13520. }
  13521. this._resetVertexBufferBinding();
  13522. vbo.references = 1;
  13523. return vbo;
  13524. };
  13525. /**
  13526. * Creates a dynamic vertex buffer
  13527. * @param data the data for the dynamic vertex buffer
  13528. * @returns the new WebGL dynamic buffer
  13529. */
  13530. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13531. var vbo = this._gl.createBuffer();
  13532. if (!vbo) {
  13533. throw new Error("Unable to create dynamic vertex buffer");
  13534. }
  13535. this.bindArrayBuffer(vbo);
  13536. if (data instanceof Array) {
  13537. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13538. }
  13539. else {
  13540. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13541. }
  13542. this._resetVertexBufferBinding();
  13543. vbo.references = 1;
  13544. return vbo;
  13545. };
  13546. /**
  13547. * Update a dynamic index buffer
  13548. * @param indexBuffer defines the target index buffer
  13549. * @param indices defines the data to update
  13550. * @param offset defines the offset in the target index buffer where update should start
  13551. */
  13552. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13553. if (offset === void 0) { offset = 0; }
  13554. // Force cache update
  13555. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13556. this.bindIndexBuffer(indexBuffer);
  13557. var arrayBuffer;
  13558. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13559. arrayBuffer = indices;
  13560. }
  13561. else {
  13562. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13563. }
  13564. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13565. this._resetIndexBufferBinding();
  13566. };
  13567. /**
  13568. * Updates a dynamic vertex buffer.
  13569. * @param vertexBuffer the vertex buffer to update
  13570. * @param data the data used to update the vertex buffer
  13571. * @param byteOffset the byte offset of the data
  13572. * @param byteLength the byte length of the data
  13573. */
  13574. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13575. this.bindArrayBuffer(vertexBuffer);
  13576. if (byteOffset === undefined) {
  13577. byteOffset = 0;
  13578. }
  13579. if (byteLength === undefined) {
  13580. if (data instanceof Array) {
  13581. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13582. }
  13583. else {
  13584. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13585. }
  13586. }
  13587. else {
  13588. if (data instanceof Array) {
  13589. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13590. }
  13591. else {
  13592. if (data instanceof ArrayBuffer) {
  13593. data = new Uint8Array(data, byteOffset, byteLength);
  13594. }
  13595. else {
  13596. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13597. }
  13598. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13599. }
  13600. }
  13601. this._resetVertexBufferBinding();
  13602. };
  13603. Engine.prototype._resetIndexBufferBinding = function () {
  13604. this.bindIndexBuffer(null);
  13605. this._cachedIndexBuffer = null;
  13606. };
  13607. /**
  13608. * Creates a new index buffer
  13609. * @param indices defines the content of the index buffer
  13610. * @param updatable defines if the index buffer must be updatable
  13611. * @returns a new webGL buffer
  13612. */
  13613. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13614. var vbo = this._gl.createBuffer();
  13615. if (!vbo) {
  13616. throw new Error("Unable to create index buffer");
  13617. }
  13618. this.bindIndexBuffer(vbo);
  13619. // Check for 32 bits indices
  13620. var arrayBuffer;
  13621. var need32Bits = false;
  13622. if (indices instanceof Uint16Array) {
  13623. arrayBuffer = indices;
  13624. }
  13625. else {
  13626. //check 32 bit support
  13627. if (this._caps.uintIndices) {
  13628. if (indices instanceof Uint32Array) {
  13629. arrayBuffer = indices;
  13630. need32Bits = true;
  13631. }
  13632. else {
  13633. //number[] or Int32Array, check if 32 bit is necessary
  13634. for (var index = 0; index < indices.length; index++) {
  13635. if (indices[index] > 65535) {
  13636. need32Bits = true;
  13637. break;
  13638. }
  13639. }
  13640. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13641. }
  13642. }
  13643. else {
  13644. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13645. arrayBuffer = new Uint16Array(indices);
  13646. }
  13647. }
  13648. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13649. this._resetIndexBufferBinding();
  13650. vbo.references = 1;
  13651. vbo.is32Bits = need32Bits;
  13652. return vbo;
  13653. };
  13654. /**
  13655. * Bind a webGL buffer to the webGL context
  13656. * @param buffer defines the buffer to bind
  13657. */
  13658. Engine.prototype.bindArrayBuffer = function (buffer) {
  13659. if (!this._vaoRecordInProgress) {
  13660. this._unbindVertexArrayObject();
  13661. }
  13662. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13663. };
  13664. /**
  13665. * Bind an uniform buffer to the current webGL context
  13666. * @param buffer defines the buffer to bind
  13667. */
  13668. Engine.prototype.bindUniformBuffer = function (buffer) {
  13669. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13670. };
  13671. /**
  13672. * Bind a buffer to the current webGL context at a given location
  13673. * @param buffer defines the buffer to bind
  13674. * @param location defines the index where to bind the buffer
  13675. */
  13676. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13677. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13678. };
  13679. /**
  13680. * Bind a specific block at a given index in a specific shader program
  13681. * @param shaderProgram defines the shader program
  13682. * @param blockName defines the block name
  13683. * @param index defines the index where to bind the block
  13684. */
  13685. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13686. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13687. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13688. };
  13689. ;
  13690. Engine.prototype.bindIndexBuffer = function (buffer) {
  13691. if (!this._vaoRecordInProgress) {
  13692. this._unbindVertexArrayObject();
  13693. }
  13694. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13695. };
  13696. Engine.prototype.bindBuffer = function (buffer, target) {
  13697. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13698. this._gl.bindBuffer(target, buffer);
  13699. this._currentBoundBuffer[target] = buffer;
  13700. }
  13701. };
  13702. /**
  13703. * update the bound buffer with the given data
  13704. * @param data defines the data to update
  13705. */
  13706. Engine.prototype.updateArrayBuffer = function (data) {
  13707. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13708. };
  13709. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13710. var pointer = this._currentBufferPointers[indx];
  13711. var changed = false;
  13712. if (!pointer.active) {
  13713. changed = true;
  13714. pointer.active = true;
  13715. pointer.index = indx;
  13716. pointer.size = size;
  13717. pointer.type = type;
  13718. pointer.normalized = normalized;
  13719. pointer.stride = stride;
  13720. pointer.offset = offset;
  13721. pointer.buffer = buffer;
  13722. }
  13723. else {
  13724. if (pointer.buffer !== buffer) {
  13725. pointer.buffer = buffer;
  13726. changed = true;
  13727. }
  13728. if (pointer.size !== size) {
  13729. pointer.size = size;
  13730. changed = true;
  13731. }
  13732. if (pointer.type !== type) {
  13733. pointer.type = type;
  13734. changed = true;
  13735. }
  13736. if (pointer.normalized !== normalized) {
  13737. pointer.normalized = normalized;
  13738. changed = true;
  13739. }
  13740. if (pointer.stride !== stride) {
  13741. pointer.stride = stride;
  13742. changed = true;
  13743. }
  13744. if (pointer.offset !== offset) {
  13745. pointer.offset = offset;
  13746. changed = true;
  13747. }
  13748. }
  13749. if (changed || this._vaoRecordInProgress) {
  13750. this.bindArrayBuffer(buffer);
  13751. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13752. }
  13753. };
  13754. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13755. if (indexBuffer == null) {
  13756. return;
  13757. }
  13758. if (this._cachedIndexBuffer !== indexBuffer) {
  13759. this._cachedIndexBuffer = indexBuffer;
  13760. this.bindIndexBuffer(indexBuffer);
  13761. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13762. }
  13763. };
  13764. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13765. var attributes = effect.getAttributesNames();
  13766. if (!this._vaoRecordInProgress) {
  13767. this._unbindVertexArrayObject();
  13768. }
  13769. this.unbindAllAttributes();
  13770. for (var index = 0; index < attributes.length; index++) {
  13771. var order = effect.getAttributeLocation(index);
  13772. if (order >= 0) {
  13773. var vertexBuffer = vertexBuffers[attributes[index]];
  13774. if (!vertexBuffer) {
  13775. continue;
  13776. }
  13777. this._gl.enableVertexAttribArray(order);
  13778. if (!this._vaoRecordInProgress) {
  13779. this._vertexAttribArraysEnabled[order] = true;
  13780. }
  13781. var buffer = vertexBuffer.getBuffer();
  13782. if (buffer) {
  13783. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13784. if (vertexBuffer.getIsInstanced()) {
  13785. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13786. if (!this._vaoRecordInProgress) {
  13787. this._currentInstanceLocations.push(order);
  13788. this._currentInstanceBuffers.push(buffer);
  13789. }
  13790. }
  13791. }
  13792. }
  13793. }
  13794. };
  13795. /**
  13796. * Records a vertex array object
  13797. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13798. * @param vertexBuffers defines the list of vertex buffers to store
  13799. * @param indexBuffer defines the index buffer to store
  13800. * @param effect defines the effect to store
  13801. * @returns the new vertex array object
  13802. */
  13803. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13804. var vao = this._gl.createVertexArray();
  13805. this._vaoRecordInProgress = true;
  13806. this._gl.bindVertexArray(vao);
  13807. this._mustWipeVertexAttributes = true;
  13808. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13809. this.bindIndexBuffer(indexBuffer);
  13810. this._vaoRecordInProgress = false;
  13811. this._gl.bindVertexArray(null);
  13812. return vao;
  13813. };
  13814. /**
  13815. * Bind a specific vertex array object
  13816. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13817. * @param vertexArrayObject defines the vertex array object to bind
  13818. * @param indexBuffer defines the index buffer to bind
  13819. */
  13820. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13821. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13822. this._cachedVertexArrayObject = vertexArrayObject;
  13823. this._gl.bindVertexArray(vertexArrayObject);
  13824. this._cachedVertexBuffers = null;
  13825. this._cachedIndexBuffer = null;
  13826. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13827. this._mustWipeVertexAttributes = true;
  13828. }
  13829. };
  13830. /**
  13831. * Bind webGl buffers directly to the webGL context
  13832. * @param vertexBuffer defines the vertex buffer to bind
  13833. * @param indexBuffer defines the index buffer to bind
  13834. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13835. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13836. * @param effect defines the effect associated with the vertex buffer
  13837. */
  13838. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13839. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13840. this._cachedVertexBuffers = vertexBuffer;
  13841. this._cachedEffectForVertexBuffers = effect;
  13842. var attributesCount = effect.getAttributesCount();
  13843. this._unbindVertexArrayObject();
  13844. this.unbindAllAttributes();
  13845. var offset = 0;
  13846. for (var index = 0; index < attributesCount; index++) {
  13847. if (index < vertexDeclaration.length) {
  13848. var order = effect.getAttributeLocation(index);
  13849. if (order >= 0) {
  13850. this._gl.enableVertexAttribArray(order);
  13851. this._vertexAttribArraysEnabled[order] = true;
  13852. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13853. }
  13854. offset += vertexDeclaration[index] * 4;
  13855. }
  13856. }
  13857. }
  13858. this._bindIndexBufferWithCache(indexBuffer);
  13859. };
  13860. Engine.prototype._unbindVertexArrayObject = function () {
  13861. if (!this._cachedVertexArrayObject) {
  13862. return;
  13863. }
  13864. this._cachedVertexArrayObject = null;
  13865. this._gl.bindVertexArray(null);
  13866. };
  13867. /**
  13868. * Bind a list of vertex buffers to the webGL context
  13869. * @param vertexBuffers defines the list of vertex buffers to bind
  13870. * @param indexBuffer defines the index buffer to bind
  13871. * @param effect defines the effect associated with the vertex buffers
  13872. */
  13873. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13874. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13875. this._cachedVertexBuffers = vertexBuffers;
  13876. this._cachedEffectForVertexBuffers = effect;
  13877. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13878. }
  13879. this._bindIndexBufferWithCache(indexBuffer);
  13880. };
  13881. /**
  13882. * Unbind all instance attributes
  13883. */
  13884. Engine.prototype.unbindInstanceAttributes = function () {
  13885. var boundBuffer;
  13886. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13887. var instancesBuffer = this._currentInstanceBuffers[i];
  13888. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13889. boundBuffer = instancesBuffer;
  13890. this.bindArrayBuffer(instancesBuffer);
  13891. }
  13892. var offsetLocation = this._currentInstanceLocations[i];
  13893. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13894. }
  13895. this._currentInstanceBuffers.length = 0;
  13896. this._currentInstanceLocations.length = 0;
  13897. };
  13898. /**
  13899. * Release and free the memory of a vertex array object
  13900. * @param vao defines the vertex array object to delete
  13901. */
  13902. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13903. this._gl.deleteVertexArray(vao);
  13904. };
  13905. /** @hidden */
  13906. Engine.prototype._releaseBuffer = function (buffer) {
  13907. buffer.references--;
  13908. if (buffer.references === 0) {
  13909. this._gl.deleteBuffer(buffer);
  13910. return true;
  13911. }
  13912. return false;
  13913. };
  13914. /**
  13915. * Creates a webGL buffer to use with instanciation
  13916. * @param capacity defines the size of the buffer
  13917. * @returns the webGL buffer
  13918. */
  13919. Engine.prototype.createInstancesBuffer = function (capacity) {
  13920. var buffer = this._gl.createBuffer();
  13921. if (!buffer) {
  13922. throw new Error("Unable to create instance buffer");
  13923. }
  13924. buffer.capacity = capacity;
  13925. this.bindArrayBuffer(buffer);
  13926. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13927. return buffer;
  13928. };
  13929. /**
  13930. * Delete a webGL buffer used with instanciation
  13931. * @param buffer defines the webGL buffer to delete
  13932. */
  13933. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13934. this._gl.deleteBuffer(buffer);
  13935. };
  13936. /**
  13937. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13938. * @param instancesBuffer defines the webGL buffer to update and bind
  13939. * @param data defines the data to store in the buffer
  13940. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13941. */
  13942. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13943. this.bindArrayBuffer(instancesBuffer);
  13944. if (data) {
  13945. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13946. }
  13947. if (offsetLocations[0].index !== undefined) {
  13948. var stride = 0;
  13949. for (var i = 0; i < offsetLocations.length; i++) {
  13950. var ai = offsetLocations[i];
  13951. stride += ai.attributeSize * 4;
  13952. }
  13953. for (var i = 0; i < offsetLocations.length; i++) {
  13954. var ai = offsetLocations[i];
  13955. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13956. this._gl.enableVertexAttribArray(ai.index);
  13957. this._vertexAttribArraysEnabled[ai.index] = true;
  13958. }
  13959. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13960. this._gl.vertexAttribDivisor(ai.index, 1);
  13961. this._currentInstanceLocations.push(ai.index);
  13962. this._currentInstanceBuffers.push(instancesBuffer);
  13963. }
  13964. }
  13965. else {
  13966. for (var index = 0; index < 4; index++) {
  13967. var offsetLocation = offsetLocations[index];
  13968. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13969. this._gl.enableVertexAttribArray(offsetLocation);
  13970. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13971. }
  13972. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13973. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13974. this._currentInstanceLocations.push(offsetLocation);
  13975. this._currentInstanceBuffers.push(instancesBuffer);
  13976. }
  13977. }
  13978. };
  13979. /**
  13980. * Apply all cached states (depth, culling, stencil and alpha)
  13981. */
  13982. Engine.prototype.applyStates = function () {
  13983. this._depthCullingState.apply(this._gl);
  13984. this._stencilState.apply(this._gl);
  13985. this._alphaState.apply(this._gl);
  13986. };
  13987. /**
  13988. * Send a draw order
  13989. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13990. * @param indexStart defines the starting index
  13991. * @param indexCount defines the number of index to draw
  13992. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13993. */
  13994. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13995. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13996. };
  13997. /**
  13998. * Draw a list of points
  13999. * @param verticesStart defines the index of first vertex to draw
  14000. * @param verticesCount defines the count of vertices to draw
  14001. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14002. */
  14003. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14004. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14005. };
  14006. /**
  14007. * Draw a list of unindexed primitives
  14008. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14009. * @param verticesStart defines the index of first vertex to draw
  14010. * @param verticesCount defines the count of vertices to draw
  14011. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14012. */
  14013. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14014. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14015. };
  14016. /**
  14017. * Draw a list of indexed primitives
  14018. * @param fillMode defines the primitive to use
  14019. * @param indexStart defines the starting index
  14020. * @param indexCount defines the number of index to draw
  14021. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14022. */
  14023. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14024. // Apply states
  14025. this.applyStates();
  14026. this._drawCalls.addCount(1, false);
  14027. // Render
  14028. var drawMode = this._drawMode(fillMode);
  14029. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14030. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14031. if (instancesCount) {
  14032. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14033. }
  14034. else {
  14035. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14036. }
  14037. };
  14038. /**
  14039. * Draw a list of unindexed primitives
  14040. * @param fillMode defines the primitive to use
  14041. * @param verticesStart defines the index of first vertex to draw
  14042. * @param verticesCount defines the count of vertices to draw
  14043. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14044. */
  14045. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14046. // Apply states
  14047. this.applyStates();
  14048. this._drawCalls.addCount(1, false);
  14049. var drawMode = this._drawMode(fillMode);
  14050. if (instancesCount) {
  14051. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14052. }
  14053. else {
  14054. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14055. }
  14056. };
  14057. Engine.prototype._drawMode = function (fillMode) {
  14058. switch (fillMode) {
  14059. // Triangle views
  14060. case BABYLON.Material.TriangleFillMode:
  14061. return this._gl.TRIANGLES;
  14062. case BABYLON.Material.PointFillMode:
  14063. return this._gl.POINTS;
  14064. case BABYLON.Material.WireFrameFillMode:
  14065. return this._gl.LINES;
  14066. // Draw modes
  14067. case BABYLON.Material.PointListDrawMode:
  14068. return this._gl.POINTS;
  14069. case BABYLON.Material.LineListDrawMode:
  14070. return this._gl.LINES;
  14071. case BABYLON.Material.LineLoopDrawMode:
  14072. return this._gl.LINE_LOOP;
  14073. case BABYLON.Material.LineStripDrawMode:
  14074. return this._gl.LINE_STRIP;
  14075. case BABYLON.Material.TriangleStripDrawMode:
  14076. return this._gl.TRIANGLE_STRIP;
  14077. case BABYLON.Material.TriangleFanDrawMode:
  14078. return this._gl.TRIANGLE_FAN;
  14079. default:
  14080. return this._gl.TRIANGLES;
  14081. }
  14082. };
  14083. // Shaders
  14084. /** @hidden */
  14085. Engine.prototype._releaseEffect = function (effect) {
  14086. if (this._compiledEffects[effect._key]) {
  14087. delete this._compiledEffects[effect._key];
  14088. this._deleteProgram(effect.getProgram());
  14089. }
  14090. };
  14091. /** @hidden */
  14092. Engine.prototype._deleteProgram = function (program) {
  14093. if (program) {
  14094. program.__SPECTOR_rebuildProgram = null;
  14095. if (program.transformFeedback) {
  14096. this.deleteTransformFeedback(program.transformFeedback);
  14097. program.transformFeedback = null;
  14098. }
  14099. this._gl.deleteProgram(program);
  14100. }
  14101. };
  14102. /**
  14103. * Create a new effect (used to store vertex/fragment shaders)
  14104. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14105. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14106. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14107. * @param samplers defines an array of string used to represent textures
  14108. * @param defines defines the string containing the defines to use to compile the shaders
  14109. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14110. * @param onCompiled defines a function to call when the effect creation is successful
  14111. * @param onError defines a function to call when the effect creation has failed
  14112. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14113. * @returns the new Effect
  14114. */
  14115. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14116. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14117. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14118. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14119. if (this._compiledEffects[name]) {
  14120. var compiledEffect = this._compiledEffects[name];
  14121. if (onCompiled && compiledEffect.isReady()) {
  14122. onCompiled(compiledEffect);
  14123. }
  14124. return compiledEffect;
  14125. }
  14126. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14127. effect._key = name;
  14128. this._compiledEffects[name] = effect;
  14129. return effect;
  14130. };
  14131. /**
  14132. * Create an effect to use with particle systems.
  14133. * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration
  14134. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14135. * @param uniformsNames defines a list of attribute names
  14136. * @param samplers defines an array of string used to represent textures
  14137. * @param defines defines the string containing the defines to use to compile the shaders
  14138. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14139. * @param onCompiled defines a function to call when the effect creation is successful
  14140. * @param onError defines a function to call when the effect creation has failed
  14141. * @returns the new Effect
  14142. */
  14143. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14144. if (uniformsNames === void 0) { uniformsNames = []; }
  14145. if (samplers === void 0) { samplers = []; }
  14146. if (defines === void 0) { defines = ""; }
  14147. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  14148. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  14149. if (defines.indexOf(" BILLBOARD") === -1) {
  14150. defines += "\n#define BILLBOARD\n";
  14151. }
  14152. if (samplers.indexOf("diffuseSampler") === -1) {
  14153. samplers.push("diffuseSampler");
  14154. }
  14155. return this.createEffect({
  14156. vertex: "particles",
  14157. fragmentElement: fragmentName
  14158. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  14159. };
  14160. /**
  14161. * Directly creates a webGL program
  14162. * @param vertexCode defines the vertex shader code to use
  14163. * @param fragmentCode defines the fragment shader code to use
  14164. * @param context defines the webGL context to use (if not set, the current one will be used)
  14165. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14166. * @returns the new webGL program
  14167. */
  14168. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14169. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14170. context = context || this._gl;
  14171. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14172. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14173. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14174. };
  14175. /**
  14176. * Creates a webGL program
  14177. * @param vertexCode defines the vertex shader code to use
  14178. * @param fragmentCode defines the fragment shader code to use
  14179. * @param defines defines the string containing the defines to use to compile the shaders
  14180. * @param context defines the webGL context to use (if not set, the current one will be used)
  14181. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14182. * @returns the new webGL program
  14183. */
  14184. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14185. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14186. context = context || this._gl;
  14187. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14188. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14189. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14190. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14191. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14192. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14193. return program;
  14194. };
  14195. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14196. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14197. var shaderProgram = context.createProgram();
  14198. if (!shaderProgram) {
  14199. throw new Error("Unable to create program");
  14200. }
  14201. context.attachShader(shaderProgram, vertexShader);
  14202. context.attachShader(shaderProgram, fragmentShader);
  14203. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14204. var transformFeedback = this.createTransformFeedback();
  14205. this.bindTransformFeedback(transformFeedback);
  14206. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14207. shaderProgram.transformFeedback = transformFeedback;
  14208. }
  14209. context.linkProgram(shaderProgram);
  14210. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14211. this.bindTransformFeedback(null);
  14212. }
  14213. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14214. if (!linked) {
  14215. var error = context.getProgramInfoLog(shaderProgram);
  14216. if (error) {
  14217. throw new Error(error);
  14218. }
  14219. }
  14220. context.validateProgram(shaderProgram);
  14221. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14222. if (!validated) {
  14223. var error = context.getProgramInfoLog(shaderProgram);
  14224. if (error) {
  14225. throw new Error(error);
  14226. }
  14227. }
  14228. context.deleteShader(vertexShader);
  14229. context.deleteShader(fragmentShader);
  14230. return shaderProgram;
  14231. };
  14232. /**
  14233. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14234. * @param shaderProgram defines the webGL program to use
  14235. * @param uniformsNames defines the list of uniform names
  14236. * @returns an array of webGL uniform locations
  14237. */
  14238. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14239. var results = new Array();
  14240. for (var index = 0; index < uniformsNames.length; index++) {
  14241. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14242. }
  14243. return results;
  14244. };
  14245. /**
  14246. * Gets the lsit of active attributes for a given webGL program
  14247. * @param shaderProgram defines the webGL program to use
  14248. * @param attributesNames defines the list of attribute names to get
  14249. * @returns an array of indices indicating the offset of each attribute
  14250. */
  14251. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14252. var results = [];
  14253. for (var index = 0; index < attributesNames.length; index++) {
  14254. try {
  14255. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14256. }
  14257. catch (e) {
  14258. results.push(-1);
  14259. }
  14260. }
  14261. return results;
  14262. };
  14263. /**
  14264. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14265. * @param effect defines the effect to activate
  14266. */
  14267. Engine.prototype.enableEffect = function (effect) {
  14268. if (!effect) {
  14269. return;
  14270. }
  14271. // Use program
  14272. this.bindSamplers(effect);
  14273. this._currentEffect = effect;
  14274. if (effect.onBind) {
  14275. effect.onBind(effect);
  14276. }
  14277. effect.onBindObservable.notifyObservers(effect);
  14278. };
  14279. /**
  14280. * Set the value of an uniform to an array of int32
  14281. * @param uniform defines the webGL uniform location where to store the value
  14282. * @param array defines the array of int32 to store
  14283. */
  14284. Engine.prototype.setIntArray = function (uniform, array) {
  14285. if (!uniform)
  14286. return;
  14287. this._gl.uniform1iv(uniform, array);
  14288. };
  14289. /**
  14290. * Set the value of an uniform to an array of int32 (stored as vec2)
  14291. * @param uniform defines the webGL uniform location where to store the value
  14292. * @param array defines the array of int32 to store
  14293. */
  14294. Engine.prototype.setIntArray2 = function (uniform, array) {
  14295. if (!uniform || array.length % 2 !== 0)
  14296. return;
  14297. this._gl.uniform2iv(uniform, array);
  14298. };
  14299. /**
  14300. * Set the value of an uniform to an array of int32 (stored as vec3)
  14301. * @param uniform defines the webGL uniform location where to store the value
  14302. * @param array defines the array of int32 to store
  14303. */
  14304. Engine.prototype.setIntArray3 = function (uniform, array) {
  14305. if (!uniform || array.length % 3 !== 0)
  14306. return;
  14307. this._gl.uniform3iv(uniform, array);
  14308. };
  14309. /**
  14310. * Set the value of an uniform to an array of int32 (stored as vec4)
  14311. * @param uniform defines the webGL uniform location where to store the value
  14312. * @param array defines the array of int32 to store
  14313. */
  14314. Engine.prototype.setIntArray4 = function (uniform, array) {
  14315. if (!uniform || array.length % 4 !== 0)
  14316. return;
  14317. this._gl.uniform4iv(uniform, array);
  14318. };
  14319. /**
  14320. * Set the value of an uniform to an array of float32
  14321. * @param uniform defines the webGL uniform location where to store the value
  14322. * @param array defines the array of float32 to store
  14323. */
  14324. Engine.prototype.setFloatArray = function (uniform, array) {
  14325. if (!uniform)
  14326. return;
  14327. this._gl.uniform1fv(uniform, array);
  14328. };
  14329. /**
  14330. * Set the value of an uniform to an array of float32 (stored as vec2)
  14331. * @param uniform defines the webGL uniform location where to store the value
  14332. * @param array defines the array of float32 to store
  14333. */
  14334. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14335. if (!uniform || array.length % 2 !== 0)
  14336. return;
  14337. this._gl.uniform2fv(uniform, array);
  14338. };
  14339. /**
  14340. * Set the value of an uniform to an array of float32 (stored as vec3)
  14341. * @param uniform defines the webGL uniform location where to store the value
  14342. * @param array defines the array of float32 to store
  14343. */
  14344. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14345. if (!uniform || array.length % 3 !== 0)
  14346. return;
  14347. this._gl.uniform3fv(uniform, array);
  14348. };
  14349. /**
  14350. * Set the value of an uniform to an array of float32 (stored as vec4)
  14351. * @param uniform defines the webGL uniform location where to store the value
  14352. * @param array defines the array of float32 to store
  14353. */
  14354. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14355. if (!uniform || array.length % 4 !== 0)
  14356. return;
  14357. this._gl.uniform4fv(uniform, array);
  14358. };
  14359. /**
  14360. * Set the value of an uniform to an array of number
  14361. * @param uniform defines the webGL uniform location where to store the value
  14362. * @param array defines the array of number to store
  14363. */
  14364. Engine.prototype.setArray = function (uniform, array) {
  14365. if (!uniform)
  14366. return;
  14367. this._gl.uniform1fv(uniform, array);
  14368. };
  14369. /**
  14370. * Set the value of an uniform to an array of number (stored as vec2)
  14371. * @param uniform defines the webGL uniform location where to store the value
  14372. * @param array defines the array of number to store
  14373. */
  14374. Engine.prototype.setArray2 = function (uniform, array) {
  14375. if (!uniform || array.length % 2 !== 0)
  14376. return;
  14377. this._gl.uniform2fv(uniform, array);
  14378. };
  14379. /**
  14380. * Set the value of an uniform to an array of number (stored as vec3)
  14381. * @param uniform defines the webGL uniform location where to store the value
  14382. * @param array defines the array of number to store
  14383. */
  14384. Engine.prototype.setArray3 = function (uniform, array) {
  14385. if (!uniform || array.length % 3 !== 0)
  14386. return;
  14387. this._gl.uniform3fv(uniform, array);
  14388. };
  14389. /**
  14390. * Set the value of an uniform to an array of number (stored as vec4)
  14391. * @param uniform defines the webGL uniform location where to store the value
  14392. * @param array defines the array of number to store
  14393. */
  14394. Engine.prototype.setArray4 = function (uniform, array) {
  14395. if (!uniform || array.length % 4 !== 0)
  14396. return;
  14397. this._gl.uniform4fv(uniform, array);
  14398. };
  14399. /**
  14400. * Set the value of an uniform to an array of float32 (stored as matrices)
  14401. * @param uniform defines the webGL uniform location where to store the value
  14402. * @param matrices defines the array of float32 to store
  14403. */
  14404. Engine.prototype.setMatrices = function (uniform, matrices) {
  14405. if (!uniform)
  14406. return;
  14407. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14408. };
  14409. /**
  14410. * Set the value of an uniform to a matrix
  14411. * @param uniform defines the webGL uniform location where to store the value
  14412. * @param matrix defines the matrix to store
  14413. */
  14414. Engine.prototype.setMatrix = function (uniform, matrix) {
  14415. if (!uniform)
  14416. return;
  14417. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14418. };
  14419. /**
  14420. * Set the value of an uniform to a matrix (3x3)
  14421. * @param uniform defines the webGL uniform location where to store the value
  14422. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14423. */
  14424. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14425. if (!uniform)
  14426. return;
  14427. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14428. };
  14429. /**
  14430. * Set the value of an uniform to a matrix (2x2)
  14431. * @param uniform defines the webGL uniform location where to store the value
  14432. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14433. */
  14434. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14435. if (!uniform)
  14436. return;
  14437. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14438. };
  14439. /**
  14440. * Set the value of an uniform to a number (int)
  14441. * @param uniform defines the webGL uniform location where to store the value
  14442. * @param value defines the int number to store
  14443. */
  14444. Engine.prototype.setInt = function (uniform, value) {
  14445. if (!uniform)
  14446. return;
  14447. this._gl.uniform1i(uniform, value);
  14448. };
  14449. /**
  14450. * Set the value of an uniform to a number (float)
  14451. * @param uniform defines the webGL uniform location where to store the value
  14452. * @param value defines the float number to store
  14453. */
  14454. Engine.prototype.setFloat = function (uniform, value) {
  14455. if (!uniform)
  14456. return;
  14457. this._gl.uniform1f(uniform, value);
  14458. };
  14459. /**
  14460. * Set the value of an uniform to a vec2
  14461. * @param uniform defines the webGL uniform location where to store the value
  14462. * @param x defines the 1st component of the value
  14463. * @param y defines the 2nd component of the value
  14464. */
  14465. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14466. if (!uniform)
  14467. return;
  14468. this._gl.uniform2f(uniform, x, y);
  14469. };
  14470. /**
  14471. * Set the value of an uniform to a vec3
  14472. * @param uniform defines the webGL uniform location where to store the value
  14473. * @param x defines the 1st component of the value
  14474. * @param y defines the 2nd component of the value
  14475. * @param z defines the 3rd component of the value
  14476. */
  14477. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14478. if (!uniform)
  14479. return;
  14480. this._gl.uniform3f(uniform, x, y, z);
  14481. };
  14482. /**
  14483. * Set the value of an uniform to a boolean
  14484. * @param uniform defines the webGL uniform location where to store the value
  14485. * @param bool defines the boolean to store
  14486. */
  14487. Engine.prototype.setBool = function (uniform, bool) {
  14488. if (!uniform)
  14489. return;
  14490. this._gl.uniform1i(uniform, bool);
  14491. };
  14492. /**
  14493. * Set the value of an uniform to a vec4
  14494. * @param uniform defines the webGL uniform location where to store the value
  14495. * @param x defines the 1st component of the value
  14496. * @param y defines the 2nd component of the value
  14497. * @param z defines the 3rd component of the value
  14498. * @param w defines the 4th component of the value
  14499. */
  14500. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14501. if (!uniform)
  14502. return;
  14503. this._gl.uniform4f(uniform, x, y, z, w);
  14504. };
  14505. /**
  14506. * Set the value of an uniform to a Color3
  14507. * @param uniform defines the webGL uniform location where to store the value
  14508. * @param color3 defines the color to store
  14509. */
  14510. Engine.prototype.setColor3 = function (uniform, color3) {
  14511. if (!uniform)
  14512. return;
  14513. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14514. };
  14515. /**
  14516. * Set the value of an uniform to a Color3 and an alpha value
  14517. * @param uniform defines the webGL uniform location where to store the value
  14518. * @param color3 defines the color to store
  14519. * @param alpha defines the alpha component to store
  14520. */
  14521. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14522. if (!uniform)
  14523. return;
  14524. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14525. };
  14526. /**
  14527. * Sets a Color4 on a uniform variable
  14528. * @param uniform defines the uniform location
  14529. * @param color4 defines the value to be set
  14530. */
  14531. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14532. if (!uniform)
  14533. return;
  14534. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14535. };
  14536. // States
  14537. /**
  14538. * Set various states to the webGL context
  14539. * @param culling defines backface culling state
  14540. * @param zOffset defines the value to apply to zOffset (0 by default)
  14541. * @param force defines if states must be applied even if cache is up to date
  14542. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14543. */
  14544. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14545. if (zOffset === void 0) { zOffset = 0; }
  14546. if (reverseSide === void 0) { reverseSide = false; }
  14547. // Culling
  14548. if (this._depthCullingState.cull !== culling || force) {
  14549. this._depthCullingState.cull = culling;
  14550. }
  14551. // Cull face
  14552. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14553. if (this._depthCullingState.cullFace !== cullFace || force) {
  14554. this._depthCullingState.cullFace = cullFace;
  14555. }
  14556. // Z offset
  14557. this.setZOffset(zOffset);
  14558. // Front face
  14559. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14560. if (this._depthCullingState.frontFace !== frontFace || force) {
  14561. this._depthCullingState.frontFace = frontFace;
  14562. }
  14563. };
  14564. /**
  14565. * Set the z offset to apply to current rendering
  14566. * @param value defines the offset to apply
  14567. */
  14568. Engine.prototype.setZOffset = function (value) {
  14569. this._depthCullingState.zOffset = value;
  14570. };
  14571. /**
  14572. * Gets the current value of the zOffset
  14573. * @returns the current zOffset state
  14574. */
  14575. Engine.prototype.getZOffset = function () {
  14576. return this._depthCullingState.zOffset;
  14577. };
  14578. /**
  14579. * Enable or disable depth buffering
  14580. * @param enable defines the state to set
  14581. */
  14582. Engine.prototype.setDepthBuffer = function (enable) {
  14583. this._depthCullingState.depthTest = enable;
  14584. };
  14585. /**
  14586. * Gets a boolean indicating if depth writing is enabled
  14587. * @returns the current depth writing state
  14588. */
  14589. Engine.prototype.getDepthWrite = function () {
  14590. return this._depthCullingState.depthMask;
  14591. };
  14592. /**
  14593. * Enable or disable depth writing
  14594. * @param enable defines the state to set
  14595. */
  14596. Engine.prototype.setDepthWrite = function (enable) {
  14597. this._depthCullingState.depthMask = enable;
  14598. };
  14599. /**
  14600. * Enable or disable color writing
  14601. * @param enable defines the state to set
  14602. */
  14603. Engine.prototype.setColorWrite = function (enable) {
  14604. this._gl.colorMask(enable, enable, enable, enable);
  14605. this._colorWrite = enable;
  14606. };
  14607. /**
  14608. * Gets a boolean indicating if color writing is enabled
  14609. * @returns the current color writing state
  14610. */
  14611. Engine.prototype.getColorWrite = function () {
  14612. return this._colorWrite;
  14613. };
  14614. /**
  14615. * Sets alpha constants used by some alpha blending modes
  14616. * @param r defines the red component
  14617. * @param g defines the green component
  14618. * @param b defines the blue component
  14619. * @param a defines the alpha component
  14620. */
  14621. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14622. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14623. };
  14624. /**
  14625. * Sets the current alpha mode
  14626. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14627. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14628. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14629. */
  14630. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14631. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14632. if (this._alphaMode === mode) {
  14633. return;
  14634. }
  14635. switch (mode) {
  14636. case Engine.ALPHA_DISABLE:
  14637. this._alphaState.alphaBlend = false;
  14638. break;
  14639. case Engine.ALPHA_PREMULTIPLIED:
  14640. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14641. this._alphaState.alphaBlend = true;
  14642. break;
  14643. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14644. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14645. this._alphaState.alphaBlend = true;
  14646. break;
  14647. case Engine.ALPHA_COMBINE:
  14648. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14649. this._alphaState.alphaBlend = true;
  14650. break;
  14651. case Engine.ALPHA_ONEONE:
  14652. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14653. this._alphaState.alphaBlend = true;
  14654. break;
  14655. case Engine.ALPHA_ADD:
  14656. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14657. this._alphaState.alphaBlend = true;
  14658. break;
  14659. case Engine.ALPHA_SUBTRACT:
  14660. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14661. this._alphaState.alphaBlend = true;
  14662. break;
  14663. case Engine.ALPHA_MULTIPLY:
  14664. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14665. this._alphaState.alphaBlend = true;
  14666. break;
  14667. case Engine.ALPHA_MAXIMIZED:
  14668. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14669. this._alphaState.alphaBlend = true;
  14670. break;
  14671. case Engine.ALPHA_INTERPOLATE:
  14672. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14673. this._alphaState.alphaBlend = true;
  14674. break;
  14675. case Engine.ALPHA_SCREENMODE:
  14676. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14677. this._alphaState.alphaBlend = true;
  14678. break;
  14679. }
  14680. if (!noDepthWriteChange) {
  14681. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14682. }
  14683. this._alphaMode = mode;
  14684. };
  14685. /**
  14686. * Gets the current alpha mode
  14687. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14688. * @returns the current alpha mode
  14689. */
  14690. Engine.prototype.getAlphaMode = function () {
  14691. return this._alphaMode;
  14692. };
  14693. // Textures
  14694. /**
  14695. * Clears the list of texture accessible through engine.
  14696. * This can help preventing texture load conflict due to name collision.
  14697. */
  14698. Engine.prototype.clearInternalTexturesCache = function () {
  14699. this._internalTexturesCache = [];
  14700. };
  14701. /**
  14702. * Force the entire cache to be cleared
  14703. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14704. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14705. */
  14706. Engine.prototype.wipeCaches = function (bruteForce) {
  14707. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14708. return;
  14709. }
  14710. this._currentEffect = null;
  14711. this._unpackFlipYCached = null;
  14712. this._viewportCached.x = 0;
  14713. this._viewportCached.y = 0;
  14714. this._viewportCached.z = 0;
  14715. this._viewportCached.w = 0;
  14716. if (bruteForce) {
  14717. this.resetTextureCache();
  14718. this._currentProgram = null;
  14719. this._stencilState.reset();
  14720. this._depthCullingState.reset();
  14721. this.setDepthFunctionToLessOrEqual();
  14722. this._alphaState.reset();
  14723. }
  14724. this._resetVertexBufferBinding();
  14725. this._cachedIndexBuffer = null;
  14726. this._cachedEffectForVertexBuffers = null;
  14727. this._unbindVertexArrayObject();
  14728. this.bindIndexBuffer(null);
  14729. };
  14730. /**
  14731. * Set the compressed texture format to use, based on the formats you have, and the formats
  14732. * supported by the hardware / browser.
  14733. *
  14734. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14735. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14736. * to API arguments needed to compressed textures. This puts the burden on the container
  14737. * generator to house the arcane code for determining these for current & future formats.
  14738. *
  14739. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14740. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14741. *
  14742. * Note: The result of this call is not taken into account when a texture is base64.
  14743. *
  14744. * @param formatsAvailable defines the list of those format families you have created
  14745. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14746. *
  14747. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14748. * @returns The extension selected.
  14749. */
  14750. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14751. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14752. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14753. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14754. return this._textureFormatInUse = this._texturesSupported[i];
  14755. }
  14756. }
  14757. }
  14758. // actively set format to nothing, to allow this to be called more than once
  14759. // and possibly fail the 2nd time
  14760. this._textureFormatInUse = null;
  14761. return null;
  14762. };
  14763. /** @hidden */
  14764. Engine.prototype._createTexture = function () {
  14765. var texture = this._gl.createTexture();
  14766. if (!texture) {
  14767. throw new Error("Unable to create texture");
  14768. }
  14769. return texture;
  14770. };
  14771. /**
  14772. * Usually called from BABYLON.Texture.ts.
  14773. * Passed information to create a WebGLTexture
  14774. * @param urlArg defines a value which contains one of the following:
  14775. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14776. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14777. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14778. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14779. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14780. * @param scene needed for loading to the correct scene
  14781. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14782. * @param onLoad optional callback to be called upon successful completion
  14783. * @param onError optional callback to be called upon failure
  14784. * @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
  14785. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14786. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14787. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14788. */
  14789. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14790. var _this = this;
  14791. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14792. if (onLoad === void 0) { onLoad = null; }
  14793. if (onError === void 0) { onError = null; }
  14794. if (buffer === void 0) { buffer = null; }
  14795. if (fallback === void 0) { fallback = null; }
  14796. if (format === void 0) { format = null; }
  14797. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14798. var fromData = url.substr(0, 5) === "data:";
  14799. var fromBlob = url.substr(0, 5) === "blob:";
  14800. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14801. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14802. // establish the file extension, if possible
  14803. var lastDot = url.lastIndexOf('.');
  14804. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14805. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14806. var isTGA = (extension.indexOf(".tga") === 0);
  14807. // determine if a ktx file should be substituted
  14808. var isKTX = false;
  14809. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14810. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14811. isKTX = true;
  14812. }
  14813. if (scene) {
  14814. scene._addPendingData(texture);
  14815. }
  14816. texture.url = url;
  14817. texture.generateMipMaps = !noMipmap;
  14818. texture.samplingMode = samplingMode;
  14819. texture.invertY = invertY;
  14820. if (!this._doNotHandleContextLost) {
  14821. // Keep a link to the buffer only if we plan to handle context lost
  14822. texture._buffer = buffer;
  14823. }
  14824. var onLoadObserver = null;
  14825. if (onLoad && !fallback) {
  14826. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14827. }
  14828. if (!fallback)
  14829. this._internalTexturesCache.push(texture);
  14830. var onerror = function (message, exception) {
  14831. if (scene) {
  14832. scene._removePendingData(texture);
  14833. }
  14834. if (onLoadObserver && !isKTX) {
  14835. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14836. texture.onLoadedObservable.remove(onLoadObserver);
  14837. }
  14838. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14839. if (isKTX) {
  14840. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14841. }
  14842. else if (BABYLON.Tools.UseFallbackTexture) {
  14843. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14844. }
  14845. if (onError) {
  14846. onError(message || "Unknown error", exception);
  14847. }
  14848. };
  14849. var callback = null;
  14850. // processing for non-image formats
  14851. if (isKTX || isTGA || isDDS) {
  14852. if (isKTX) {
  14853. callback = function (data) {
  14854. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14855. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14856. ktx.uploadLevels(_this._gl, !noMipmap);
  14857. return false;
  14858. }, samplingMode);
  14859. };
  14860. }
  14861. else if (isTGA) {
  14862. callback = function (arrayBuffer) {
  14863. var data = new Uint8Array(arrayBuffer);
  14864. var header = BABYLON.TGATools.GetTGAHeader(data);
  14865. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14866. BABYLON.TGATools.UploadContent(_this._gl, data);
  14867. return false;
  14868. }, samplingMode);
  14869. };
  14870. }
  14871. else if (isDDS) {
  14872. callback = function (data) {
  14873. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14874. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14875. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14876. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14877. return false;
  14878. }, samplingMode);
  14879. };
  14880. }
  14881. if (!buffer) {
  14882. this._loadFile(url, function (data) {
  14883. if (callback) {
  14884. callback(data);
  14885. }
  14886. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14887. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14888. });
  14889. }
  14890. else {
  14891. if (callback) {
  14892. callback(buffer);
  14893. }
  14894. }
  14895. // image format processing
  14896. }
  14897. else {
  14898. var onload = function (img) {
  14899. if (fromBlob && !_this._doNotHandleContextLost) {
  14900. // We need to store the image if we need to rebuild the texture
  14901. // in case of a webgl context lost
  14902. texture._buffer = img;
  14903. }
  14904. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14905. var gl = _this._gl;
  14906. var isPot = (img.width === potWidth && img.height === potHeight);
  14907. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14908. if (isPot) {
  14909. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14910. return false;
  14911. }
  14912. var maxTextureSize = _this._caps.maxTextureSize;
  14913. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14914. _this._prepareWorkingCanvas();
  14915. if (!_this._workingCanvas || !_this._workingContext) {
  14916. return false;
  14917. }
  14918. _this._workingCanvas.width = potWidth;
  14919. _this._workingCanvas.height = potHeight;
  14920. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14921. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14922. texture.width = potWidth;
  14923. texture.height = potHeight;
  14924. return false;
  14925. }
  14926. else {
  14927. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14928. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14929. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14930. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14931. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14932. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14933. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14934. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14935. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14936. _this._releaseTexture(source_1);
  14937. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14938. continuationCallback();
  14939. });
  14940. }
  14941. return true;
  14942. }, samplingMode);
  14943. };
  14944. if (!fromData || isBase64) {
  14945. if (buffer instanceof HTMLImageElement) {
  14946. onload(buffer);
  14947. }
  14948. else {
  14949. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14950. }
  14951. }
  14952. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14953. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14954. }
  14955. else {
  14956. onload(buffer);
  14957. }
  14958. }
  14959. return texture;
  14960. };
  14961. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14962. var _this = this;
  14963. var rtt = this.createRenderTargetTexture({
  14964. width: destination.width,
  14965. height: destination.height,
  14966. }, {
  14967. generateMipMaps: false,
  14968. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14969. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14970. generateDepthBuffer: false,
  14971. generateStencilBuffer: false
  14972. });
  14973. if (!this._rescalePostProcess) {
  14974. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14975. }
  14976. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14977. _this._rescalePostProcess.onApply = function (effect) {
  14978. effect._bindTexture("textureSampler", source);
  14979. };
  14980. var hostingScene = scene;
  14981. if (!hostingScene) {
  14982. hostingScene = _this.scenes[_this.scenes.length - 1];
  14983. }
  14984. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14985. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14986. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14987. _this.unBindFramebuffer(rtt);
  14988. _this._releaseTexture(rtt);
  14989. if (onComplete) {
  14990. onComplete();
  14991. }
  14992. });
  14993. };
  14994. /**
  14995. * Update a raw texture
  14996. * @param texture defines the texture to update
  14997. * @param data defines the data to store in the texture
  14998. * @param format defines the format of the data
  14999. * @param invertY defines if data must be stored with Y axis inverted
  15000. * @param compression defines the compression used (null by default)
  15001. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15002. */
  15003. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15004. if (compression === void 0) { compression = null; }
  15005. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15006. if (!texture) {
  15007. return;
  15008. }
  15009. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15010. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15011. // babylon's internalFormat but gl's texImage2D format
  15012. var internalFormat = this._getInternalFormat(format);
  15013. var textureType = this._getWebGLTextureType(type);
  15014. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15015. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15016. if (!this._doNotHandleContextLost) {
  15017. texture._bufferView = data;
  15018. texture.format = format;
  15019. texture.type = type;
  15020. texture.invertY = invertY;
  15021. texture._compression = compression;
  15022. }
  15023. if (texture.width % 4 !== 0) {
  15024. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15025. }
  15026. if (compression && data) {
  15027. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15028. }
  15029. else {
  15030. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15031. }
  15032. if (texture.generateMipMaps) {
  15033. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15034. }
  15035. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15036. // this.resetTextureCache();
  15037. texture.isReady = true;
  15038. };
  15039. /**
  15040. * Creates a raw texture
  15041. * @param data defines the data to store in the texture
  15042. * @param width defines the width of the texture
  15043. * @param height defines the height of the texture
  15044. * @param format defines the format of the data
  15045. * @param generateMipMaps defines if the engine should generate the mip levels
  15046. * @param invertY defines if data must be stored with Y axis inverted
  15047. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15048. * @param compression defines the compression used (null by default)
  15049. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15050. * @returns the raw texture inside an InternalTexture
  15051. */
  15052. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15053. if (compression === void 0) { compression = null; }
  15054. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15055. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15056. texture.baseWidth = width;
  15057. texture.baseHeight = height;
  15058. texture.width = width;
  15059. texture.height = height;
  15060. texture.format = format;
  15061. texture.generateMipMaps = generateMipMaps;
  15062. texture.samplingMode = samplingMode;
  15063. texture.invertY = invertY;
  15064. texture._compression = compression;
  15065. texture.type = type;
  15066. if (!this._doNotHandleContextLost) {
  15067. texture._bufferView = data;
  15068. }
  15069. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15070. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15071. // Filters
  15072. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15073. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15074. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15075. if (generateMipMaps) {
  15076. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15077. }
  15078. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15079. this._internalTexturesCache.push(texture);
  15080. return texture;
  15081. };
  15082. /** @hidden */
  15083. Engine.prototype._unpackFlipY = function (value) {
  15084. if (this._unpackFlipYCached !== value) {
  15085. this._unpackFlipYCached = value;
  15086. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15087. }
  15088. };
  15089. /**
  15090. * Creates a dynamic texture
  15091. * @param width defines the width of the texture
  15092. * @param height defines the height of the texture
  15093. * @param generateMipMaps defines if the engine should generate the mip levels
  15094. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15095. * @returns the dynamic texture inside an InternalTexture
  15096. */
  15097. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15098. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15099. texture.baseWidth = width;
  15100. texture.baseHeight = height;
  15101. if (generateMipMaps) {
  15102. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15103. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15104. }
  15105. // this.resetTextureCache();
  15106. texture.width = width;
  15107. texture.height = height;
  15108. texture.isReady = false;
  15109. texture.generateMipMaps = generateMipMaps;
  15110. texture.samplingMode = samplingMode;
  15111. this.updateTextureSamplingMode(samplingMode, texture);
  15112. this._internalTexturesCache.push(texture);
  15113. return texture;
  15114. };
  15115. /**
  15116. * Update the sampling mode of a given texture
  15117. * @param samplingMode defines the required sampling mode
  15118. * @param texture defines the texture to update
  15119. */
  15120. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15121. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  15122. if (texture.isCube) {
  15123. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15124. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15125. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15126. }
  15127. else if (texture.is3D) {
  15128. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15129. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15130. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15131. }
  15132. else {
  15133. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15134. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15135. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15136. }
  15137. texture.samplingMode = samplingMode;
  15138. };
  15139. /**
  15140. * Update the content of a dynamic texture
  15141. * @param texture defines the texture to update
  15142. * @param canvas defines the canvas containing the source
  15143. * @param invertY defines if data must be stored with Y axis inverted
  15144. * @param premulAlpha defines if alpha is stored as premultiplied
  15145. * @param format defines the format of the data
  15146. */
  15147. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15148. if (premulAlpha === void 0) { premulAlpha = false; }
  15149. if (!texture) {
  15150. return;
  15151. }
  15152. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15153. this._unpackFlipY(invertY);
  15154. if (premulAlpha) {
  15155. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15156. }
  15157. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15158. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15159. if (texture.generateMipMaps) {
  15160. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15161. }
  15162. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15163. if (premulAlpha) {
  15164. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15165. }
  15166. texture.isReady = true;
  15167. };
  15168. /**
  15169. * Update a video texture
  15170. * @param texture defines the texture to update
  15171. * @param video defines the video element to use
  15172. * @param invertY defines if data must be stored with Y axis inverted
  15173. */
  15174. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15175. if (!texture || texture._isDisabled) {
  15176. return;
  15177. }
  15178. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15179. this._unpackFlipY(!invertY); // Video are upside down by default
  15180. try {
  15181. // Testing video texture support
  15182. if (this._videoTextureSupported === undefined) {
  15183. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15184. if (this._gl.getError() !== 0) {
  15185. this._videoTextureSupported = false;
  15186. }
  15187. else {
  15188. this._videoTextureSupported = true;
  15189. }
  15190. }
  15191. // Copy video through the current working canvas if video texture is not supported
  15192. if (!this._videoTextureSupported) {
  15193. if (!texture._workingCanvas) {
  15194. texture._workingCanvas = document.createElement("canvas");
  15195. var context = texture._workingCanvas.getContext("2d");
  15196. if (!context) {
  15197. throw new Error("Unable to get 2d context");
  15198. }
  15199. texture._workingContext = context;
  15200. texture._workingCanvas.width = texture.width;
  15201. texture._workingCanvas.height = texture.height;
  15202. }
  15203. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15204. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15205. }
  15206. else {
  15207. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15208. }
  15209. if (texture.generateMipMaps) {
  15210. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15211. }
  15212. if (!wasPreviouslyBound) {
  15213. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15214. }
  15215. // this.resetTextureCache();
  15216. texture.isReady = true;
  15217. }
  15218. catch (ex) {
  15219. // Something unexpected
  15220. // Let's disable the texture
  15221. texture._isDisabled = true;
  15222. }
  15223. };
  15224. /**
  15225. * Updates a depth texture Comparison Mode and Function.
  15226. * If the comparison Function is equal to 0, the mode will be set to none.
  15227. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15228. * @param texture The texture to set the comparison function for
  15229. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15230. */
  15231. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15232. if (this.webGLVersion === 1) {
  15233. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15234. return;
  15235. }
  15236. var gl = this._gl;
  15237. if (texture.isCube) {
  15238. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15239. if (comparisonFunction === 0) {
  15240. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15241. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15242. }
  15243. else {
  15244. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15245. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15246. }
  15247. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15248. }
  15249. else {
  15250. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15251. if (comparisonFunction === 0) {
  15252. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15253. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15254. }
  15255. else {
  15256. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15257. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15258. }
  15259. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15260. }
  15261. texture._comparisonFunction = comparisonFunction;
  15262. };
  15263. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15264. var width = size.width || size;
  15265. var height = size.height || size;
  15266. internalTexture.baseWidth = width;
  15267. internalTexture.baseHeight = height;
  15268. internalTexture.width = width;
  15269. internalTexture.height = height;
  15270. internalTexture.isReady = true;
  15271. internalTexture.samples = 1;
  15272. internalTexture.generateMipMaps = false;
  15273. internalTexture._generateDepthBuffer = true;
  15274. internalTexture._generateStencilBuffer = generateStencil;
  15275. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15276. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15277. internalTexture._comparisonFunction = comparisonFunction;
  15278. var gl = this._gl;
  15279. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15280. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15281. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15282. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15283. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15284. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15285. if (comparisonFunction === 0) {
  15286. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15287. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15288. }
  15289. else {
  15290. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15291. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15292. }
  15293. };
  15294. /**
  15295. * Creates a depth stencil texture.
  15296. * This is only available in WebGL 2 or with the depth texture extension available.
  15297. * @param size The size of face edge in the texture.
  15298. * @param options The options defining the texture.
  15299. * @returns The texture
  15300. */
  15301. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15302. if (options.isCube) {
  15303. var width = size.width || size;
  15304. return this._createDepthStencilCubeTexture(width, options);
  15305. }
  15306. else {
  15307. return this._createDepthStencilTexture(size, options);
  15308. }
  15309. };
  15310. /**
  15311. * Creates a depth stencil texture.
  15312. * This is only available in WebGL 2 or with the depth texture extension available.
  15313. * @param size The size of face edge in the texture.
  15314. * @param options The options defining the texture.
  15315. * @returns The texture
  15316. */
  15317. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15318. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15319. if (!this._caps.depthTextureExtension) {
  15320. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15321. return internalTexture;
  15322. }
  15323. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15324. var gl = this._gl;
  15325. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15326. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15327. if (this.webGLVersion > 1) {
  15328. if (internalOptions.generateStencil) {
  15329. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15330. }
  15331. else {
  15332. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15333. }
  15334. }
  15335. else {
  15336. if (internalOptions.generateStencil) {
  15337. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15338. }
  15339. else {
  15340. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15341. }
  15342. }
  15343. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15344. return internalTexture;
  15345. };
  15346. /**
  15347. * Creates a depth stencil cube texture.
  15348. * This is only available in WebGL 2.
  15349. * @param size The size of face edge in the cube texture.
  15350. * @param options The options defining the cube texture.
  15351. * @returns The cube texture
  15352. */
  15353. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15354. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15355. internalTexture.isCube = true;
  15356. if (this.webGLVersion === 1) {
  15357. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15358. return internalTexture;
  15359. }
  15360. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15361. var gl = this._gl;
  15362. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15363. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15364. // Create the depth/stencil buffer
  15365. for (var face = 0; face < 6; face++) {
  15366. if (internalOptions.generateStencil) {
  15367. 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);
  15368. }
  15369. else {
  15370. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15371. }
  15372. }
  15373. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15374. return internalTexture;
  15375. };
  15376. /**
  15377. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15378. * @param renderTarget The render target to set the frame buffer for
  15379. */
  15380. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15381. // Create the framebuffer
  15382. var internalTexture = renderTarget.getInternalTexture();
  15383. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15384. return;
  15385. }
  15386. var gl = this._gl;
  15387. var depthStencilTexture = renderTarget.depthStencilTexture;
  15388. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15389. if (depthStencilTexture.isCube) {
  15390. if (depthStencilTexture._generateStencilBuffer) {
  15391. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15392. }
  15393. else {
  15394. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15395. }
  15396. }
  15397. else {
  15398. if (depthStencilTexture._generateStencilBuffer) {
  15399. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15400. }
  15401. else {
  15402. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15403. }
  15404. }
  15405. this.bindUnboundFramebuffer(null);
  15406. };
  15407. /**
  15408. * Creates a new render target texture
  15409. * @param size defines the size of the texture
  15410. * @param options defines the options used to create the texture
  15411. * @returns a new render target texture stored in an InternalTexture
  15412. */
  15413. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15414. var fullOptions = new RenderTargetCreationOptions();
  15415. if (options !== undefined && typeof options === "object") {
  15416. fullOptions.generateMipMaps = options.generateMipMaps;
  15417. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15418. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15419. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15420. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15421. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15422. }
  15423. else {
  15424. fullOptions.generateMipMaps = options;
  15425. fullOptions.generateDepthBuffer = true;
  15426. fullOptions.generateStencilBuffer = false;
  15427. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15428. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15429. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15430. }
  15431. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15432. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15433. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15434. }
  15435. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15436. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15437. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15438. }
  15439. var gl = this._gl;
  15440. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15441. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15442. var width = size.width || size;
  15443. var height = size.height || size;
  15444. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15445. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15446. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15447. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15448. }
  15449. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15450. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15451. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15453. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15454. // Create the framebuffer
  15455. var currentFrameBuffer = this._currentFramebuffer;
  15456. var framebuffer = gl.createFramebuffer();
  15457. this.bindUnboundFramebuffer(framebuffer);
  15458. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15459. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15460. if (fullOptions.generateMipMaps) {
  15461. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15462. }
  15463. // Unbind
  15464. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15465. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15466. this.bindUnboundFramebuffer(currentFrameBuffer);
  15467. texture._framebuffer = framebuffer;
  15468. texture.baseWidth = width;
  15469. texture.baseHeight = height;
  15470. texture.width = width;
  15471. texture.height = height;
  15472. texture.isReady = true;
  15473. texture.samples = 1;
  15474. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15475. texture.samplingMode = fullOptions.samplingMode;
  15476. texture.type = fullOptions.type;
  15477. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15478. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15479. // this.resetTextureCache();
  15480. this._internalTexturesCache.push(texture);
  15481. return texture;
  15482. };
  15483. /**
  15484. * Create a multi render target texture
  15485. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15486. * @param size defines the size of the texture
  15487. * @param options defines the creation options
  15488. * @returns the cube texture as an InternalTexture
  15489. */
  15490. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15491. var generateMipMaps = false;
  15492. var generateDepthBuffer = true;
  15493. var generateStencilBuffer = false;
  15494. var generateDepthTexture = false;
  15495. var textureCount = 1;
  15496. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15497. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15498. var types = new Array();
  15499. var samplingModes = new Array();
  15500. if (options !== undefined) {
  15501. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15502. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15503. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15504. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15505. textureCount = options.textureCount || 1;
  15506. if (options.types) {
  15507. types = options.types;
  15508. }
  15509. if (options.samplingModes) {
  15510. samplingModes = options.samplingModes;
  15511. }
  15512. }
  15513. var gl = this._gl;
  15514. // Create the framebuffer
  15515. var framebuffer = gl.createFramebuffer();
  15516. this.bindUnboundFramebuffer(framebuffer);
  15517. var width = size.width || size;
  15518. var height = size.height || size;
  15519. var textures = [];
  15520. var attachments = [];
  15521. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15522. for (var i = 0; i < textureCount; i++) {
  15523. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15524. var type = types[i] || defaultType;
  15525. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15526. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15527. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15528. }
  15529. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15530. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15531. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15532. }
  15533. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15534. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15535. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15536. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15537. }
  15538. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15539. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15540. textures.push(texture);
  15541. attachments.push(attachment);
  15542. gl.activeTexture(gl["TEXTURE" + i]);
  15543. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15544. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15545. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15546. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15547. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15548. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15549. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15550. if (generateMipMaps) {
  15551. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15552. }
  15553. // Unbind
  15554. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15555. texture._framebuffer = framebuffer;
  15556. texture._depthStencilBuffer = depthStencilBuffer;
  15557. texture.baseWidth = width;
  15558. texture.baseHeight = height;
  15559. texture.width = width;
  15560. texture.height = height;
  15561. texture.isReady = true;
  15562. texture.samples = 1;
  15563. texture.generateMipMaps = generateMipMaps;
  15564. texture.samplingMode = samplingMode;
  15565. texture.type = type;
  15566. texture._generateDepthBuffer = generateDepthBuffer;
  15567. texture._generateStencilBuffer = generateStencilBuffer;
  15568. texture._attachments = attachments;
  15569. this._internalTexturesCache.push(texture);
  15570. }
  15571. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15572. // Depth texture
  15573. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15574. gl.activeTexture(gl.TEXTURE0);
  15575. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15576. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15577. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15578. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15579. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15580. 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);
  15581. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15582. depthTexture._framebuffer = framebuffer;
  15583. depthTexture.baseWidth = width;
  15584. depthTexture.baseHeight = height;
  15585. depthTexture.width = width;
  15586. depthTexture.height = height;
  15587. depthTexture.isReady = true;
  15588. depthTexture.samples = 1;
  15589. depthTexture.generateMipMaps = generateMipMaps;
  15590. depthTexture.samplingMode = gl.NEAREST;
  15591. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15592. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15593. textures.push(depthTexture);
  15594. this._internalTexturesCache.push(depthTexture);
  15595. }
  15596. gl.drawBuffers(attachments);
  15597. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15598. this.bindUnboundFramebuffer(null);
  15599. this.resetTextureCache();
  15600. return textures;
  15601. };
  15602. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15603. if (samples === void 0) { samples = 1; }
  15604. var depthStencilBuffer = null;
  15605. var gl = this._gl;
  15606. // Create the depth/stencil buffer
  15607. if (generateStencilBuffer) {
  15608. depthStencilBuffer = gl.createRenderbuffer();
  15609. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15610. if (samples > 1) {
  15611. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15612. }
  15613. else {
  15614. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15615. }
  15616. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15617. }
  15618. else if (generateDepthBuffer) {
  15619. depthStencilBuffer = gl.createRenderbuffer();
  15620. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15621. if (samples > 1) {
  15622. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15623. }
  15624. else {
  15625. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15626. }
  15627. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15628. }
  15629. return depthStencilBuffer;
  15630. };
  15631. /**
  15632. * Updates the sample count of a render target texture
  15633. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15634. * @param texture defines the texture to update
  15635. * @param samples defines the sample count to set
  15636. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15637. */
  15638. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15639. if (this.webGLVersion < 2 || !texture) {
  15640. return 1;
  15641. }
  15642. if (texture.samples === samples) {
  15643. return samples;
  15644. }
  15645. var gl = this._gl;
  15646. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15647. // Dispose previous render buffers
  15648. if (texture._depthStencilBuffer) {
  15649. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15650. texture._depthStencilBuffer = null;
  15651. }
  15652. if (texture._MSAAFramebuffer) {
  15653. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15654. texture._MSAAFramebuffer = null;
  15655. }
  15656. if (texture._MSAARenderBuffer) {
  15657. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15658. texture._MSAARenderBuffer = null;
  15659. }
  15660. if (samples > 1) {
  15661. var framebuffer = gl.createFramebuffer();
  15662. if (!framebuffer) {
  15663. throw new Error("Unable to create multi sampled framebuffer");
  15664. }
  15665. texture._MSAAFramebuffer = framebuffer;
  15666. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15667. var colorRenderbuffer = gl.createRenderbuffer();
  15668. if (!colorRenderbuffer) {
  15669. throw new Error("Unable to create multi sampled framebuffer");
  15670. }
  15671. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15672. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15673. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15674. texture._MSAARenderBuffer = colorRenderbuffer;
  15675. }
  15676. else {
  15677. this.bindUnboundFramebuffer(texture._framebuffer);
  15678. }
  15679. texture.samples = samples;
  15680. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15681. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15682. this.bindUnboundFramebuffer(null);
  15683. return samples;
  15684. };
  15685. /**
  15686. * Update the sample count for a given multiple render target texture
  15687. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15688. * @param textures defines the textures to update
  15689. * @param samples defines the sample count to set
  15690. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15691. */
  15692. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15693. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15694. return 1;
  15695. }
  15696. if (textures[0].samples === samples) {
  15697. return samples;
  15698. }
  15699. var gl = this._gl;
  15700. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15701. // Dispose previous render buffers
  15702. if (textures[0]._depthStencilBuffer) {
  15703. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15704. textures[0]._depthStencilBuffer = null;
  15705. }
  15706. if (textures[0]._MSAAFramebuffer) {
  15707. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15708. textures[0]._MSAAFramebuffer = null;
  15709. }
  15710. for (var i = 0; i < textures.length; i++) {
  15711. if (textures[i]._MSAARenderBuffer) {
  15712. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15713. textures[i]._MSAARenderBuffer = null;
  15714. }
  15715. }
  15716. if (samples > 1) {
  15717. var framebuffer = gl.createFramebuffer();
  15718. if (!framebuffer) {
  15719. throw new Error("Unable to create multi sampled framebuffer");
  15720. }
  15721. this.bindUnboundFramebuffer(framebuffer);
  15722. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15723. var attachments = [];
  15724. for (var i = 0; i < textures.length; i++) {
  15725. var texture = textures[i];
  15726. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15727. var colorRenderbuffer = gl.createRenderbuffer();
  15728. if (!colorRenderbuffer) {
  15729. throw new Error("Unable to create multi sampled framebuffer");
  15730. }
  15731. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15732. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15733. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15734. texture._MSAAFramebuffer = framebuffer;
  15735. texture._MSAARenderBuffer = colorRenderbuffer;
  15736. texture.samples = samples;
  15737. texture._depthStencilBuffer = depthStencilBuffer;
  15738. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15739. attachments.push(attachment);
  15740. }
  15741. gl.drawBuffers(attachments);
  15742. }
  15743. else {
  15744. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15745. }
  15746. this.bindUnboundFramebuffer(null);
  15747. return samples;
  15748. };
  15749. /** @hidden */
  15750. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15751. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15752. };
  15753. /** @hidden */
  15754. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15755. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15756. };
  15757. /** @hidden */
  15758. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15759. var gl = this._gl;
  15760. var textureType = this._getWebGLTextureType(texture.type);
  15761. var format = this._getInternalFormat(texture.format);
  15762. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15763. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15764. this._bindTextureDirectly(bindTarget, texture, true);
  15765. this._unpackFlipY(texture.invertY);
  15766. var target = gl.TEXTURE_2D;
  15767. if (texture.isCube) {
  15768. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15769. }
  15770. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15771. this._bindTextureDirectly(bindTarget, null, true);
  15772. };
  15773. /**
  15774. * Creates a new render target cube texture
  15775. * @param size defines the size of the texture
  15776. * @param options defines the options used to create the texture
  15777. * @returns a new render target cube texture stored in an InternalTexture
  15778. */
  15779. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15780. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15781. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15782. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15783. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15784. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15785. }
  15786. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15787. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15788. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15789. }
  15790. var gl = this._gl;
  15791. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15792. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15793. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15794. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15795. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15796. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15797. }
  15798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15802. for (var face = 0; face < 6; face++) {
  15803. 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);
  15804. }
  15805. // Create the framebuffer
  15806. var framebuffer = gl.createFramebuffer();
  15807. this.bindUnboundFramebuffer(framebuffer);
  15808. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15809. // MipMaps
  15810. if (fullOptions.generateMipMaps) {
  15811. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15812. }
  15813. // Unbind
  15814. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15815. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15816. this.bindUnboundFramebuffer(null);
  15817. texture._framebuffer = framebuffer;
  15818. texture.width = size;
  15819. texture.height = size;
  15820. texture.isReady = true;
  15821. texture.isCube = true;
  15822. texture.samples = 1;
  15823. texture.generateMipMaps = fullOptions.generateMipMaps;
  15824. texture.samplingMode = fullOptions.samplingMode;
  15825. texture.type = fullOptions.type;
  15826. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15827. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15828. this._internalTexturesCache.push(texture);
  15829. return texture;
  15830. };
  15831. /**
  15832. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15833. * @param rootUrl defines the url where the file to load is located
  15834. * @param scene defines the current scene
  15835. * @param lodScale defines scale to apply to the mip map selection
  15836. * @param lodOffset defines offset to apply to the mip map selection
  15837. * @param onLoad defines an optional callback raised when the texture is loaded
  15838. * @param onError defines an optional callback raised if there is an issue to load the texture
  15839. * @param format defines the format of the data
  15840. * @param forcedExtension defines the extension to use to pick the right loader
  15841. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15842. * @returns the cube texture as an InternalTexture
  15843. */
  15844. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15845. var _this = this;
  15846. if (onLoad === void 0) { onLoad = null; }
  15847. if (onError === void 0) { onError = null; }
  15848. if (forcedExtension === void 0) { forcedExtension = null; }
  15849. if (createPolynomials === void 0) { createPolynomials = true; }
  15850. var callback = function (loadData) {
  15851. if (!loadData) {
  15852. if (onLoad) {
  15853. onLoad(null);
  15854. }
  15855. return;
  15856. }
  15857. var texture = loadData.texture;
  15858. if (!createPolynomials) {
  15859. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15860. }
  15861. else if (loadData.info.sphericalPolynomial) {
  15862. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15863. }
  15864. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15865. if (_this._caps.textureLOD) {
  15866. // Do not add extra process if texture lod is supported.
  15867. if (onLoad) {
  15868. onLoad(texture);
  15869. }
  15870. return;
  15871. }
  15872. var mipSlices = 3;
  15873. var gl = _this._gl;
  15874. var width = loadData.width;
  15875. if (!width) {
  15876. return;
  15877. }
  15878. var textures = [];
  15879. for (var i = 0; i < mipSlices; i++) {
  15880. //compute LOD from even spacing in smoothness (matching shader calculation)
  15881. var smoothness = i / (mipSlices - 1);
  15882. var roughness = 1 - smoothness;
  15883. var minLODIndex = lodOffset; // roughness = 0
  15884. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15885. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15886. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15887. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15888. glTextureFromLod.isCube = true;
  15889. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15890. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15891. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15892. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15893. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15894. if (loadData.isDDS) {
  15895. var info = loadData.info;
  15896. var data = loadData.data;
  15897. _this._unpackFlipY(info.isCompressed);
  15898. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15899. }
  15900. else {
  15901. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15902. }
  15903. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15904. // Wrap in a base texture for easy binding.
  15905. var lodTexture = new BABYLON.BaseTexture(scene);
  15906. lodTexture.isCube = true;
  15907. lodTexture._texture = glTextureFromLod;
  15908. glTextureFromLod.isReady = true;
  15909. textures.push(lodTexture);
  15910. }
  15911. texture._lodTextureHigh = textures[2];
  15912. texture._lodTextureMid = textures[1];
  15913. texture._lodTextureLow = textures[0];
  15914. if (onLoad) {
  15915. onLoad(texture);
  15916. }
  15917. };
  15918. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15919. };
  15920. /**
  15921. * Creates a cube texture
  15922. * @param rootUrl defines the url where the files to load is located
  15923. * @param scene defines the current scene
  15924. * @param files defines the list of files to load (1 per face)
  15925. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15926. * @param onLoad defines an optional callback raised when the texture is loaded
  15927. * @param onError defines an optional callback raised if there is an issue to load the texture
  15928. * @param format defines the format of the data
  15929. * @param forcedExtension defines the extension to use to pick the right loader
  15930. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15931. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15932. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15933. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15934. * @returns the cube texture as an InternalTexture
  15935. */
  15936. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15937. var _this = this;
  15938. if (onLoad === void 0) { onLoad = null; }
  15939. if (onError === void 0) { onError = null; }
  15940. if (forcedExtension === void 0) { forcedExtension = null; }
  15941. if (createPolynomials === void 0) { createPolynomials = false; }
  15942. if (lodScale === void 0) { lodScale = 0; }
  15943. if (lodOffset === void 0) { lodOffset = 0; }
  15944. if (fallback === void 0) { fallback = null; }
  15945. var gl = this._gl;
  15946. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15947. texture.isCube = true;
  15948. texture.url = rootUrl;
  15949. texture.generateMipMaps = !noMipmap;
  15950. texture._lodGenerationScale = lodScale;
  15951. texture._lodGenerationOffset = lodOffset;
  15952. if (!this._doNotHandleContextLost) {
  15953. texture._extension = forcedExtension;
  15954. texture._files = files;
  15955. }
  15956. var isKTX = false;
  15957. var isDDS = false;
  15958. var isEnv = false;
  15959. var lastDot = rootUrl.lastIndexOf('.');
  15960. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15961. if (this._textureFormatInUse && !fallback) {
  15962. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15963. isKTX = true;
  15964. }
  15965. else {
  15966. isDDS = (extension === ".dds");
  15967. isEnv = (extension === ".env");
  15968. }
  15969. var onerror = function (request, exception) {
  15970. if (isKTX) {
  15971. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15972. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15973. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15974. }
  15975. if (onError && request) {
  15976. onError(request.status + " " + request.statusText, exception);
  15977. }
  15978. };
  15979. if (isKTX) {
  15980. this._loadFile(rootUrl, function (data) {
  15981. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15982. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15983. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15984. _this._unpackFlipY(true);
  15985. ktx.uploadLevels(_this._gl, !noMipmap);
  15986. _this.setCubeMapTextureParams(gl, loadMipmap);
  15987. texture.width = ktx.pixelWidth;
  15988. texture.height = ktx.pixelHeight;
  15989. texture.isReady = true;
  15990. }, undefined, undefined, true, onerror);
  15991. }
  15992. else if (isEnv) {
  15993. this._loadFile(rootUrl, function (data) {
  15994. data = data;
  15995. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15996. if (info) {
  15997. texture.width = info.width;
  15998. texture.height = info.width;
  15999. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  16000. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  16001. texture.isReady = true;
  16002. if (onLoad) {
  16003. onLoad();
  16004. }
  16005. });
  16006. }
  16007. else if (onError) {
  16008. onError("Can not parse the environment file", null);
  16009. }
  16010. }, undefined, undefined, true, onerror);
  16011. }
  16012. else if (isDDS) {
  16013. if (files && files.length === 6) {
  16014. this._cascadeLoadFiles(scene, function (imgs) {
  16015. var info;
  16016. var loadMipmap = false;
  16017. var width = 0;
  16018. for (var index = 0; index < imgs.length; index++) {
  16019. var data = imgs[index];
  16020. info = BABYLON.DDSTools.GetDDSInfo(data);
  16021. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  16022. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16023. _this._unpackFlipY(info.isCompressed);
  16024. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  16025. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  16026. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16027. }
  16028. texture.width = info.width;
  16029. texture.height = info.height;
  16030. texture.type = info.textureType;
  16031. width = info.width;
  16032. }
  16033. _this.setCubeMapTextureParams(gl, loadMipmap);
  16034. texture.isReady = true;
  16035. if (onLoad) {
  16036. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  16037. }
  16038. }, files, onError);
  16039. }
  16040. else {
  16041. this._loadFile(rootUrl, function (data) {
  16042. var info = BABYLON.DDSTools.GetDDSInfo(data);
  16043. if (createPolynomials) {
  16044. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16045. }
  16046. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  16047. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16048. _this._unpackFlipY(info.isCompressed);
  16049. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  16050. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  16051. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16052. }
  16053. _this.setCubeMapTextureParams(gl, loadMipmap);
  16054. texture.width = info.width;
  16055. texture.height = info.height;
  16056. texture.isReady = true;
  16057. texture.type = info.textureType;
  16058. if (onLoad) {
  16059. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  16060. }
  16061. }, undefined, undefined, true, onerror);
  16062. }
  16063. }
  16064. else {
  16065. if (!files) {
  16066. throw new Error("Cannot load cubemap because files were not defined");
  16067. }
  16068. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16069. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16070. var height = width;
  16071. _this._prepareWorkingCanvas();
  16072. if (!_this._workingCanvas || !_this._workingContext) {
  16073. return;
  16074. }
  16075. _this._workingCanvas.width = width;
  16076. _this._workingCanvas.height = height;
  16077. var faces = [
  16078. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16079. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16080. ];
  16081. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16082. _this._unpackFlipY(false);
  16083. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16084. for (var index = 0; index < faces.length; index++) {
  16085. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16086. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16087. }
  16088. if (!noMipmap) {
  16089. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16090. }
  16091. _this.setCubeMapTextureParams(gl, !noMipmap);
  16092. texture.width = width;
  16093. texture.height = height;
  16094. texture.isReady = true;
  16095. if (format) {
  16096. texture.format = format;
  16097. }
  16098. texture.onLoadedObservable.notifyObservers(texture);
  16099. texture.onLoadedObservable.clear();
  16100. if (onLoad) {
  16101. onLoad();
  16102. }
  16103. }, files, onError);
  16104. }
  16105. this._internalTexturesCache.push(texture);
  16106. return texture;
  16107. };
  16108. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  16109. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16110. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16111. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16113. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16114. // this.resetTextureCache();
  16115. };
  16116. /**
  16117. * Update a raw cube texture
  16118. * @param texture defines the texture to udpdate
  16119. * @param data defines the data to store
  16120. * @param format defines the data format
  16121. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16122. * @param invertY defines if data must be stored with Y axis inverted
  16123. * @param compression defines the compression used (null by default)
  16124. * @param level defines which level of the texture to update
  16125. */
  16126. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16127. if (compression === void 0) { compression = null; }
  16128. if (level === void 0) { level = 0; }
  16129. texture._bufferViewArray = data;
  16130. texture.format = format;
  16131. texture.type = type;
  16132. texture.invertY = invertY;
  16133. texture._compression = compression;
  16134. var gl = this._gl;
  16135. var textureType = this._getWebGLTextureType(type);
  16136. var internalFormat = this._getInternalFormat(format);
  16137. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16138. var needConversion = false;
  16139. if (internalFormat === gl.RGB) {
  16140. internalFormat = gl.RGBA;
  16141. needConversion = true;
  16142. }
  16143. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16144. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16145. if (texture.width % 4 !== 0) {
  16146. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16147. }
  16148. // Data are known to be in +X +Y +Z -X -Y -Z
  16149. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16150. var faceData = data[faceIndex];
  16151. if (compression) {
  16152. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16153. }
  16154. else {
  16155. if (needConversion) {
  16156. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16157. }
  16158. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16159. }
  16160. }
  16161. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16162. if (isPot && texture.generateMipMaps && level === 0) {
  16163. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16164. }
  16165. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16166. // this.resetTextureCache();
  16167. texture.isReady = true;
  16168. };
  16169. /**
  16170. * Creates a new raw cube texture
  16171. * @param data defines the array of data to use to create each face
  16172. * @param size defines the size of the textures
  16173. * @param format defines the format of the data
  16174. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16175. * @param generateMipMaps defines if the engine should generate the mip levels
  16176. * @param invertY defines if data must be stored with Y axis inverted
  16177. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16178. * @param compression defines the compression used (null by default)
  16179. * @returns the cube texture as an InternalTexture
  16180. */
  16181. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16182. if (compression === void 0) { compression = null; }
  16183. var gl = this._gl;
  16184. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16185. texture.isCube = true;
  16186. texture.generateMipMaps = generateMipMaps;
  16187. texture.format = format;
  16188. texture.type = type;
  16189. if (!this._doNotHandleContextLost) {
  16190. texture._bufferViewArray = data;
  16191. }
  16192. var textureType = this._getWebGLTextureType(type);
  16193. var internalFormat = this._getInternalFormat(format);
  16194. if (internalFormat === gl.RGB) {
  16195. internalFormat = gl.RGBA;
  16196. }
  16197. var width = size;
  16198. var height = width;
  16199. texture.width = width;
  16200. texture.height = height;
  16201. // Double check on POT to generate Mips.
  16202. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16203. if (!isPot) {
  16204. generateMipMaps = false;
  16205. }
  16206. // Upload data if needed. The texture won't be ready until then.
  16207. if (data) {
  16208. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16209. }
  16210. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16211. // Filters
  16212. if (data && generateMipMaps) {
  16213. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16214. }
  16215. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16216. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16217. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16218. }
  16219. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16221. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16222. }
  16223. else {
  16224. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16227. }
  16228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16229. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16230. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16231. return texture;
  16232. };
  16233. /**
  16234. * Creates a new raw cube texture from a specified url
  16235. * @param url defines the url where the data is located
  16236. * @param scene defines the current scene
  16237. * @param size defines the size of the textures
  16238. * @param format defines the format of the data
  16239. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16240. * @param noMipmap defines if the engine should avoid generating the mip levels
  16241. * @param callback defines a callback used to extract texture data from loaded data
  16242. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16243. * @param onLoad defines a callback called when texture is loaded
  16244. * @param onError defines a callback called if there is an error
  16245. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16246. * @param invertY defines if data must be stored with Y axis inverted
  16247. * @returns the cube texture as an InternalTexture
  16248. */
  16249. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16250. var _this = this;
  16251. if (onLoad === void 0) { onLoad = null; }
  16252. if (onError === void 0) { onError = null; }
  16253. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16254. if (invertY === void 0) { invertY = false; }
  16255. var gl = this._gl;
  16256. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16257. scene._addPendingData(texture);
  16258. texture.url = url;
  16259. this._internalTexturesCache.push(texture);
  16260. var onerror = function (request, exception) {
  16261. scene._removePendingData(texture);
  16262. if (onError && request) {
  16263. onError(request.status + " " + request.statusText, exception);
  16264. }
  16265. };
  16266. var internalCallback = function (data) {
  16267. var width = texture.width;
  16268. var faceDataArrays = callback(data);
  16269. if (!faceDataArrays) {
  16270. return;
  16271. }
  16272. if (mipmapGenerator) {
  16273. var textureType = _this._getWebGLTextureType(type);
  16274. var internalFormat = _this._getInternalFormat(format);
  16275. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16276. var needConversion = false;
  16277. if (internalFormat === gl.RGB) {
  16278. internalFormat = gl.RGBA;
  16279. needConversion = true;
  16280. }
  16281. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16282. _this._unpackFlipY(false);
  16283. var mipData = mipmapGenerator(faceDataArrays);
  16284. for (var level = 0; level < mipData.length; level++) {
  16285. var mipSize = width >> level;
  16286. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16287. var mipFaceData = mipData[level][faceIndex];
  16288. if (needConversion) {
  16289. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16290. }
  16291. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16292. }
  16293. }
  16294. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16295. }
  16296. else {
  16297. texture.generateMipMaps = !noMipmap;
  16298. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16299. }
  16300. texture.isReady = true;
  16301. // this.resetTextureCache();
  16302. scene._removePendingData(texture);
  16303. if (onLoad) {
  16304. onLoad();
  16305. }
  16306. };
  16307. this._loadFile(url, function (data) {
  16308. internalCallback(data);
  16309. }, undefined, scene.database, true, onerror);
  16310. return texture;
  16311. };
  16312. ;
  16313. /**
  16314. * Update a raw 3D texture
  16315. * @param texture defines the texture to update
  16316. * @param data defines the data to store
  16317. * @param format defines the data format
  16318. * @param invertY defines if data must be stored with Y axis inverted
  16319. * @param compression defines the used compression (can be null)
  16320. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16321. */
  16322. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16323. if (compression === void 0) { compression = null; }
  16324. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16325. var internalType = this._getWebGLTextureType(textureType);
  16326. var internalFormat = this._getInternalFormat(format);
  16327. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16328. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16329. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16330. if (!this._doNotHandleContextLost) {
  16331. texture._bufferView = data;
  16332. texture.format = format;
  16333. texture.invertY = invertY;
  16334. texture._compression = compression;
  16335. }
  16336. if (texture.width % 4 !== 0) {
  16337. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16338. }
  16339. if (compression && data) {
  16340. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16341. }
  16342. else {
  16343. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16344. }
  16345. if (texture.generateMipMaps) {
  16346. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16347. }
  16348. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16349. // this.resetTextureCache();
  16350. texture.isReady = true;
  16351. };
  16352. /**
  16353. * Creates a new raw 3D texture
  16354. * @param data defines the data used to create the texture
  16355. * @param width defines the width of the texture
  16356. * @param height defines the height of the texture
  16357. * @param depth defines the depth of the texture
  16358. * @param format defines the format of the texture
  16359. * @param generateMipMaps defines if the engine must generate mip levels
  16360. * @param invertY defines if data must be stored with Y axis inverted
  16361. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16362. * @param compression defines the compressed used (can be null)
  16363. * @param textureType defines the compressed used (can be null)
  16364. * @returns a new raw 3D texture (stored in an InternalTexture)
  16365. */
  16366. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16367. if (compression === void 0) { compression = null; }
  16368. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16369. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16370. texture.baseWidth = width;
  16371. texture.baseHeight = height;
  16372. texture.baseDepth = depth;
  16373. texture.width = width;
  16374. texture.height = height;
  16375. texture.depth = depth;
  16376. texture.format = format;
  16377. texture.type = textureType;
  16378. texture.generateMipMaps = generateMipMaps;
  16379. texture.samplingMode = samplingMode;
  16380. texture.is3D = true;
  16381. if (!this._doNotHandleContextLost) {
  16382. texture._bufferView = data;
  16383. }
  16384. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16385. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16386. // Filters
  16387. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16388. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16389. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16390. if (generateMipMaps) {
  16391. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16392. }
  16393. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16394. this._internalTexturesCache.push(texture);
  16395. return texture;
  16396. };
  16397. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16398. var gl = this._gl;
  16399. if (!gl) {
  16400. return;
  16401. }
  16402. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16403. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16404. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16405. if (!noMipmap && !isCompressed) {
  16406. gl.generateMipmap(gl.TEXTURE_2D);
  16407. }
  16408. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16409. // this.resetTextureCache();
  16410. if (scene) {
  16411. scene._removePendingData(texture);
  16412. }
  16413. texture.onLoadedObservable.notifyObservers(texture);
  16414. texture.onLoadedObservable.clear();
  16415. };
  16416. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16417. var _this = this;
  16418. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16419. var maxTextureSize = this.getCaps().maxTextureSize;
  16420. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16421. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16422. var gl = this._gl;
  16423. if (!gl) {
  16424. return;
  16425. }
  16426. if (!texture._webGLTexture) {
  16427. // this.resetTextureCache();
  16428. if (scene) {
  16429. scene._removePendingData(texture);
  16430. }
  16431. return;
  16432. }
  16433. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16434. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16435. texture.baseWidth = width;
  16436. texture.baseHeight = height;
  16437. texture.width = potWidth;
  16438. texture.height = potHeight;
  16439. texture.isReady = true;
  16440. if (processFunction(potWidth, potHeight, function () {
  16441. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16442. })) {
  16443. // Returning as texture needs extra async steps
  16444. return;
  16445. }
  16446. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16447. };
  16448. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16449. // Create new RGBA data container.
  16450. var rgbaData;
  16451. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16452. rgbaData = new Float32Array(width * height * 4);
  16453. }
  16454. else {
  16455. rgbaData = new Uint32Array(width * height * 4);
  16456. }
  16457. // Convert each pixel.
  16458. for (var x = 0; x < width; x++) {
  16459. for (var y = 0; y < height; y++) {
  16460. var index = (y * width + x) * 3;
  16461. var newIndex = (y * width + x) * 4;
  16462. // Map Old Value to new value.
  16463. rgbaData[newIndex + 0] = rgbData[index + 0];
  16464. rgbaData[newIndex + 1] = rgbData[index + 1];
  16465. rgbaData[newIndex + 2] = rgbData[index + 2];
  16466. // Add fully opaque alpha channel.
  16467. rgbaData[newIndex + 3] = 1;
  16468. }
  16469. }
  16470. return rgbaData;
  16471. };
  16472. /** @hidden */
  16473. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16474. var gl = this._gl;
  16475. if (texture._framebuffer) {
  16476. gl.deleteFramebuffer(texture._framebuffer);
  16477. texture._framebuffer = null;
  16478. }
  16479. if (texture._depthStencilBuffer) {
  16480. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16481. texture._depthStencilBuffer = null;
  16482. }
  16483. if (texture._MSAAFramebuffer) {
  16484. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16485. texture._MSAAFramebuffer = null;
  16486. }
  16487. if (texture._MSAARenderBuffer) {
  16488. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16489. texture._MSAARenderBuffer = null;
  16490. }
  16491. };
  16492. /** @hidden */
  16493. Engine.prototype._releaseTexture = function (texture) {
  16494. var gl = this._gl;
  16495. this._releaseFramebufferObjects(texture);
  16496. gl.deleteTexture(texture._webGLTexture);
  16497. // Unbind channels
  16498. this.unbindAllTextures();
  16499. var index = this._internalTexturesCache.indexOf(texture);
  16500. if (index !== -1) {
  16501. this._internalTexturesCache.splice(index, 1);
  16502. }
  16503. // Integrated fixed lod samplers.
  16504. if (texture._lodTextureHigh) {
  16505. texture._lodTextureHigh.dispose();
  16506. }
  16507. if (texture._lodTextureMid) {
  16508. texture._lodTextureMid.dispose();
  16509. }
  16510. if (texture._lodTextureLow) {
  16511. texture._lodTextureLow.dispose();
  16512. }
  16513. // Set output texture of post process to null if the texture has been released/disposed
  16514. this.scenes.forEach(function (scene) {
  16515. scene.postProcesses.forEach(function (postProcess) {
  16516. if (postProcess._outputTexture == texture) {
  16517. postProcess._outputTexture = null;
  16518. }
  16519. });
  16520. scene.cameras.forEach(function (camera) {
  16521. camera._postProcesses.forEach(function (postProcess) {
  16522. if (postProcess) {
  16523. if (postProcess._outputTexture == texture) {
  16524. postProcess._outputTexture = null;
  16525. }
  16526. }
  16527. });
  16528. });
  16529. });
  16530. };
  16531. Engine.prototype.setProgram = function (program) {
  16532. if (this._currentProgram !== program) {
  16533. this._gl.useProgram(program);
  16534. this._currentProgram = program;
  16535. }
  16536. };
  16537. /**
  16538. * Binds an effect to the webGL context
  16539. * @param effect defines the effect to bind
  16540. */
  16541. Engine.prototype.bindSamplers = function (effect) {
  16542. this.setProgram(effect.getProgram());
  16543. var samplers = effect.getSamplers();
  16544. for (var index = 0; index < samplers.length; index++) {
  16545. var uniform = effect.getUniform(samplers[index]);
  16546. if (uniform) {
  16547. this._boundUniforms[index] = uniform;
  16548. }
  16549. }
  16550. this._currentEffect = null;
  16551. };
  16552. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16553. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16554. return;
  16555. }
  16556. // Remove
  16557. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16558. // Bind last to it
  16559. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16560. // Bind to dummy
  16561. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16562. };
  16563. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16564. if (!internalTexture) {
  16565. return -1;
  16566. }
  16567. internalTexture._initialSlot = channel;
  16568. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16569. if (channel !== internalTexture._designatedSlot) {
  16570. this._textureCollisions.addCount(1, false);
  16571. }
  16572. }
  16573. else {
  16574. if (channel !== internalTexture._designatedSlot) {
  16575. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16576. return internalTexture._designatedSlot;
  16577. }
  16578. else {
  16579. // No slot for this texture, let's pick a new one (if we find a free slot)
  16580. if (this._nextFreeTextureSlots.length) {
  16581. return this._nextFreeTextureSlots[0];
  16582. }
  16583. // We need to recycle the oldest bound texture, sorry.
  16584. this._textureCollisions.addCount(1, false);
  16585. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16586. }
  16587. }
  16588. }
  16589. return channel;
  16590. };
  16591. Engine.prototype._linkTrackers = function (previous, next) {
  16592. previous.next = next;
  16593. next.previous = previous;
  16594. };
  16595. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16596. var currentSlot = internalTexture._designatedSlot;
  16597. if (currentSlot === -1) {
  16598. return -1;
  16599. }
  16600. internalTexture._designatedSlot = -1;
  16601. if (this.disableTextureBindingOptimization) {
  16602. return -1;
  16603. }
  16604. // Remove from bound list
  16605. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16606. // Free the slot
  16607. this._boundTexturesCache[currentSlot] = null;
  16608. this._nextFreeTextureSlots.push(currentSlot);
  16609. return currentSlot;
  16610. };
  16611. Engine.prototype._activateCurrentTexture = function () {
  16612. if (this._currentTextureChannel !== this._activeChannel) {
  16613. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16614. this._currentTextureChannel = this._activeChannel;
  16615. }
  16616. };
  16617. /** @hidden */
  16618. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16619. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16620. if (force === void 0) { force = false; }
  16621. var wasPreviouslyBound = false;
  16622. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16623. this._activeChannel = texture._designatedSlot;
  16624. }
  16625. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16626. var isTextureForRendering = texture && texture._initialSlot > -1;
  16627. if (currentTextureBound !== texture || force) {
  16628. if (currentTextureBound) {
  16629. this._removeDesignatedSlot(currentTextureBound);
  16630. }
  16631. this._activateCurrentTexture();
  16632. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16633. this._boundTexturesCache[this._activeChannel] = texture;
  16634. if (texture) {
  16635. if (!this.disableTextureBindingOptimization) {
  16636. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16637. if (slotIndex > -1) {
  16638. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16639. }
  16640. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16641. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16642. }
  16643. texture._designatedSlot = this._activeChannel;
  16644. }
  16645. }
  16646. else if (forTextureDataUpdate) {
  16647. wasPreviouslyBound = true;
  16648. this._activateCurrentTexture();
  16649. }
  16650. if (isTextureForRendering && !forTextureDataUpdate) {
  16651. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16652. }
  16653. return wasPreviouslyBound;
  16654. };
  16655. /** @hidden */
  16656. Engine.prototype._bindTexture = function (channel, texture) {
  16657. if (channel < 0) {
  16658. return;
  16659. }
  16660. if (texture) {
  16661. channel = this._getCorrectTextureChannel(channel, texture);
  16662. }
  16663. this._activeChannel = channel;
  16664. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16665. };
  16666. /**
  16667. * Sets a texture to the webGL context from a postprocess
  16668. * @param channel defines the channel to use
  16669. * @param postProcess defines the source postprocess
  16670. */
  16671. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16672. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16673. };
  16674. /**
  16675. * Binds the output of the passed in post process to the texture channel specified
  16676. * @param channel The channel the texture should be bound to
  16677. * @param postProcess The post process which's output should be bound
  16678. */
  16679. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16680. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16681. };
  16682. /**
  16683. * Unbind all textures from the webGL context
  16684. */
  16685. Engine.prototype.unbindAllTextures = function () {
  16686. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16687. this._activeChannel = channel;
  16688. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16689. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16690. if (this.webGLVersion > 1) {
  16691. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16692. }
  16693. }
  16694. };
  16695. /**
  16696. * Sets a texture to the according uniform.
  16697. * @param channel The texture channel
  16698. * @param uniform The uniform to set
  16699. * @param texture The texture to apply
  16700. */
  16701. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16702. if (channel < 0) {
  16703. return;
  16704. }
  16705. if (uniform) {
  16706. this._boundUniforms[channel] = uniform;
  16707. }
  16708. this._setTexture(channel, texture);
  16709. };
  16710. /**
  16711. * Sets a depth stencil texture from a render target to the according uniform.
  16712. * @param channel The texture channel
  16713. * @param uniform The uniform to set
  16714. * @param texture The render target texture containing the depth stencil texture to apply
  16715. */
  16716. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16717. if (channel < 0) {
  16718. return;
  16719. }
  16720. if (uniform) {
  16721. this._boundUniforms[channel] = uniform;
  16722. }
  16723. if (!texture || !texture.depthStencilTexture) {
  16724. this._setTexture(channel, null);
  16725. }
  16726. else {
  16727. this._setTexture(channel, texture, false, true);
  16728. }
  16729. };
  16730. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16731. var uniform = this._boundUniforms[sourceSlot];
  16732. if (uniform._currentState === destination) {
  16733. return;
  16734. }
  16735. this._gl.uniform1i(uniform, destination);
  16736. uniform._currentState = destination;
  16737. };
  16738. Engine.prototype._getTextureWrapMode = function (mode) {
  16739. switch (mode) {
  16740. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16741. return this._gl.REPEAT;
  16742. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16743. return this._gl.CLAMP_TO_EDGE;
  16744. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16745. return this._gl.MIRRORED_REPEAT;
  16746. }
  16747. return this._gl.REPEAT;
  16748. };
  16749. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16750. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16751. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16752. // Not ready?
  16753. if (!texture) {
  16754. if (this._boundTexturesCache[channel] != null) {
  16755. this._activeChannel = channel;
  16756. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16757. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16758. if (this.webGLVersion > 1) {
  16759. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16760. }
  16761. }
  16762. return false;
  16763. }
  16764. // Video
  16765. if (texture.video) {
  16766. this._activeChannel = channel;
  16767. texture.update();
  16768. }
  16769. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16770. texture.delayLoad();
  16771. return false;
  16772. }
  16773. var internalTexture;
  16774. if (depthStencilTexture) {
  16775. internalTexture = texture.depthStencilTexture;
  16776. }
  16777. else if (texture.isReady()) {
  16778. internalTexture = texture.getInternalTexture();
  16779. }
  16780. else if (texture.isCube) {
  16781. internalTexture = this.emptyCubeTexture;
  16782. }
  16783. else if (texture.is3D) {
  16784. internalTexture = this.emptyTexture3D;
  16785. }
  16786. else {
  16787. internalTexture = this.emptyTexture;
  16788. }
  16789. if (!isPartOfTextureArray) {
  16790. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16791. }
  16792. var needToBind = true;
  16793. if (this._boundTexturesCache[channel] === internalTexture) {
  16794. this._moveBoundTextureOnTop(internalTexture);
  16795. if (!isPartOfTextureArray) {
  16796. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16797. }
  16798. needToBind = false;
  16799. }
  16800. this._activeChannel = channel;
  16801. if (internalTexture && internalTexture.is3D) {
  16802. if (needToBind) {
  16803. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16804. }
  16805. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16806. internalTexture._cachedWrapU = texture.wrapU;
  16807. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16808. }
  16809. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16810. internalTexture._cachedWrapV = texture.wrapV;
  16811. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16812. }
  16813. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16814. internalTexture._cachedWrapR = texture.wrapR;
  16815. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16816. }
  16817. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16818. }
  16819. else if (internalTexture && internalTexture.isCube) {
  16820. if (needToBind) {
  16821. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16822. }
  16823. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16824. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16825. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16826. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16827. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16828. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16829. }
  16830. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16831. }
  16832. else {
  16833. if (needToBind) {
  16834. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16835. }
  16836. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16837. internalTexture._cachedWrapU = texture.wrapU;
  16838. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16839. }
  16840. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16841. internalTexture._cachedWrapV = texture.wrapV;
  16842. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16843. }
  16844. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16845. }
  16846. return true;
  16847. };
  16848. /**
  16849. * Sets an array of texture to the webGL context
  16850. * @param channel defines the channel where the texture array must be set
  16851. * @param uniform defines the associated uniform location
  16852. * @param textures defines the array of textures to bind
  16853. */
  16854. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16855. if (channel < 0 || !uniform) {
  16856. return;
  16857. }
  16858. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16859. this._textureUnits = new Int32Array(textures.length);
  16860. }
  16861. for (var i = 0; i < textures.length; i++) {
  16862. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16863. }
  16864. this._gl.uniform1iv(uniform, this._textureUnits);
  16865. for (var index = 0; index < textures.length; index++) {
  16866. this._setTexture(this._textureUnits[index], textures[index], true);
  16867. }
  16868. };
  16869. /** @hidden */
  16870. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16871. var internalTexture = texture.getInternalTexture();
  16872. if (!internalTexture) {
  16873. return;
  16874. }
  16875. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16876. var value = texture.anisotropicFilteringLevel;
  16877. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16878. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16879. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16880. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16881. }
  16882. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16883. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16884. internalTexture._cachedAnisotropicFilteringLevel = value;
  16885. }
  16886. };
  16887. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16888. this._bindTextureDirectly(target, texture, true, true);
  16889. this._gl.texParameterf(target, parameter, value);
  16890. };
  16891. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16892. if (texture) {
  16893. this._bindTextureDirectly(target, texture, true, true);
  16894. }
  16895. this._gl.texParameteri(target, parameter, value);
  16896. };
  16897. /**
  16898. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16899. * @param x defines the x coordinate of the rectangle where pixels must be read
  16900. * @param y defines the y coordinate of the rectangle where pixels must be read
  16901. * @param width defines the width of the rectangle where pixels must be read
  16902. * @param height defines the height of the rectangle where pixels must be read
  16903. * @returns a Uint8Array containing RGBA colors
  16904. */
  16905. Engine.prototype.readPixels = function (x, y, width, height) {
  16906. var data = new Uint8Array(height * width * 4);
  16907. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16908. return data;
  16909. };
  16910. /**
  16911. * Add an externaly attached data from its key.
  16912. * This method call will fail and return false, if such key already exists.
  16913. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16914. * @param key the unique key that identifies the data
  16915. * @param data the data object to associate to the key for this Engine instance
  16916. * @return true if no such key were already present and the data was added successfully, false otherwise
  16917. */
  16918. Engine.prototype.addExternalData = function (key, data) {
  16919. if (!this._externalData) {
  16920. this._externalData = new BABYLON.StringDictionary();
  16921. }
  16922. return this._externalData.add(key, data);
  16923. };
  16924. /**
  16925. * Get an externaly attached data from its key
  16926. * @param key the unique key that identifies the data
  16927. * @return the associated data, if present (can be null), or undefined if not present
  16928. */
  16929. Engine.prototype.getExternalData = function (key) {
  16930. if (!this._externalData) {
  16931. this._externalData = new BABYLON.StringDictionary();
  16932. }
  16933. return this._externalData.get(key);
  16934. };
  16935. /**
  16936. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16937. * @param key the unique key that identifies the data
  16938. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16939. * @return the associated data, can be null if the factory returned null.
  16940. */
  16941. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16942. if (!this._externalData) {
  16943. this._externalData = new BABYLON.StringDictionary();
  16944. }
  16945. return this._externalData.getOrAddWithFactory(key, factory);
  16946. };
  16947. /**
  16948. * Remove an externaly attached data from the Engine instance
  16949. * @param key the unique key that identifies the data
  16950. * @return true if the data was successfully removed, false if it doesn't exist
  16951. */
  16952. Engine.prototype.removeExternalData = function (key) {
  16953. if (!this._externalData) {
  16954. this._externalData = new BABYLON.StringDictionary();
  16955. }
  16956. return this._externalData.remove(key);
  16957. };
  16958. /**
  16959. * Unbind all vertex attributes from the webGL context
  16960. */
  16961. Engine.prototype.unbindAllAttributes = function () {
  16962. if (this._mustWipeVertexAttributes) {
  16963. this._mustWipeVertexAttributes = false;
  16964. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16965. this._gl.disableVertexAttribArray(i);
  16966. this._vertexAttribArraysEnabled[i] = false;
  16967. this._currentBufferPointers[i].active = false;
  16968. }
  16969. return;
  16970. }
  16971. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16972. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16973. continue;
  16974. }
  16975. this._gl.disableVertexAttribArray(i);
  16976. this._vertexAttribArraysEnabled[i] = false;
  16977. this._currentBufferPointers[i].active = false;
  16978. }
  16979. };
  16980. /**
  16981. * 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
  16982. */
  16983. Engine.prototype.releaseEffects = function () {
  16984. for (var name in this._compiledEffects) {
  16985. this._deleteProgram(this._compiledEffects[name]._program);
  16986. }
  16987. this._compiledEffects = {};
  16988. };
  16989. /**
  16990. * Dispose and release all associated resources
  16991. */
  16992. Engine.prototype.dispose = function () {
  16993. this.hideLoadingUI();
  16994. this.stopRenderLoop();
  16995. // Release postProcesses
  16996. while (this.postProcesses.length) {
  16997. this.postProcesses[0].dispose();
  16998. }
  16999. // Empty texture
  17000. if (this._emptyTexture) {
  17001. this._releaseTexture(this._emptyTexture);
  17002. this._emptyTexture = null;
  17003. }
  17004. if (this._emptyCubeTexture) {
  17005. this._releaseTexture(this._emptyCubeTexture);
  17006. this._emptyCubeTexture = null;
  17007. }
  17008. // Rescale PP
  17009. if (this._rescalePostProcess) {
  17010. this._rescalePostProcess.dispose();
  17011. }
  17012. // Release scenes
  17013. while (this.scenes.length) {
  17014. this.scenes[0].dispose();
  17015. }
  17016. // Release audio engine
  17017. if (Engine.audioEngine) {
  17018. Engine.audioEngine.dispose();
  17019. }
  17020. // Release effects
  17021. this.releaseEffects();
  17022. // Unbind
  17023. this.unbindAllAttributes();
  17024. this._boundUniforms = [];
  17025. if (this._dummyFramebuffer) {
  17026. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17027. }
  17028. //WebVR
  17029. this.disableVR();
  17030. // Events
  17031. if (BABYLON.Tools.IsWindowObjectExist()) {
  17032. window.removeEventListener("blur", this._onBlur);
  17033. window.removeEventListener("focus", this._onFocus);
  17034. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17035. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17036. if (this._renderingCanvas) {
  17037. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17038. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17039. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17040. if (!this._doNotHandleContextLost) {
  17041. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17042. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17043. }
  17044. }
  17045. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17046. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17047. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17048. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17049. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17050. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17051. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17052. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17053. if (this._onVrDisplayConnect) {
  17054. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17055. if (this._onVrDisplayDisconnect) {
  17056. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17057. }
  17058. if (this._onVrDisplayPresentChange) {
  17059. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17060. }
  17061. this._onVrDisplayConnect = null;
  17062. this._onVrDisplayDisconnect = null;
  17063. }
  17064. }
  17065. // Remove from Instances
  17066. var index = Engine.Instances.indexOf(this);
  17067. if (index >= 0) {
  17068. Engine.Instances.splice(index, 1);
  17069. }
  17070. this._workingCanvas = null;
  17071. this._workingContext = null;
  17072. this._currentBufferPointers = [];
  17073. this._renderingCanvas = null;
  17074. this._currentProgram = null;
  17075. this._bindedRenderFunction = null;
  17076. this.onResizeObservable.clear();
  17077. this.onCanvasBlurObservable.clear();
  17078. this.onCanvasFocusObservable.clear();
  17079. this.onCanvasPointerOutObservable.clear();
  17080. this.onBeginFrameObservable.clear();
  17081. this.onEndFrameObservable.clear();
  17082. BABYLON.Effect.ResetCache();
  17083. // Abort active requests
  17084. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17085. var request = _a[_i];
  17086. request.abort();
  17087. }
  17088. };
  17089. // Loading screen
  17090. /**
  17091. * Display the loading screen
  17092. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17093. */
  17094. Engine.prototype.displayLoadingUI = function () {
  17095. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17096. return;
  17097. }
  17098. var loadingScreen = this.loadingScreen;
  17099. if (loadingScreen) {
  17100. loadingScreen.displayLoadingUI();
  17101. }
  17102. };
  17103. /**
  17104. * Hide the loading screen
  17105. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17106. */
  17107. Engine.prototype.hideLoadingUI = function () {
  17108. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17109. return;
  17110. }
  17111. var loadingScreen = this.loadingScreen;
  17112. if (loadingScreen) {
  17113. loadingScreen.hideLoadingUI();
  17114. }
  17115. };
  17116. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17117. /**
  17118. * Gets the current loading screen object
  17119. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17120. */
  17121. get: function () {
  17122. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17123. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17124. return this._loadingScreen;
  17125. },
  17126. /**
  17127. * Sets the current loading screen object
  17128. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17129. */
  17130. set: function (loadingScreen) {
  17131. this._loadingScreen = loadingScreen;
  17132. },
  17133. enumerable: true,
  17134. configurable: true
  17135. });
  17136. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17137. /**
  17138. * Sets the current loading screen text
  17139. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17140. */
  17141. set: function (text) {
  17142. this.loadingScreen.loadingUIText = text;
  17143. },
  17144. enumerable: true,
  17145. configurable: true
  17146. });
  17147. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17148. /**
  17149. * Sets the current loading screen background color
  17150. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17151. */
  17152. set: function (color) {
  17153. this.loadingScreen.loadingUIBackgroundColor = color;
  17154. },
  17155. enumerable: true,
  17156. configurable: true
  17157. });
  17158. /**
  17159. * Attach a new callback raised when context lost event is fired
  17160. * @param callback defines the callback to call
  17161. */
  17162. Engine.prototype.attachContextLostEvent = function (callback) {
  17163. if (this._renderingCanvas) {
  17164. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17165. }
  17166. };
  17167. /**
  17168. * Attach a new callback raised when context restored event is fired
  17169. * @param callback defines the callback to call
  17170. */
  17171. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17172. if (this._renderingCanvas) {
  17173. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17174. }
  17175. };
  17176. /**
  17177. * Gets the source code of the vertex shader associated with a specific webGL program
  17178. * @param program defines the program to use
  17179. * @returns a string containing the source code of the vertex shader associated with the program
  17180. */
  17181. Engine.prototype.getVertexShaderSource = function (program) {
  17182. var shaders = this._gl.getAttachedShaders(program);
  17183. if (!shaders) {
  17184. return null;
  17185. }
  17186. return this._gl.getShaderSource(shaders[0]);
  17187. };
  17188. /**
  17189. * Gets the source code of the fragment shader associated with a specific webGL program
  17190. * @param program defines the program to use
  17191. * @returns a string containing the source code of the fragment shader associated with the program
  17192. */
  17193. Engine.prototype.getFragmentShaderSource = function (program) {
  17194. var shaders = this._gl.getAttachedShaders(program);
  17195. if (!shaders) {
  17196. return null;
  17197. }
  17198. return this._gl.getShaderSource(shaders[1]);
  17199. };
  17200. /**
  17201. * Get the current error code of the webGL context
  17202. * @returns the error code
  17203. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17204. */
  17205. Engine.prototype.getError = function () {
  17206. return this._gl.getError();
  17207. };
  17208. // FPS
  17209. /**
  17210. * Gets the current framerate
  17211. * @returns a number representing the framerate
  17212. */
  17213. Engine.prototype.getFps = function () {
  17214. return this._fps;
  17215. };
  17216. /**
  17217. * Gets the time spent between current and previous frame
  17218. * @returns a number representing the delta time in ms
  17219. */
  17220. Engine.prototype.getDeltaTime = function () {
  17221. return this._deltaTime;
  17222. };
  17223. Engine.prototype._measureFps = function () {
  17224. this._performanceMonitor.sampleFrame();
  17225. this._fps = this._performanceMonitor.averageFPS;
  17226. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17227. };
  17228. /** @hidden */
  17229. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17230. if (faceIndex === void 0) { faceIndex = -1; }
  17231. if (level === void 0) { level = 0; }
  17232. var gl = this._gl;
  17233. if (!this._dummyFramebuffer) {
  17234. var dummy = gl.createFramebuffer();
  17235. if (!dummy) {
  17236. throw new Error("Unable to create dummy framebuffer");
  17237. }
  17238. this._dummyFramebuffer = dummy;
  17239. }
  17240. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17241. if (faceIndex > -1) {
  17242. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17243. }
  17244. else {
  17245. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17246. }
  17247. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17248. var buffer;
  17249. switch (readType) {
  17250. case gl.UNSIGNED_BYTE:
  17251. buffer = new Uint8Array(4 * width * height);
  17252. readType = gl.UNSIGNED_BYTE;
  17253. break;
  17254. default:
  17255. buffer = new Float32Array(4 * width * height);
  17256. readType = gl.FLOAT;
  17257. break;
  17258. }
  17259. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17260. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17261. return buffer;
  17262. };
  17263. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17264. if (this._webGLVersion > 1) {
  17265. return this._caps.colorBufferFloat;
  17266. }
  17267. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17268. };
  17269. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17270. if (this._webGLVersion > 1) {
  17271. return this._caps.colorBufferFloat;
  17272. }
  17273. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17274. };
  17275. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17276. Engine.prototype._canRenderToFramebuffer = function (type) {
  17277. var gl = this._gl;
  17278. //clear existing errors
  17279. while (gl.getError() !== gl.NO_ERROR) { }
  17280. var successful = true;
  17281. var texture = gl.createTexture();
  17282. gl.bindTexture(gl.TEXTURE_2D, texture);
  17283. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17286. var fb = gl.createFramebuffer();
  17287. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17288. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17289. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17290. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17291. successful = successful && (gl.getError() === gl.NO_ERROR);
  17292. //try render by clearing frame buffer's color buffer
  17293. if (successful) {
  17294. gl.clear(gl.COLOR_BUFFER_BIT);
  17295. successful = successful && (gl.getError() === gl.NO_ERROR);
  17296. }
  17297. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17298. if (successful) {
  17299. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17300. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17301. var readFormat = gl.RGBA;
  17302. var readType = gl.UNSIGNED_BYTE;
  17303. var buffer = new Uint8Array(4);
  17304. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17305. successful = successful && (gl.getError() === gl.NO_ERROR);
  17306. }
  17307. //clean up
  17308. gl.deleteTexture(texture);
  17309. gl.deleteFramebuffer(fb);
  17310. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17311. //clear accumulated errors
  17312. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17313. return successful;
  17314. };
  17315. /** @hidden */
  17316. Engine.prototype._getWebGLTextureType = function (type) {
  17317. if (type === Engine.TEXTURETYPE_FLOAT) {
  17318. return this._gl.FLOAT;
  17319. }
  17320. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17321. // Add Half Float Constant.
  17322. return this._gl.HALF_FLOAT_OES;
  17323. }
  17324. return this._gl.UNSIGNED_BYTE;
  17325. };
  17326. ;
  17327. Engine.prototype._getInternalFormat = function (format) {
  17328. var internalFormat = this._gl.RGBA;
  17329. switch (format) {
  17330. case Engine.TEXTUREFORMAT_ALPHA:
  17331. internalFormat = this._gl.ALPHA;
  17332. break;
  17333. case Engine.TEXTUREFORMAT_LUMINANCE:
  17334. internalFormat = this._gl.LUMINANCE;
  17335. break;
  17336. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17337. internalFormat = this._gl.LUMINANCE_ALPHA;
  17338. break;
  17339. case Engine.TEXTUREFORMAT_RGB:
  17340. internalFormat = this._gl.RGB;
  17341. break;
  17342. case Engine.TEXTUREFORMAT_RGBA:
  17343. internalFormat = this._gl.RGBA;
  17344. break;
  17345. case Engine.TEXTUREFORMAT_R:
  17346. internalFormat = this._gl.RED;
  17347. break;
  17348. case Engine.TEXTUREFORMAT_RG:
  17349. internalFormat = this._gl.RG;
  17350. break;
  17351. }
  17352. return internalFormat;
  17353. };
  17354. /** @hidden */
  17355. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17356. if (this._webGLVersion === 1) {
  17357. if (format !== undefined) {
  17358. switch (format) {
  17359. case Engine.TEXTUREFORMAT_LUMINANCE:
  17360. return this._gl.LUMINANCE;
  17361. case Engine.TEXTUREFORMAT_ALPHA:
  17362. return this._gl.ALPHA;
  17363. }
  17364. }
  17365. return this._gl.RGBA;
  17366. }
  17367. if (type === Engine.TEXTURETYPE_FLOAT) {
  17368. if (format !== undefined) {
  17369. switch (format) {
  17370. case Engine.TEXTUREFORMAT_R:
  17371. return this._gl.R32F;
  17372. case Engine.TEXTUREFORMAT_RG:
  17373. return this._gl.RG32F;
  17374. case Engine.TEXTUREFORMAT_RGB:
  17375. return this._gl.RGB32F;
  17376. }
  17377. }
  17378. return this._gl.RGBA32F;
  17379. }
  17380. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17381. if (format) {
  17382. switch (format) {
  17383. case Engine.TEXTUREFORMAT_R:
  17384. return this._gl.R16F;
  17385. case Engine.TEXTUREFORMAT_RG:
  17386. return this._gl.RG16F;
  17387. case Engine.TEXTUREFORMAT_RGB:
  17388. return this._gl.RGB16F;
  17389. }
  17390. }
  17391. return this._gl.RGBA16F;
  17392. }
  17393. if (format !== undefined) {
  17394. switch (format) {
  17395. case Engine.TEXTUREFORMAT_LUMINANCE:
  17396. return this._gl.LUMINANCE;
  17397. case Engine.TEXTUREFORMAT_RGB:
  17398. return this._gl.RGB;
  17399. case Engine.TEXTUREFORMAT_R:
  17400. return this._gl.R8;
  17401. case Engine.TEXTUREFORMAT_RG:
  17402. return this._gl.RG8;
  17403. case Engine.TEXTUREFORMAT_ALPHA:
  17404. return this._gl.ALPHA;
  17405. }
  17406. }
  17407. return this._gl.RGBA;
  17408. };
  17409. ;
  17410. /** @hidden */
  17411. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17412. if (type === Engine.TEXTURETYPE_FLOAT) {
  17413. return this._gl.RGBA32F;
  17414. }
  17415. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17416. return this._gl.RGBA16F;
  17417. }
  17418. return this._gl.RGBA8;
  17419. };
  17420. ;
  17421. /**
  17422. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17423. * @return the new query
  17424. */
  17425. Engine.prototype.createQuery = function () {
  17426. return this._gl.createQuery();
  17427. };
  17428. /**
  17429. * Delete and release a webGL query
  17430. * @param query defines the query to delete
  17431. * @return the current engine
  17432. */
  17433. Engine.prototype.deleteQuery = function (query) {
  17434. this._gl.deleteQuery(query);
  17435. return this;
  17436. };
  17437. /**
  17438. * Check if a given query has resolved and got its value
  17439. * @param query defines the query to check
  17440. * @returns true if the query got its value
  17441. */
  17442. Engine.prototype.isQueryResultAvailable = function (query) {
  17443. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17444. };
  17445. /**
  17446. * Gets the value of a given query
  17447. * @param query defines the query to check
  17448. * @returns the value of the query
  17449. */
  17450. Engine.prototype.getQueryResult = function (query) {
  17451. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17452. };
  17453. /**
  17454. * Initiates an occlusion query
  17455. * @param algorithmType defines the algorithm to use
  17456. * @param query defines the query to use
  17457. * @returns the current engine
  17458. * @see http://doc.babylonjs.com/features/occlusionquery
  17459. */
  17460. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17461. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17462. this._gl.beginQuery(glAlgorithm, query);
  17463. return this;
  17464. };
  17465. /**
  17466. * Ends an occlusion query
  17467. * @see http://doc.babylonjs.com/features/occlusionquery
  17468. * @param algorithmType defines the algorithm to use
  17469. * @returns the current engine
  17470. */
  17471. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17472. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17473. this._gl.endQuery(glAlgorithm);
  17474. return this;
  17475. };
  17476. /* Time queries */
  17477. Engine.prototype._createTimeQuery = function () {
  17478. var timerQuery = this._caps.timerQuery;
  17479. if (timerQuery.createQueryEXT) {
  17480. return timerQuery.createQueryEXT();
  17481. }
  17482. return this.createQuery();
  17483. };
  17484. Engine.prototype._deleteTimeQuery = function (query) {
  17485. var timerQuery = this._caps.timerQuery;
  17486. if (timerQuery.deleteQueryEXT) {
  17487. timerQuery.deleteQueryEXT(query);
  17488. return;
  17489. }
  17490. this.deleteQuery(query);
  17491. };
  17492. Engine.prototype._getTimeQueryResult = function (query) {
  17493. var timerQuery = this._caps.timerQuery;
  17494. if (timerQuery.getQueryObjectEXT) {
  17495. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17496. }
  17497. return this.getQueryResult(query);
  17498. };
  17499. Engine.prototype._getTimeQueryAvailability = function (query) {
  17500. var timerQuery = this._caps.timerQuery;
  17501. if (timerQuery.getQueryObjectEXT) {
  17502. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17503. }
  17504. return this.isQueryResultAvailable(query);
  17505. };
  17506. /**
  17507. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17508. * Please note that only one query can be issued at a time
  17509. * @returns a time token used to track the time span
  17510. */
  17511. Engine.prototype.startTimeQuery = function () {
  17512. var timerQuery = this._caps.timerQuery;
  17513. if (!timerQuery) {
  17514. return null;
  17515. }
  17516. var token = new BABYLON._TimeToken();
  17517. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17518. if (this._caps.canUseTimestampForTimerQuery) {
  17519. token._startTimeQuery = this._createTimeQuery();
  17520. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17521. }
  17522. else {
  17523. if (this._currentNonTimestampToken) {
  17524. return this._currentNonTimestampToken;
  17525. }
  17526. token._timeElapsedQuery = this._createTimeQuery();
  17527. if (timerQuery.beginQueryEXT) {
  17528. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17529. }
  17530. else {
  17531. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17532. }
  17533. this._currentNonTimestampToken = token;
  17534. }
  17535. return token;
  17536. };
  17537. /**
  17538. * Ends a time query
  17539. * @param token defines the token used to measure the time span
  17540. * @returns the time spent (in ns)
  17541. */
  17542. Engine.prototype.endTimeQuery = function (token) {
  17543. var timerQuery = this._caps.timerQuery;
  17544. if (!timerQuery || !token) {
  17545. return -1;
  17546. }
  17547. if (this._caps.canUseTimestampForTimerQuery) {
  17548. if (!token._startTimeQuery) {
  17549. return -1;
  17550. }
  17551. if (!token._endTimeQuery) {
  17552. token._endTimeQuery = this._createTimeQuery();
  17553. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17554. }
  17555. }
  17556. else if (!token._timeElapsedQueryEnded) {
  17557. if (!token._timeElapsedQuery) {
  17558. return -1;
  17559. }
  17560. if (timerQuery.endQueryEXT) {
  17561. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17562. }
  17563. else {
  17564. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17565. }
  17566. token._timeElapsedQueryEnded = true;
  17567. }
  17568. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17569. var available = false;
  17570. if (token._endTimeQuery) {
  17571. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17572. }
  17573. else if (token._timeElapsedQuery) {
  17574. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17575. }
  17576. if (available && !disjoint) {
  17577. var result = 0;
  17578. if (this._caps.canUseTimestampForTimerQuery) {
  17579. if (!token._startTimeQuery || !token._endTimeQuery) {
  17580. return -1;
  17581. }
  17582. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17583. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17584. result = timeEnd - timeStart;
  17585. this._deleteTimeQuery(token._startTimeQuery);
  17586. this._deleteTimeQuery(token._endTimeQuery);
  17587. token._startTimeQuery = null;
  17588. token._endTimeQuery = null;
  17589. }
  17590. else {
  17591. if (!token._timeElapsedQuery) {
  17592. return -1;
  17593. }
  17594. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17595. this._deleteTimeQuery(token._timeElapsedQuery);
  17596. token._timeElapsedQuery = null;
  17597. token._timeElapsedQueryEnded = false;
  17598. this._currentNonTimestampToken = null;
  17599. }
  17600. return result;
  17601. }
  17602. return -1;
  17603. };
  17604. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17605. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17606. };
  17607. // Transform feedback
  17608. /**
  17609. * Creates a webGL transform feedback object
  17610. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17611. * @returns the webGL transform feedback object
  17612. */
  17613. Engine.prototype.createTransformFeedback = function () {
  17614. return this._gl.createTransformFeedback();
  17615. };
  17616. /**
  17617. * Delete a webGL transform feedback object
  17618. * @param value defines the webGL transform feedback object to delete
  17619. */
  17620. Engine.prototype.deleteTransformFeedback = function (value) {
  17621. this._gl.deleteTransformFeedback(value);
  17622. };
  17623. /**
  17624. * Bind a webGL transform feedback object to the webgl context
  17625. * @param value defines the webGL transform feedback object to bind
  17626. */
  17627. Engine.prototype.bindTransformFeedback = function (value) {
  17628. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17629. };
  17630. /**
  17631. * Begins a transform feedback operation
  17632. * @param usePoints defines if points or triangles must be used
  17633. */
  17634. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17635. if (usePoints === void 0) { usePoints = true; }
  17636. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17637. };
  17638. /**
  17639. * Ends a transform feedback operation
  17640. */
  17641. Engine.prototype.endTransformFeedback = function () {
  17642. this._gl.endTransformFeedback();
  17643. };
  17644. /**
  17645. * Specify the varyings to use with transform feedback
  17646. * @param program defines the associated webGL program
  17647. * @param value defines the list of strings representing the varying names
  17648. */
  17649. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17650. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17651. };
  17652. /**
  17653. * Bind a webGL buffer for a transform feedback operation
  17654. * @param value defines the webGL buffer to bind
  17655. */
  17656. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17657. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17658. };
  17659. /** @hidden */
  17660. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17661. var _this = this;
  17662. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17663. this._activeRequests.push(request);
  17664. request.onCompleteObservable.add(function (request) {
  17665. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17666. });
  17667. return request;
  17668. };
  17669. /** @hidden */
  17670. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17671. var _this = this;
  17672. return new Promise(function (resolve, reject) {
  17673. _this._loadFile(url, function (data) {
  17674. resolve(data);
  17675. }, undefined, database, useArrayBuffer, function (request, exception) {
  17676. reject(exception);
  17677. });
  17678. });
  17679. };
  17680. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17681. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17682. var onload = function (data) {
  17683. loadedFiles[index] = data;
  17684. loadedFiles._internalCount++;
  17685. if (loadedFiles._internalCount === 6) {
  17686. onfinish(loadedFiles);
  17687. }
  17688. };
  17689. var onerror = function (request, exception) {
  17690. if (onErrorCallBack && request) {
  17691. onErrorCallBack(request.status + " " + request.statusText, exception);
  17692. }
  17693. };
  17694. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17695. };
  17696. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17697. if (onError === void 0) { onError = null; }
  17698. var loadedFiles = [];
  17699. loadedFiles._internalCount = 0;
  17700. for (var index = 0; index < 6; index++) {
  17701. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17702. }
  17703. };
  17704. // Statics
  17705. /**
  17706. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17707. * @returns true if the engine can be created
  17708. * @ignorenaming
  17709. */
  17710. Engine.isSupported = function () {
  17711. try {
  17712. var tempcanvas = document.createElement("canvas");
  17713. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17714. return gl != null && !!window.WebGLRenderingContext;
  17715. }
  17716. catch (e) {
  17717. return false;
  17718. }
  17719. };
  17720. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17721. Engine.ExceptionList = [
  17722. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17723. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17724. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17725. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17726. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17727. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17728. ];
  17729. /** Gets the list of created engines */
  17730. Engine.Instances = new Array();
  17731. // Const statics
  17732. Engine._ALPHA_DISABLE = 0;
  17733. Engine._ALPHA_ADD = 1;
  17734. Engine._ALPHA_COMBINE = 2;
  17735. Engine._ALPHA_SUBTRACT = 3;
  17736. Engine._ALPHA_MULTIPLY = 4;
  17737. Engine._ALPHA_MAXIMIZED = 5;
  17738. Engine._ALPHA_ONEONE = 6;
  17739. Engine._ALPHA_PREMULTIPLIED = 7;
  17740. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17741. Engine._ALPHA_INTERPOLATE = 9;
  17742. Engine._ALPHA_SCREENMODE = 10;
  17743. Engine._DELAYLOADSTATE_NONE = 0;
  17744. Engine._DELAYLOADSTATE_LOADED = 1;
  17745. Engine._DELAYLOADSTATE_LOADING = 2;
  17746. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17747. Engine._TEXTUREFORMAT_ALPHA = 0;
  17748. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17749. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17750. Engine._TEXTUREFORMAT_RGB = 4;
  17751. Engine._TEXTUREFORMAT_RGBA = 5;
  17752. Engine._TEXTUREFORMAT_R = 6;
  17753. Engine._TEXTUREFORMAT_RG = 7;
  17754. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17755. Engine._TEXTURETYPE_FLOAT = 1;
  17756. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17757. // Depht or Stencil test Constants.
  17758. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17759. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  17760. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17761. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17762. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  17763. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17764. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  17765. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  17766. // Stencil Actions Constants.
  17767. Engine._KEEP = 0x1E00;
  17768. Engine._REPLACE = 0x1E01;
  17769. Engine._INCR = 0x1E02;
  17770. Engine._DECR = 0x1E03;
  17771. Engine._INVERT = 0x150A;
  17772. Engine._INCR_WRAP = 0x8507;
  17773. Engine._DECR_WRAP = 0x8508;
  17774. // Texture rescaling mode
  17775. Engine._SCALEMODE_FLOOR = 1;
  17776. Engine._SCALEMODE_NEAREST = 2;
  17777. Engine._SCALEMODE_CEILING = 3;
  17778. // Updatable statics so stick with vars here
  17779. /**
  17780. * Gets or sets the epsilon value used by collision engine
  17781. */
  17782. Engine.CollisionsEpsilon = 0.001;
  17783. /**
  17784. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17785. */
  17786. Engine.CodeRepository = "src/";
  17787. /**
  17788. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17789. */
  17790. Engine.ShadersRepository = "src/Shaders/";
  17791. return Engine;
  17792. }());
  17793. BABYLON.Engine = Engine;
  17794. })(BABYLON || (BABYLON = {}));
  17795. //# sourceMappingURL=babylon.engine.js.map
  17796. var BABYLON;
  17797. (function (BABYLON) {
  17798. /**
  17799. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17800. */
  17801. var Node = /** @class */ (function () {
  17802. /**
  17803. * Creates a new Node
  17804. * @param {string} name - the name and id to be given to this node
  17805. * @param {BABYLON.Scene} the scene this node will be added to
  17806. */
  17807. function Node(name, scene) {
  17808. if (scene === void 0) { scene = null; }
  17809. /**
  17810. * Gets or sets a string used to store user defined state for the node
  17811. */
  17812. this.state = "";
  17813. /**
  17814. * Gets or sets an object used to store user defined information for the node
  17815. */
  17816. this.metadata = null;
  17817. /**
  17818. * Gets or sets a boolean used to define if the node must be serialized
  17819. */
  17820. this.doNotSerialize = false;
  17821. /** @hidden */
  17822. this._isDisposed = false;
  17823. /**
  17824. * Gets a list of Animations associated with the node
  17825. */
  17826. this.animations = new Array();
  17827. this._ranges = {};
  17828. this._isEnabled = true;
  17829. this._isReady = true;
  17830. /** @hidden */
  17831. this._currentRenderId = -1;
  17832. this._parentRenderId = -1;
  17833. this._childRenderId = -1;
  17834. this._animationPropertiesOverride = null;
  17835. /**
  17836. * An event triggered when the mesh is disposed
  17837. */
  17838. this.onDisposeObservable = new BABYLON.Observable();
  17839. // Behaviors
  17840. this._behaviors = new Array();
  17841. this.name = name;
  17842. this.id = name;
  17843. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17844. this.uniqueId = this._scene.getUniqueId();
  17845. this._initCache();
  17846. }
  17847. /**
  17848. * Gets a boolean indicating if the node has been disposed
  17849. * @returns true if the node was disposed
  17850. */
  17851. Node.prototype.isDisposed = function () {
  17852. return this._isDisposed;
  17853. };
  17854. Object.defineProperty(Node.prototype, "parent", {
  17855. get: function () {
  17856. return this._parentNode;
  17857. },
  17858. /**
  17859. * Gets or sets the parent of the node
  17860. */
  17861. set: function (parent) {
  17862. if (this._parentNode === parent) {
  17863. return;
  17864. }
  17865. // Remove self from list of children of parent
  17866. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17867. var index = this._parentNode._children.indexOf(this);
  17868. if (index !== -1) {
  17869. this._parentNode._children.splice(index, 1);
  17870. }
  17871. }
  17872. // Store new parent
  17873. this._parentNode = parent;
  17874. // Add as child to new parent
  17875. if (this._parentNode) {
  17876. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17877. this._parentNode._children = new Array();
  17878. }
  17879. this._parentNode._children.push(this);
  17880. }
  17881. },
  17882. enumerable: true,
  17883. configurable: true
  17884. });
  17885. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17886. /**
  17887. * Gets or sets the animation properties override
  17888. */
  17889. get: function () {
  17890. if (!this._animationPropertiesOverride) {
  17891. return this._scene.animationPropertiesOverride;
  17892. }
  17893. return this._animationPropertiesOverride;
  17894. },
  17895. set: function (value) {
  17896. this._animationPropertiesOverride = value;
  17897. },
  17898. enumerable: true,
  17899. configurable: true
  17900. });
  17901. /**
  17902. * Gets a string idenfifying the name of the class
  17903. * @returns "Node" string
  17904. */
  17905. Node.prototype.getClassName = function () {
  17906. return "Node";
  17907. };
  17908. Object.defineProperty(Node.prototype, "onDispose", {
  17909. /**
  17910. * Sets a callback that will be raised when the node will be disposed
  17911. */
  17912. set: function (callback) {
  17913. if (this._onDisposeObserver) {
  17914. this.onDisposeObservable.remove(this._onDisposeObserver);
  17915. }
  17916. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17917. },
  17918. enumerable: true,
  17919. configurable: true
  17920. });
  17921. /**
  17922. * Gets the scene of the node
  17923. * @returns a {BABYLON.Scene}
  17924. */
  17925. Node.prototype.getScene = function () {
  17926. return this._scene;
  17927. };
  17928. /**
  17929. * Gets the engine of the node
  17930. * @returns a {BABYLON.Engine}
  17931. */
  17932. Node.prototype.getEngine = function () {
  17933. return this._scene.getEngine();
  17934. };
  17935. /**
  17936. * Attach a behavior to the node
  17937. * @see http://doc.babylonjs.com/features/behaviour
  17938. * @param behavior defines the behavior to attach
  17939. * @returns the current Node
  17940. */
  17941. Node.prototype.addBehavior = function (behavior) {
  17942. var _this = this;
  17943. var index = this._behaviors.indexOf(behavior);
  17944. if (index !== -1) {
  17945. return this;
  17946. }
  17947. behavior.init();
  17948. if (this._scene.isLoading) {
  17949. // We defer the attach when the scene will be loaded
  17950. this._scene.onDataLoadedObservable.addOnce(function () {
  17951. behavior.attach(_this);
  17952. });
  17953. }
  17954. else {
  17955. behavior.attach(this);
  17956. }
  17957. this._behaviors.push(behavior);
  17958. return this;
  17959. };
  17960. /**
  17961. * Remove an attached behavior
  17962. * @see http://doc.babylonjs.com/features/behaviour
  17963. * @param behavior defines the behavior to attach
  17964. * @returns the current Node
  17965. */
  17966. Node.prototype.removeBehavior = function (behavior) {
  17967. var index = this._behaviors.indexOf(behavior);
  17968. if (index === -1) {
  17969. return this;
  17970. }
  17971. this._behaviors[index].detach();
  17972. this._behaviors.splice(index, 1);
  17973. return this;
  17974. };
  17975. Object.defineProperty(Node.prototype, "behaviors", {
  17976. /**
  17977. * Gets the list of attached behaviors
  17978. * @see http://doc.babylonjs.com/features/behaviour
  17979. */
  17980. get: function () {
  17981. return this._behaviors;
  17982. },
  17983. enumerable: true,
  17984. configurable: true
  17985. });
  17986. /**
  17987. * Gets an attached behavior by name
  17988. * @param name defines the name of the behavior to look for
  17989. * @see http://doc.babylonjs.com/features/behaviour
  17990. * @returns null if behavior was not found else the requested behavior
  17991. */
  17992. Node.prototype.getBehaviorByName = function (name) {
  17993. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17994. var behavior = _a[_i];
  17995. if (behavior.name === name) {
  17996. return behavior;
  17997. }
  17998. }
  17999. return null;
  18000. };
  18001. /**
  18002. * Returns the world matrix of the node
  18003. * @returns a matrix containing the node's world matrix
  18004. */
  18005. Node.prototype.getWorldMatrix = function () {
  18006. return BABYLON.Matrix.Identity();
  18007. };
  18008. /** @hidden */
  18009. Node.prototype._getWorldMatrixDeterminant = function () {
  18010. return 1;
  18011. };
  18012. // override it in derived class if you add new variables to the cache
  18013. // and call the parent class method
  18014. /** @hidden */
  18015. Node.prototype._initCache = function () {
  18016. this._cache = {};
  18017. this._cache.parent = undefined;
  18018. };
  18019. /** @hidden */
  18020. Node.prototype.updateCache = function (force) {
  18021. if (!force && this.isSynchronized())
  18022. return;
  18023. this._cache.parent = this.parent;
  18024. this._updateCache();
  18025. };
  18026. // override it in derived class if you add new variables to the cache
  18027. // and call the parent class method if !ignoreParentClass
  18028. /** @hidden */
  18029. Node.prototype._updateCache = function (ignoreParentClass) {
  18030. };
  18031. // override it in derived class if you add new variables to the cache
  18032. /** @hidden */
  18033. Node.prototype._isSynchronized = function () {
  18034. return true;
  18035. };
  18036. /** @hidden */
  18037. Node.prototype._markSyncedWithParent = function () {
  18038. if (this.parent) {
  18039. this._parentRenderId = this.parent._childRenderId;
  18040. }
  18041. };
  18042. /** @hidden */
  18043. Node.prototype.isSynchronizedWithParent = function () {
  18044. if (!this.parent) {
  18045. return true;
  18046. }
  18047. if (this._parentRenderId !== this.parent._childRenderId) {
  18048. return false;
  18049. }
  18050. return this.parent.isSynchronized();
  18051. };
  18052. /** @hidden */
  18053. Node.prototype.isSynchronized = function (updateCache) {
  18054. var check = this.hasNewParent();
  18055. check = check || !this.isSynchronizedWithParent();
  18056. check = check || !this._isSynchronized();
  18057. if (updateCache)
  18058. this.updateCache(true);
  18059. return !check;
  18060. };
  18061. /** @hidden */
  18062. Node.prototype.hasNewParent = function (update) {
  18063. if (this._cache.parent === this.parent)
  18064. return false;
  18065. if (update)
  18066. this._cache.parent = this.parent;
  18067. return true;
  18068. };
  18069. /**
  18070. * Is this node ready to be used/rendered
  18071. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18072. * @return true if the node is ready
  18073. */
  18074. Node.prototype.isReady = function (completeCheck) {
  18075. if (completeCheck === void 0) { completeCheck = false; }
  18076. return this._isReady;
  18077. };
  18078. /**
  18079. * Is this node enabled?
  18080. * 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
  18081. * @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
  18082. * @return whether this node (and its parent) is enabled
  18083. */
  18084. Node.prototype.isEnabled = function (checkAncestors) {
  18085. if (checkAncestors === void 0) { checkAncestors = true; }
  18086. if (checkAncestors === false) {
  18087. return this._isEnabled;
  18088. }
  18089. if (this._isEnabled === false) {
  18090. return false;
  18091. }
  18092. if (this.parent !== undefined && this.parent !== null) {
  18093. return this.parent.isEnabled(checkAncestors);
  18094. }
  18095. return true;
  18096. };
  18097. /**
  18098. * Set the enabled state of this node
  18099. * @param value defines the new enabled state
  18100. */
  18101. Node.prototype.setEnabled = function (value) {
  18102. this._isEnabled = value;
  18103. };
  18104. /**
  18105. * Is this node a descendant of the given node?
  18106. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18107. * @param ancestor defines the parent node to inspect
  18108. * @returns a boolean indicating if this node is a descendant of the given node
  18109. */
  18110. Node.prototype.isDescendantOf = function (ancestor) {
  18111. if (this.parent) {
  18112. if (this.parent === ancestor) {
  18113. return true;
  18114. }
  18115. return this.parent.isDescendantOf(ancestor);
  18116. }
  18117. return false;
  18118. };
  18119. /** @hidden */
  18120. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18121. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18122. if (!this._children) {
  18123. return;
  18124. }
  18125. for (var index = 0; index < this._children.length; index++) {
  18126. var item = this._children[index];
  18127. if (!predicate || predicate(item)) {
  18128. results.push(item);
  18129. }
  18130. if (!directDescendantsOnly) {
  18131. item._getDescendants(results, false, predicate);
  18132. }
  18133. }
  18134. };
  18135. /**
  18136. * Will return all nodes that have this node as ascendant
  18137. * @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
  18138. * @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
  18139. * @return all children nodes of all types
  18140. */
  18141. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18142. var results = new Array();
  18143. this._getDescendants(results, directDescendantsOnly, predicate);
  18144. return results;
  18145. };
  18146. /**
  18147. * Get all child-meshes of this node
  18148. * @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
  18149. * @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
  18150. * @returns an array of {BABYLON.AbstractMesh}
  18151. */
  18152. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18153. var results = [];
  18154. this._getDescendants(results, directDescendantsOnly, function (node) {
  18155. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18156. });
  18157. return results;
  18158. };
  18159. /**
  18160. * Get all child-transformNodes of this node
  18161. * @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
  18162. * @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
  18163. * @returns an array of {BABYLON.TransformNode}
  18164. */
  18165. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18166. var results = [];
  18167. this._getDescendants(results, directDescendantsOnly, function (node) {
  18168. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18169. });
  18170. return results;
  18171. };
  18172. /**
  18173. * Get all direct children of this node
  18174. * @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
  18175. * @returns an array of {BABYLON.Node}
  18176. */
  18177. Node.prototype.getChildren = function (predicate) {
  18178. return this.getDescendants(true, predicate);
  18179. };
  18180. /** @hidden */
  18181. Node.prototype._setReady = function (state) {
  18182. if (state === this._isReady) {
  18183. return;
  18184. }
  18185. if (!state) {
  18186. this._isReady = false;
  18187. return;
  18188. }
  18189. if (this.onReady) {
  18190. this.onReady(this);
  18191. }
  18192. this._isReady = true;
  18193. };
  18194. /**
  18195. * Get an animation by name
  18196. * @param name defines the name of the animation to look for
  18197. * @returns null if not found else the requested animation
  18198. */
  18199. Node.prototype.getAnimationByName = function (name) {
  18200. for (var i = 0; i < this.animations.length; i++) {
  18201. var animation = this.animations[i];
  18202. if (animation.name === name) {
  18203. return animation;
  18204. }
  18205. }
  18206. return null;
  18207. };
  18208. /**
  18209. * Creates an animation range for this node
  18210. * @param name defines the name of the range
  18211. * @param from defines the starting key
  18212. * @param to defines the end key
  18213. */
  18214. Node.prototype.createAnimationRange = function (name, from, to) {
  18215. // check name not already in use
  18216. if (!this._ranges[name]) {
  18217. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18218. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18219. if (this.animations[i]) {
  18220. this.animations[i].createRange(name, from, to);
  18221. }
  18222. }
  18223. }
  18224. };
  18225. /**
  18226. * Delete a specific animation range
  18227. * @param name defines the name of the range to delete
  18228. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18229. */
  18230. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18231. if (deleteFrames === void 0) { deleteFrames = true; }
  18232. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18233. if (this.animations[i]) {
  18234. this.animations[i].deleteRange(name, deleteFrames);
  18235. }
  18236. }
  18237. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18238. };
  18239. /**
  18240. * Get an animation range by name
  18241. * @param name defines the name of the animation range to look for
  18242. * @returns null if not found else the requested animation range
  18243. */
  18244. Node.prototype.getAnimationRange = function (name) {
  18245. return this._ranges[name];
  18246. };
  18247. /**
  18248. * Will start the animation sequence
  18249. * @param name defines the range frames for animation sequence
  18250. * @param loop defines if the animation should loop (false by default)
  18251. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18252. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18253. * @returns the object created for this animation. If range does not exist, it will return null
  18254. */
  18255. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18256. var range = this.getAnimationRange(name);
  18257. if (!range) {
  18258. return null;
  18259. }
  18260. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18261. };
  18262. /**
  18263. * Serialize animation ranges into a JSON compatible object
  18264. * @returns serialization object
  18265. */
  18266. Node.prototype.serializeAnimationRanges = function () {
  18267. var serializationRanges = [];
  18268. for (var name in this._ranges) {
  18269. var localRange = this._ranges[name];
  18270. if (!localRange) {
  18271. continue;
  18272. }
  18273. var range = {};
  18274. range.name = name;
  18275. range.from = localRange.from;
  18276. range.to = localRange.to;
  18277. serializationRanges.push(range);
  18278. }
  18279. return serializationRanges;
  18280. };
  18281. /**
  18282. * Computes the world matrix of the node
  18283. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18284. * @returns the world matrix
  18285. */
  18286. Node.prototype.computeWorldMatrix = function (force) {
  18287. return BABYLON.Matrix.Identity();
  18288. };
  18289. /**
  18290. * Releases resources associated with this node.
  18291. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18292. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18293. */
  18294. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18295. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18296. if (!doNotRecurse) {
  18297. var nodes = this.getDescendants(true);
  18298. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18299. var node = nodes_1[_i];
  18300. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18301. }
  18302. }
  18303. else {
  18304. var transformNodes = this.getChildTransformNodes(true);
  18305. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18306. var transformNode = transformNodes_1[_a];
  18307. transformNode.parent = null;
  18308. transformNode.computeWorldMatrix(true);
  18309. }
  18310. }
  18311. this.parent = null;
  18312. // Callback
  18313. this.onDisposeObservable.notifyObservers(this);
  18314. this.onDisposeObservable.clear();
  18315. // Behaviors
  18316. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18317. var behavior = _c[_b];
  18318. behavior.detach();
  18319. }
  18320. this._behaviors = [];
  18321. this._isDisposed = true;
  18322. };
  18323. /**
  18324. * Parse animation range data from a serialization object and store them into a given node
  18325. * @param node defines where to store the animation ranges
  18326. * @param parsedNode defines the serialization object to read data from
  18327. * @param scene defines the hosting scene
  18328. */
  18329. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18330. if (parsedNode.ranges) {
  18331. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18332. var data = parsedNode.ranges[index];
  18333. node.createAnimationRange(data.name, data.from, data.to);
  18334. }
  18335. }
  18336. };
  18337. __decorate([
  18338. BABYLON.serialize()
  18339. ], Node.prototype, "name", void 0);
  18340. __decorate([
  18341. BABYLON.serialize()
  18342. ], Node.prototype, "id", void 0);
  18343. __decorate([
  18344. BABYLON.serialize()
  18345. ], Node.prototype, "uniqueId", void 0);
  18346. __decorate([
  18347. BABYLON.serialize()
  18348. ], Node.prototype, "state", void 0);
  18349. __decorate([
  18350. BABYLON.serialize()
  18351. ], Node.prototype, "metadata", void 0);
  18352. return Node;
  18353. }());
  18354. BABYLON.Node = Node;
  18355. })(BABYLON || (BABYLON = {}));
  18356. //# sourceMappingURL=babylon.node.js.map
  18357. var BABYLON;
  18358. (function (BABYLON) {
  18359. var BoundingSphere = /** @class */ (function () {
  18360. /**
  18361. * Creates a new bounding sphere
  18362. * @param min defines the minimum vector (in local space)
  18363. * @param max defines the maximum vector (in local space)
  18364. */
  18365. function BoundingSphere(min, max) {
  18366. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18367. this.reConstruct(min, max);
  18368. }
  18369. /**
  18370. * Recreates the entire bounding sphere from scratch
  18371. * @param min defines the new minimum vector (in local space)
  18372. * @param max defines the new maximum vector (in local space)
  18373. */
  18374. BoundingSphere.prototype.reConstruct = function (min, max) {
  18375. this.minimum = min.clone();
  18376. this.maximum = max.clone();
  18377. var distance = BABYLON.Vector3.Distance(min, max);
  18378. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18379. this.radius = distance * 0.5;
  18380. this.centerWorld = BABYLON.Vector3.Zero();
  18381. this._update(BABYLON.Matrix.Identity());
  18382. };
  18383. // Methods
  18384. BoundingSphere.prototype._update = function (world) {
  18385. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18386. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18387. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18388. };
  18389. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18390. for (var i = 0; i < 6; i++) {
  18391. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18392. return false;
  18393. }
  18394. return true;
  18395. };
  18396. BoundingSphere.prototype.intersectsPoint = function (point) {
  18397. var x = this.centerWorld.x - point.x;
  18398. var y = this.centerWorld.y - point.y;
  18399. var z = this.centerWorld.z - point.z;
  18400. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18401. if (this.radiusWorld < distance)
  18402. return false;
  18403. return true;
  18404. };
  18405. // Statics
  18406. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18407. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18408. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18409. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18410. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18411. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18412. return false;
  18413. return true;
  18414. };
  18415. return BoundingSphere;
  18416. }());
  18417. BABYLON.BoundingSphere = BoundingSphere;
  18418. })(BABYLON || (BABYLON = {}));
  18419. //# sourceMappingURL=babylon.boundingSphere.js.map
  18420. var BABYLON;
  18421. (function (BABYLON) {
  18422. var BoundingBox = /** @class */ (function () {
  18423. /**
  18424. * Creates a new bounding box
  18425. * @param min defines the minimum vector (in local space)
  18426. * @param max defines the maximum vector (in local space)
  18427. */
  18428. function BoundingBox(min, max) {
  18429. this.vectorsWorld = new Array();
  18430. this.reConstruct(min, max);
  18431. }
  18432. // Methods
  18433. /**
  18434. * Recreates the entire bounding box from scratch
  18435. * @param min defines the new minimum vector (in local space)
  18436. * @param max defines the new maximum vector (in local space)
  18437. */
  18438. BoundingBox.prototype.reConstruct = function (min, max) {
  18439. this.minimum = min.clone();
  18440. this.maximum = max.clone();
  18441. // Bounding vectors
  18442. this.vectors = new Array();
  18443. this.vectors.push(this.minimum.clone());
  18444. this.vectors.push(this.maximum.clone());
  18445. this.vectors.push(this.minimum.clone());
  18446. this.vectors[2].x = this.maximum.x;
  18447. this.vectors.push(this.minimum.clone());
  18448. this.vectors[3].y = this.maximum.y;
  18449. this.vectors.push(this.minimum.clone());
  18450. this.vectors[4].z = this.maximum.z;
  18451. this.vectors.push(this.maximum.clone());
  18452. this.vectors[5].z = this.minimum.z;
  18453. this.vectors.push(this.maximum.clone());
  18454. this.vectors[6].x = this.minimum.x;
  18455. this.vectors.push(this.maximum.clone());
  18456. this.vectors[7].y = this.minimum.y;
  18457. // OBB
  18458. this.center = this.maximum.add(this.minimum).scale(0.5);
  18459. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18460. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18461. // World
  18462. for (var index = 0; index < this.vectors.length; index++) {
  18463. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18464. }
  18465. this.minimumWorld = BABYLON.Vector3.Zero();
  18466. this.maximumWorld = BABYLON.Vector3.Zero();
  18467. this.centerWorld = BABYLON.Vector3.Zero();
  18468. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18469. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18470. };
  18471. BoundingBox.prototype.getWorldMatrix = function () {
  18472. return this._worldMatrix;
  18473. };
  18474. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18475. this._worldMatrix.copyFrom(matrix);
  18476. return this;
  18477. };
  18478. BoundingBox.prototype._update = function (world) {
  18479. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18480. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18481. for (var index = 0; index < this.vectors.length; index++) {
  18482. var v = this.vectorsWorld[index];
  18483. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18484. if (v.x < this.minimumWorld.x)
  18485. this.minimumWorld.x = v.x;
  18486. if (v.y < this.minimumWorld.y)
  18487. this.minimumWorld.y = v.y;
  18488. if (v.z < this.minimumWorld.z)
  18489. this.minimumWorld.z = v.z;
  18490. if (v.x > this.maximumWorld.x)
  18491. this.maximumWorld.x = v.x;
  18492. if (v.y > this.maximumWorld.y)
  18493. this.maximumWorld.y = v.y;
  18494. if (v.z > this.maximumWorld.z)
  18495. this.maximumWorld.z = v.z;
  18496. }
  18497. // Extend
  18498. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18499. this.extendSizeWorld.scaleInPlace(0.5);
  18500. // OBB
  18501. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18502. this.centerWorld.scaleInPlace(0.5);
  18503. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18504. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18505. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18506. this._worldMatrix = world;
  18507. };
  18508. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18509. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18510. };
  18511. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18512. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18513. };
  18514. BoundingBox.prototype.intersectsPoint = function (point) {
  18515. var delta = -BABYLON.Epsilon;
  18516. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18517. return false;
  18518. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18519. return false;
  18520. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18521. return false;
  18522. return true;
  18523. };
  18524. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18525. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18526. };
  18527. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18528. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18529. return false;
  18530. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18531. return false;
  18532. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18533. return false;
  18534. return true;
  18535. };
  18536. // Statics
  18537. BoundingBox.Intersects = function (box0, box1) {
  18538. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18539. return false;
  18540. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18541. return false;
  18542. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18543. return false;
  18544. return true;
  18545. };
  18546. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18547. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18548. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18549. return (num <= (sphereRadius * sphereRadius));
  18550. };
  18551. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18552. for (var p = 0; p < 6; p++) {
  18553. for (var i = 0; i < 8; i++) {
  18554. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18555. return false;
  18556. }
  18557. }
  18558. }
  18559. return true;
  18560. };
  18561. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18562. for (var p = 0; p < 6; p++) {
  18563. var inCount = 8;
  18564. for (var i = 0; i < 8; i++) {
  18565. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18566. --inCount;
  18567. }
  18568. else {
  18569. break;
  18570. }
  18571. }
  18572. if (inCount === 0)
  18573. return false;
  18574. }
  18575. return true;
  18576. };
  18577. return BoundingBox;
  18578. }());
  18579. BABYLON.BoundingBox = BoundingBox;
  18580. })(BABYLON || (BABYLON = {}));
  18581. //# sourceMappingURL=babylon.boundingBox.js.map
  18582. var BABYLON;
  18583. (function (BABYLON) {
  18584. var computeBoxExtents = function (axis, box) {
  18585. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18586. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18587. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18588. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18589. var r = r0 + r1 + r2;
  18590. return {
  18591. min: p - r,
  18592. max: p + r
  18593. };
  18594. };
  18595. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18596. var axisOverlap = function (axis, box0, box1) {
  18597. var result0 = computeBoxExtents(axis, box0);
  18598. var result1 = computeBoxExtents(axis, box1);
  18599. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18600. };
  18601. var BoundingInfo = /** @class */ (function () {
  18602. function BoundingInfo(minimum, maximum) {
  18603. this.minimum = minimum;
  18604. this.maximum = maximum;
  18605. this._isLocked = false;
  18606. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18607. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18608. }
  18609. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18610. get: function () {
  18611. return this._isLocked;
  18612. },
  18613. set: function (value) {
  18614. this._isLocked = value;
  18615. },
  18616. enumerable: true,
  18617. configurable: true
  18618. });
  18619. // Methods
  18620. BoundingInfo.prototype.update = function (world) {
  18621. if (this._isLocked) {
  18622. return;
  18623. }
  18624. this.boundingBox._update(world);
  18625. this.boundingSphere._update(world);
  18626. };
  18627. /**
  18628. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18629. * @param center New center of the bounding info
  18630. * @param extend New extend of the bounding info
  18631. */
  18632. BoundingInfo.prototype.centerOn = function (center, extend) {
  18633. this.minimum = center.subtract(extend);
  18634. this.maximum = center.add(extend);
  18635. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18636. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18637. return this;
  18638. };
  18639. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18640. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18641. return false;
  18642. return this.boundingBox.isInFrustum(frustumPlanes);
  18643. };
  18644. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18645. /**
  18646. * Gets the world distance between the min and max points of the bounding box
  18647. */
  18648. get: function () {
  18649. var boundingBox = this.boundingBox;
  18650. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18651. return size.length();
  18652. },
  18653. enumerable: true,
  18654. configurable: true
  18655. });
  18656. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18657. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18658. };
  18659. BoundingInfo.prototype._checkCollision = function (collider) {
  18660. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18661. };
  18662. BoundingInfo.prototype.intersectsPoint = function (point) {
  18663. if (!this.boundingSphere.centerWorld) {
  18664. return false;
  18665. }
  18666. if (!this.boundingSphere.intersectsPoint(point)) {
  18667. return false;
  18668. }
  18669. if (!this.boundingBox.intersectsPoint(point)) {
  18670. return false;
  18671. }
  18672. return true;
  18673. };
  18674. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18675. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18676. return false;
  18677. }
  18678. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18679. return false;
  18680. }
  18681. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18682. return false;
  18683. }
  18684. if (!precise) {
  18685. return true;
  18686. }
  18687. var box0 = this.boundingBox;
  18688. var box1 = boundingInfo.boundingBox;
  18689. if (!axisOverlap(box0.directions[0], box0, box1))
  18690. return false;
  18691. if (!axisOverlap(box0.directions[1], box0, box1))
  18692. return false;
  18693. if (!axisOverlap(box0.directions[2], box0, box1))
  18694. return false;
  18695. if (!axisOverlap(box1.directions[0], box0, box1))
  18696. return false;
  18697. if (!axisOverlap(box1.directions[1], box0, box1))
  18698. return false;
  18699. if (!axisOverlap(box1.directions[2], box0, box1))
  18700. return false;
  18701. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18702. return false;
  18703. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18704. return false;
  18705. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18706. return false;
  18707. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18708. return false;
  18709. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18710. return false;
  18711. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18712. return false;
  18713. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18714. return false;
  18715. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18716. return false;
  18717. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18718. return false;
  18719. return true;
  18720. };
  18721. return BoundingInfo;
  18722. }());
  18723. BABYLON.BoundingInfo = BoundingInfo;
  18724. })(BABYLON || (BABYLON = {}));
  18725. //# sourceMappingURL=babylon.boundingInfo.js.map
  18726. var BABYLON;
  18727. (function (BABYLON) {
  18728. var TransformNode = /** @class */ (function (_super) {
  18729. __extends(TransformNode, _super);
  18730. function TransformNode(name, scene, isPure) {
  18731. if (scene === void 0) { scene = null; }
  18732. if (isPure === void 0) { isPure = true; }
  18733. var _this = _super.call(this, name, scene) || this;
  18734. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18735. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18736. _this._up = new BABYLON.Vector3(0, 1, 0);
  18737. _this._right = new BABYLON.Vector3(1, 0, 0);
  18738. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18739. // Properties
  18740. _this._rotation = BABYLON.Vector3.Zero();
  18741. _this._scaling = BABYLON.Vector3.One();
  18742. _this._isDirty = false;
  18743. /**
  18744. * Set the billboard mode. Default is 0.
  18745. *
  18746. * | Value | Type | Description |
  18747. * | --- | --- | --- |
  18748. * | 0 | BILLBOARDMODE_NONE | |
  18749. * | 1 | BILLBOARDMODE_X | |
  18750. * | 2 | BILLBOARDMODE_Y | |
  18751. * | 4 | BILLBOARDMODE_Z | |
  18752. * | 7 | BILLBOARDMODE_ALL | |
  18753. *
  18754. */
  18755. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18756. _this.scalingDeterminant = 1;
  18757. _this.infiniteDistance = false;
  18758. /**
  18759. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18760. * By default the system will update normals to compensate
  18761. */
  18762. _this.ignoreNonUniformScaling = false;
  18763. _this.position = BABYLON.Vector3.Zero();
  18764. _this._localWorld = BABYLON.Matrix.Zero();
  18765. _this._worldMatrix = BABYLON.Matrix.Zero();
  18766. _this._worldMatrixDeterminant = 0;
  18767. _this._absolutePosition = BABYLON.Vector3.Zero();
  18768. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18769. _this._postMultiplyPivotMatrix = false;
  18770. _this._isWorldMatrixFrozen = false;
  18771. /**
  18772. * An event triggered after the world matrix is updated
  18773. */
  18774. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18775. _this._nonUniformScaling = false;
  18776. if (isPure) {
  18777. _this.getScene().addTransformNode(_this);
  18778. }
  18779. return _this;
  18780. }
  18781. /**
  18782. * Gets a string idenfifying the name of the class
  18783. * @returns "TransformNode" string
  18784. */
  18785. TransformNode.prototype.getClassName = function () {
  18786. return "TransformNode";
  18787. };
  18788. Object.defineProperty(TransformNode.prototype, "rotation", {
  18789. /**
  18790. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18791. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18792. * Default : (0.0, 0.0, 0.0)
  18793. */
  18794. get: function () {
  18795. return this._rotation;
  18796. },
  18797. set: function (newRotation) {
  18798. this._rotation = newRotation;
  18799. },
  18800. enumerable: true,
  18801. configurable: true
  18802. });
  18803. Object.defineProperty(TransformNode.prototype, "scaling", {
  18804. /**
  18805. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18806. * Default : (1.0, 1.0, 1.0)
  18807. */
  18808. get: function () {
  18809. return this._scaling;
  18810. },
  18811. /**
  18812. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18813. * Default : (1.0, 1.0, 1.0)
  18814. */
  18815. set: function (newScaling) {
  18816. this._scaling = newScaling;
  18817. },
  18818. enumerable: true,
  18819. configurable: true
  18820. });
  18821. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18822. /**
  18823. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18824. * It's null by default.
  18825. * 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)
  18826. */
  18827. get: function () {
  18828. return this._rotationQuaternion;
  18829. },
  18830. set: function (quaternion) {
  18831. this._rotationQuaternion = quaternion;
  18832. //reset the rotation vector.
  18833. if (quaternion && this.rotation.length()) {
  18834. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18835. }
  18836. },
  18837. enumerable: true,
  18838. configurable: true
  18839. });
  18840. Object.defineProperty(TransformNode.prototype, "forward", {
  18841. /**
  18842. * The forward direction of that transform in world space.
  18843. */
  18844. get: function () {
  18845. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18846. },
  18847. enumerable: true,
  18848. configurable: true
  18849. });
  18850. Object.defineProperty(TransformNode.prototype, "up", {
  18851. /**
  18852. * The up direction of that transform in world space.
  18853. */
  18854. get: function () {
  18855. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18856. },
  18857. enumerable: true,
  18858. configurable: true
  18859. });
  18860. Object.defineProperty(TransformNode.prototype, "right", {
  18861. /**
  18862. * The right direction of that transform in world space.
  18863. */
  18864. get: function () {
  18865. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18866. },
  18867. enumerable: true,
  18868. configurable: true
  18869. });
  18870. /**
  18871. * Returns the latest update of the World matrix
  18872. * Returns a Matrix.
  18873. */
  18874. TransformNode.prototype.getWorldMatrix = function () {
  18875. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18876. this.computeWorldMatrix();
  18877. }
  18878. return this._worldMatrix;
  18879. };
  18880. /** @hidden */
  18881. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18882. return this._worldMatrixDeterminant;
  18883. };
  18884. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18885. /**
  18886. * Returns directly the latest state of the mesh World matrix.
  18887. * A Matrix is returned.
  18888. */
  18889. get: function () {
  18890. return this._worldMatrix;
  18891. },
  18892. enumerable: true,
  18893. configurable: true
  18894. });
  18895. /**
  18896. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18897. * Returns the TransformNode.
  18898. */
  18899. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18900. this._poseMatrix.copyFrom(matrix);
  18901. return this;
  18902. };
  18903. /**
  18904. * Returns the mesh Pose matrix.
  18905. * Returned object : Matrix
  18906. */
  18907. TransformNode.prototype.getPoseMatrix = function () {
  18908. return this._poseMatrix;
  18909. };
  18910. TransformNode.prototype._isSynchronized = function () {
  18911. if (this._isDirty) {
  18912. return false;
  18913. }
  18914. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18915. return false;
  18916. if (this._cache.pivotMatrixUpdated) {
  18917. return false;
  18918. }
  18919. if (this.infiniteDistance) {
  18920. return false;
  18921. }
  18922. if (!this._cache.position.equals(this.position))
  18923. return false;
  18924. if (this.rotationQuaternion) {
  18925. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18926. return false;
  18927. }
  18928. if (!this._cache.rotation.equals(this.rotation))
  18929. return false;
  18930. if (!this._cache.scaling.equals(this.scaling))
  18931. return false;
  18932. return true;
  18933. };
  18934. TransformNode.prototype._initCache = function () {
  18935. _super.prototype._initCache.call(this);
  18936. this._cache.localMatrixUpdated = false;
  18937. this._cache.position = BABYLON.Vector3.Zero();
  18938. this._cache.scaling = BABYLON.Vector3.Zero();
  18939. this._cache.rotation = BABYLON.Vector3.Zero();
  18940. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18941. this._cache.billboardMode = -1;
  18942. };
  18943. TransformNode.prototype.markAsDirty = function (property) {
  18944. if (property === "rotation") {
  18945. this.rotationQuaternion = null;
  18946. }
  18947. this._currentRenderId = Number.MAX_VALUE;
  18948. this._isDirty = true;
  18949. return this;
  18950. };
  18951. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18952. /**
  18953. * Returns the current mesh absolute position.
  18954. * Retuns a Vector3.
  18955. */
  18956. get: function () {
  18957. return this._absolutePosition;
  18958. },
  18959. enumerable: true,
  18960. configurable: true
  18961. });
  18962. /**
  18963. * Sets a new matrix to apply before all other transformation
  18964. * @param matrix defines the transform matrix
  18965. * @returns the current TransformNode
  18966. */
  18967. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18968. return this.setPivotMatrix(matrix, false);
  18969. };
  18970. /**
  18971. * Sets a new pivot matrix to the current node
  18972. * @param matrix defines the new pivot matrix to use
  18973. * @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
  18974. * @returns the current TransformNode
  18975. */
  18976. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18977. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18978. this._pivotMatrix = matrix.clone();
  18979. this._cache.pivotMatrixUpdated = true;
  18980. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18981. if (this._postMultiplyPivotMatrix) {
  18982. if (!this._pivotMatrixInverse) {
  18983. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18984. }
  18985. else {
  18986. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18987. }
  18988. }
  18989. return this;
  18990. };
  18991. /**
  18992. * Returns the mesh pivot matrix.
  18993. * Default : Identity.
  18994. * A Matrix is returned.
  18995. */
  18996. TransformNode.prototype.getPivotMatrix = function () {
  18997. return this._pivotMatrix;
  18998. };
  18999. /**
  19000. * Prevents the World matrix to be computed any longer.
  19001. * Returns the TransformNode.
  19002. */
  19003. TransformNode.prototype.freezeWorldMatrix = function () {
  19004. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19005. this.computeWorldMatrix(true);
  19006. this._isWorldMatrixFrozen = true;
  19007. return this;
  19008. };
  19009. /**
  19010. * Allows back the World matrix computation.
  19011. * Returns the TransformNode.
  19012. */
  19013. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19014. this._isWorldMatrixFrozen = false;
  19015. this.computeWorldMatrix(true);
  19016. return this;
  19017. };
  19018. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19019. /**
  19020. * True if the World matrix has been frozen.
  19021. * Returns a boolean.
  19022. */
  19023. get: function () {
  19024. return this._isWorldMatrixFrozen;
  19025. },
  19026. enumerable: true,
  19027. configurable: true
  19028. });
  19029. /**
  19030. * Retuns the mesh absolute position in the World.
  19031. * Returns a Vector3.
  19032. */
  19033. TransformNode.prototype.getAbsolutePosition = function () {
  19034. this.computeWorldMatrix();
  19035. return this._absolutePosition;
  19036. };
  19037. /**
  19038. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19039. * Returns the TransformNode.
  19040. */
  19041. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19042. if (!absolutePosition) {
  19043. return this;
  19044. }
  19045. var absolutePositionX;
  19046. var absolutePositionY;
  19047. var absolutePositionZ;
  19048. if (absolutePosition.x === undefined) {
  19049. if (arguments.length < 3) {
  19050. return this;
  19051. }
  19052. absolutePositionX = arguments[0];
  19053. absolutePositionY = arguments[1];
  19054. absolutePositionZ = arguments[2];
  19055. }
  19056. else {
  19057. absolutePositionX = absolutePosition.x;
  19058. absolutePositionY = absolutePosition.y;
  19059. absolutePositionZ = absolutePosition.z;
  19060. }
  19061. if (this.parent) {
  19062. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19063. invertParentWorldMatrix.invert();
  19064. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19065. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19066. }
  19067. else {
  19068. this.position.x = absolutePositionX;
  19069. this.position.y = absolutePositionY;
  19070. this.position.z = absolutePositionZ;
  19071. }
  19072. return this;
  19073. };
  19074. /**
  19075. * Sets the mesh position in its local space.
  19076. * Returns the TransformNode.
  19077. */
  19078. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19079. this.computeWorldMatrix();
  19080. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19081. return this;
  19082. };
  19083. /**
  19084. * Returns the mesh position in the local space from the current World matrix values.
  19085. * Returns a new Vector3.
  19086. */
  19087. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19088. this.computeWorldMatrix();
  19089. var invLocalWorldMatrix = this._localWorld.clone();
  19090. invLocalWorldMatrix.invert();
  19091. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19092. };
  19093. /**
  19094. * Translates the mesh along the passed Vector3 in its local space.
  19095. * Returns the TransformNode.
  19096. */
  19097. TransformNode.prototype.locallyTranslate = function (vector3) {
  19098. this.computeWorldMatrix(true);
  19099. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19100. return this;
  19101. };
  19102. /**
  19103. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19104. * @param targetPoint the position (must be in same space as current mesh) to look at
  19105. * @param yawCor optional yaw (y-axis) correction in radians
  19106. * @param pitchCor optional pitch (x-axis) correction in radians
  19107. * @param rollCor optional roll (z-axis) correction in radians
  19108. * @param space the choosen space of the target
  19109. * @returns the TransformNode.
  19110. */
  19111. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19112. if (yawCor === void 0) { yawCor = 0; }
  19113. if (pitchCor === void 0) { pitchCor = 0; }
  19114. if (rollCor === void 0) { rollCor = 0; }
  19115. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19116. var dv = TransformNode._lookAtVectorCache;
  19117. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19118. targetPoint.subtractToRef(pos, dv);
  19119. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19120. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19121. var pitch = Math.atan2(dv.y, len);
  19122. if (this.rotationQuaternion) {
  19123. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19124. }
  19125. else {
  19126. this.rotation.x = pitch + pitchCor;
  19127. this.rotation.y = yaw + yawCor;
  19128. this.rotation.z = rollCor;
  19129. }
  19130. return this;
  19131. };
  19132. /**
  19133. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19134. * This Vector3 is expressed in the World space.
  19135. */
  19136. TransformNode.prototype.getDirection = function (localAxis) {
  19137. var result = BABYLON.Vector3.Zero();
  19138. this.getDirectionToRef(localAxis, result);
  19139. return result;
  19140. };
  19141. /**
  19142. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19143. * localAxis is expressed in the mesh local space.
  19144. * result is computed in the Wordl space from the mesh World matrix.
  19145. * Returns the TransformNode.
  19146. */
  19147. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19148. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19149. return this;
  19150. };
  19151. /**
  19152. * Sets a new pivot point to the current node
  19153. * @param point defines the new pivot point to use
  19154. * @param space defines if the point is in world or local space (local by default)
  19155. * @returns the current TransformNode
  19156. */
  19157. TransformNode.prototype.setPivotPoint = function (point, space) {
  19158. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19159. if (this.getScene().getRenderId() == 0) {
  19160. this.computeWorldMatrix(true);
  19161. }
  19162. var wm = this.getWorldMatrix();
  19163. if (space == BABYLON.Space.WORLD) {
  19164. var tmat = BABYLON.Tmp.Matrix[0];
  19165. wm.invertToRef(tmat);
  19166. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19167. }
  19168. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19169. };
  19170. /**
  19171. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19172. */
  19173. TransformNode.prototype.getPivotPoint = function () {
  19174. var point = BABYLON.Vector3.Zero();
  19175. this.getPivotPointToRef(point);
  19176. return point;
  19177. };
  19178. /**
  19179. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19180. * Returns the TransformNode.
  19181. */
  19182. TransformNode.prototype.getPivotPointToRef = function (result) {
  19183. result.x = -this._pivotMatrix.m[12];
  19184. result.y = -this._pivotMatrix.m[13];
  19185. result.z = -this._pivotMatrix.m[14];
  19186. return this;
  19187. };
  19188. /**
  19189. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19190. */
  19191. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19192. var point = BABYLON.Vector3.Zero();
  19193. this.getAbsolutePivotPointToRef(point);
  19194. return point;
  19195. };
  19196. /**
  19197. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19198. * Returns the TransformNode.
  19199. */
  19200. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19201. result.x = this._pivotMatrix.m[12];
  19202. result.y = this._pivotMatrix.m[13];
  19203. result.z = this._pivotMatrix.m[14];
  19204. this.getPivotPointToRef(result);
  19205. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19206. return this;
  19207. };
  19208. /**
  19209. * Defines the passed node as the parent of the current node.
  19210. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19211. * Returns the TransformNode.
  19212. */
  19213. TransformNode.prototype.setParent = function (node) {
  19214. if (!node && !this.parent) {
  19215. return this;
  19216. }
  19217. if (!node) {
  19218. var rotation = BABYLON.Tmp.Quaternion[0];
  19219. var position = BABYLON.Tmp.Vector3[0];
  19220. var scale = BABYLON.Tmp.Vector3[1];
  19221. if (this.parent && this.parent.computeWorldMatrix) {
  19222. this.parent.computeWorldMatrix(true);
  19223. }
  19224. this.computeWorldMatrix(true);
  19225. this.getWorldMatrix().decompose(scale, rotation, position);
  19226. if (this.rotationQuaternion) {
  19227. this.rotationQuaternion.copyFrom(rotation);
  19228. }
  19229. else {
  19230. rotation.toEulerAnglesToRef(this.rotation);
  19231. }
  19232. this.scaling.x = scale.x;
  19233. this.scaling.y = scale.y;
  19234. this.scaling.z = scale.z;
  19235. this.position.x = position.x;
  19236. this.position.y = position.y;
  19237. this.position.z = position.z;
  19238. }
  19239. else {
  19240. var rotation = BABYLON.Tmp.Quaternion[0];
  19241. var position = BABYLON.Tmp.Vector3[0];
  19242. var scale = BABYLON.Tmp.Vector3[1];
  19243. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19244. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19245. this.computeWorldMatrix(true);
  19246. node.computeWorldMatrix(true);
  19247. node.getWorldMatrix().invertToRef(invParentMatrix);
  19248. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19249. diffMatrix.decompose(scale, rotation, position);
  19250. if (this.rotationQuaternion) {
  19251. this.rotationQuaternion.copyFrom(rotation);
  19252. }
  19253. else {
  19254. rotation.toEulerAnglesToRef(this.rotation);
  19255. }
  19256. this.position.x = position.x;
  19257. this.position.y = position.y;
  19258. this.position.z = position.z;
  19259. this.scaling.x = scale.x;
  19260. this.scaling.y = scale.y;
  19261. this.scaling.z = scale.z;
  19262. }
  19263. this.parent = node;
  19264. return this;
  19265. };
  19266. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19267. get: function () {
  19268. return this._nonUniformScaling;
  19269. },
  19270. enumerable: true,
  19271. configurable: true
  19272. });
  19273. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19274. if (this._nonUniformScaling === value) {
  19275. return false;
  19276. }
  19277. this._nonUniformScaling = value;
  19278. return true;
  19279. };
  19280. /**
  19281. * Attach the current TransformNode to another TransformNode associated with a bone
  19282. * @param bone Bone affecting the TransformNode
  19283. * @param affectedTransformNode TransformNode associated with the bone
  19284. */
  19285. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19286. this._transformToBoneReferal = affectedTransformNode;
  19287. this.parent = bone;
  19288. if (bone.getWorldMatrix().determinant() < 0) {
  19289. this.scalingDeterminant *= -1;
  19290. }
  19291. return this;
  19292. };
  19293. TransformNode.prototype.detachFromBone = function () {
  19294. if (!this.parent) {
  19295. return this;
  19296. }
  19297. if (this.parent.getWorldMatrix().determinant() < 0) {
  19298. this.scalingDeterminant *= -1;
  19299. }
  19300. this._transformToBoneReferal = null;
  19301. this.parent = null;
  19302. return this;
  19303. };
  19304. /**
  19305. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19306. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19307. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19308. * The passed axis is also normalized.
  19309. * Returns the TransformNode.
  19310. */
  19311. TransformNode.prototype.rotate = function (axis, amount, space) {
  19312. axis.normalize();
  19313. if (!this.rotationQuaternion) {
  19314. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19315. this.rotation = BABYLON.Vector3.Zero();
  19316. }
  19317. var rotationQuaternion;
  19318. if (!space || space === BABYLON.Space.LOCAL) {
  19319. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19320. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19321. }
  19322. else {
  19323. if (this.parent) {
  19324. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19325. invertParentWorldMatrix.invert();
  19326. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19327. }
  19328. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19329. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19330. }
  19331. return this;
  19332. };
  19333. /**
  19334. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19335. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19336. * The passed axis is also normalized.
  19337. * Returns the TransformNode.
  19338. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19339. */
  19340. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19341. axis.normalize();
  19342. if (!this.rotationQuaternion) {
  19343. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19344. this.rotation.copyFromFloats(0, 0, 0);
  19345. }
  19346. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19347. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19348. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19349. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19350. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19351. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19352. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19353. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19354. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19355. return this;
  19356. };
  19357. /**
  19358. * Translates the mesh along the axis vector for the passed distance in the given space.
  19359. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19360. * Returns the TransformNode.
  19361. */
  19362. TransformNode.prototype.translate = function (axis, distance, space) {
  19363. var displacementVector = axis.scale(distance);
  19364. if (!space || space === BABYLON.Space.LOCAL) {
  19365. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19366. this.setPositionWithLocalVector(tempV3);
  19367. }
  19368. else {
  19369. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19370. }
  19371. return this;
  19372. };
  19373. /**
  19374. * Adds a rotation step to the mesh current rotation.
  19375. * x, y, z are Euler angles expressed in radians.
  19376. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19377. * This means this rotation is made in the mesh local space only.
  19378. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19379. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19380. * ```javascript
  19381. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19382. * ```
  19383. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19384. * 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.
  19385. * Returns the TransformNode.
  19386. */
  19387. TransformNode.prototype.addRotation = function (x, y, z) {
  19388. var rotationQuaternion;
  19389. if (this.rotationQuaternion) {
  19390. rotationQuaternion = this.rotationQuaternion;
  19391. }
  19392. else {
  19393. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19394. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19395. }
  19396. var accumulation = BABYLON.Tmp.Quaternion[0];
  19397. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19398. rotationQuaternion.multiplyInPlace(accumulation);
  19399. if (!this.rotationQuaternion) {
  19400. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19401. }
  19402. return this;
  19403. };
  19404. /**
  19405. * Computes the mesh World matrix and returns it.
  19406. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19407. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19408. * If the parameter `force`is set to `true`, the actual computation is done.
  19409. * Returns the mesh World Matrix.
  19410. */
  19411. TransformNode.prototype.computeWorldMatrix = function (force) {
  19412. if (this._isWorldMatrixFrozen) {
  19413. return this._worldMatrix;
  19414. }
  19415. if (!force && this.isSynchronized(true)) {
  19416. this._currentRenderId = this.getScene().getRenderId();
  19417. return this._worldMatrix;
  19418. }
  19419. this._cache.position.copyFrom(this.position);
  19420. this._cache.scaling.copyFrom(this.scaling);
  19421. this._cache.pivotMatrixUpdated = false;
  19422. this._cache.billboardMode = this.billboardMode;
  19423. this._currentRenderId = this.getScene().getRenderId();
  19424. this._childRenderId = this.getScene().getRenderId();
  19425. this._isDirty = false;
  19426. // Scaling
  19427. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19428. // Rotation
  19429. //rotate, if quaternion is set and rotation was used
  19430. if (this.rotationQuaternion) {
  19431. var len = this.rotation.length();
  19432. if (len) {
  19433. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19434. this.rotation.copyFromFloats(0, 0, 0);
  19435. }
  19436. }
  19437. if (this.rotationQuaternion) {
  19438. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19439. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19440. }
  19441. else {
  19442. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19443. this._cache.rotation.copyFrom(this.rotation);
  19444. }
  19445. // Translation
  19446. var camera = this.getScene().activeCamera;
  19447. if (this.infiniteDistance && !this.parent && camera) {
  19448. var cameraWorldMatrix = camera.getWorldMatrix();
  19449. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19450. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19451. }
  19452. else {
  19453. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19454. }
  19455. // Composing transformations
  19456. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19457. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19458. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19459. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19460. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19461. // Need to decompose each rotation here
  19462. var currentPosition = BABYLON.Tmp.Vector3[3];
  19463. if (this.parent && this.parent.getWorldMatrix) {
  19464. if (this._transformToBoneReferal) {
  19465. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19466. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19467. }
  19468. else {
  19469. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19470. }
  19471. }
  19472. else {
  19473. currentPosition.copyFrom(this.position);
  19474. }
  19475. currentPosition.subtractInPlace(camera.globalPosition);
  19476. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19477. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19478. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19479. }
  19480. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19481. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19482. }
  19483. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19484. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19485. }
  19486. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19487. }
  19488. else {
  19489. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19490. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19491. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19492. }
  19493. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19494. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19495. }
  19496. // Local world
  19497. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19498. // Parent
  19499. if (this.parent && this.parent.getWorldMatrix) {
  19500. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19501. if (this._transformToBoneReferal) {
  19502. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19503. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19504. }
  19505. else {
  19506. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19507. }
  19508. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19509. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19510. this._worldMatrix.copyFrom(this._localWorld);
  19511. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19512. }
  19513. else {
  19514. if (this._transformToBoneReferal) {
  19515. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19516. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19517. }
  19518. else {
  19519. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19520. }
  19521. }
  19522. this._markSyncedWithParent();
  19523. }
  19524. else {
  19525. this._worldMatrix.copyFrom(this._localWorld);
  19526. }
  19527. // Post multiply inverse of pivotMatrix
  19528. if (this._postMultiplyPivotMatrix) {
  19529. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19530. }
  19531. // Normal matrix
  19532. if (!this.ignoreNonUniformScaling) {
  19533. if (this.scaling.isNonUniform) {
  19534. this._updateNonUniformScalingState(true);
  19535. }
  19536. else if (this.parent && this.parent._nonUniformScaling) {
  19537. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19538. }
  19539. else {
  19540. this._updateNonUniformScalingState(false);
  19541. }
  19542. }
  19543. else {
  19544. this._updateNonUniformScalingState(false);
  19545. }
  19546. this._afterComputeWorldMatrix();
  19547. // Absolute position
  19548. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19549. // Callbacks
  19550. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19551. if (!this._poseMatrix) {
  19552. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19553. }
  19554. // Cache the determinant
  19555. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19556. return this._worldMatrix;
  19557. };
  19558. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19559. };
  19560. /**
  19561. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19562. * @param func: callback function to add
  19563. *
  19564. * Returns the TransformNode.
  19565. */
  19566. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19567. this.onAfterWorldMatrixUpdateObservable.add(func);
  19568. return this;
  19569. };
  19570. /**
  19571. * Removes a registered callback function.
  19572. * Returns the TransformNode.
  19573. */
  19574. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19575. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19576. return this;
  19577. };
  19578. /**
  19579. * Clone the current transform node
  19580. * Returns the new transform node
  19581. * @param name Name of the new clone
  19582. * @param newParent New parent for the clone
  19583. * @param doNotCloneChildren Do not clone children hierarchy
  19584. */
  19585. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19586. var _this = this;
  19587. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19588. result.name = name;
  19589. result.id = name;
  19590. if (newParent) {
  19591. result.parent = newParent;
  19592. }
  19593. if (!doNotCloneChildren) {
  19594. // Children
  19595. var directDescendants = this.getDescendants(true);
  19596. for (var index = 0; index < directDescendants.length; index++) {
  19597. var child = directDescendants[index];
  19598. if (child.clone) {
  19599. child.clone(name + "." + child.name, result);
  19600. }
  19601. }
  19602. }
  19603. return result;
  19604. };
  19605. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19606. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19607. serializationObject.type = this.getClassName();
  19608. // Parent
  19609. if (this.parent) {
  19610. serializationObject.parentId = this.parent.id;
  19611. }
  19612. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19613. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19614. }
  19615. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19616. serializationObject.isEnabled = this.isEnabled();
  19617. // Parent
  19618. if (this.parent) {
  19619. serializationObject.parentId = this.parent.id;
  19620. }
  19621. return serializationObject;
  19622. };
  19623. // Statics
  19624. /**
  19625. * Returns a new TransformNode object parsed from the source provided.
  19626. * The parameter `parsedMesh` is the source.
  19627. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19628. */
  19629. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19630. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19631. if (BABYLON.Tags) {
  19632. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19633. }
  19634. if (parsedTransformNode.localMatrix) {
  19635. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19636. }
  19637. else if (parsedTransformNode.pivotMatrix) {
  19638. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19639. }
  19640. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19641. // Parent
  19642. if (parsedTransformNode.parentId) {
  19643. transformNode._waitingParentId = parsedTransformNode.parentId;
  19644. }
  19645. return transformNode;
  19646. };
  19647. /**
  19648. * Releases resources associated with this transform node.
  19649. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19650. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19651. */
  19652. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19653. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19654. // Animations
  19655. this.getScene().stopAnimation(this);
  19656. // Remove from scene
  19657. this.getScene().removeTransformNode(this);
  19658. this.onAfterWorldMatrixUpdateObservable.clear();
  19659. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19660. };
  19661. // Statics
  19662. TransformNode.BILLBOARDMODE_NONE = 0;
  19663. TransformNode.BILLBOARDMODE_X = 1;
  19664. TransformNode.BILLBOARDMODE_Y = 2;
  19665. TransformNode.BILLBOARDMODE_Z = 4;
  19666. TransformNode.BILLBOARDMODE_ALL = 7;
  19667. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19668. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19669. __decorate([
  19670. BABYLON.serializeAsVector3()
  19671. ], TransformNode.prototype, "_rotation", void 0);
  19672. __decorate([
  19673. BABYLON.serializeAsQuaternion()
  19674. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19675. __decorate([
  19676. BABYLON.serializeAsVector3()
  19677. ], TransformNode.prototype, "_scaling", void 0);
  19678. __decorate([
  19679. BABYLON.serialize()
  19680. ], TransformNode.prototype, "billboardMode", void 0);
  19681. __decorate([
  19682. BABYLON.serialize()
  19683. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19684. __decorate([
  19685. BABYLON.serialize()
  19686. ], TransformNode.prototype, "infiniteDistance", void 0);
  19687. __decorate([
  19688. BABYLON.serialize()
  19689. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19690. __decorate([
  19691. BABYLON.serializeAsVector3()
  19692. ], TransformNode.prototype, "position", void 0);
  19693. return TransformNode;
  19694. }(BABYLON.Node));
  19695. BABYLON.TransformNode = TransformNode;
  19696. })(BABYLON || (BABYLON = {}));
  19697. //# sourceMappingURL=babylon.transformNode.js.map
  19698. var BABYLON;
  19699. (function (BABYLON) {
  19700. /**
  19701. * Class used to store all common mesh properties
  19702. */
  19703. var AbstractMesh = /** @class */ (function (_super) {
  19704. __extends(AbstractMesh, _super);
  19705. // Constructor
  19706. /**
  19707. * Creates a new AbstractMesh
  19708. * @param name defines the name of the mesh
  19709. * @param scene defines the hosting scene
  19710. */
  19711. function AbstractMesh(name, scene) {
  19712. if (scene === void 0) { scene = null; }
  19713. var _this = _super.call(this, name, scene, false) || this;
  19714. _this._facetNb = 0; // facet number
  19715. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19716. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19717. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19718. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19719. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19720. _this._subDiv = {
  19721. max: 1,
  19722. X: 1,
  19723. Y: 1,
  19724. Z: 1
  19725. };
  19726. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19727. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19728. // Events
  19729. /**
  19730. * An event triggered when this mesh collides with another one
  19731. */
  19732. _this.onCollideObservable = new BABYLON.Observable();
  19733. /**
  19734. * An event triggered when the collision's position changes
  19735. */
  19736. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19737. /**
  19738. * An event triggered when material is changed
  19739. */
  19740. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19741. // Properties
  19742. /**
  19743. * Gets or sets the orientation for POV movement & rotation
  19744. */
  19745. _this.definedFacingForward = true;
  19746. /**
  19747. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19748. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19749. * * 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.
  19750. * @see http://doc.babylonjs.com/features/occlusionquery
  19751. */
  19752. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19753. /**
  19754. * 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:
  19755. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19756. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19757. * * 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.
  19758. * @see http://doc.babylonjs.com/features/occlusionquery
  19759. */
  19760. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19761. /**
  19762. * 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.
  19763. * The default value is -1 which means don't break the query and wait till the result
  19764. * @see http://doc.babylonjs.com/features/occlusionquery
  19765. */
  19766. _this.occlusionRetryCount = -1;
  19767. _this._occlusionInternalRetryCounter = 0;
  19768. _this._isOccluded = false;
  19769. _this._isOcclusionQueryInProgress = false;
  19770. _this._visibility = 1.0;
  19771. /** Gets or sets the alpha index used to sort transparent meshes
  19772. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19773. */
  19774. _this.alphaIndex = Number.MAX_VALUE;
  19775. /**
  19776. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19777. */
  19778. _this.isVisible = true;
  19779. /**
  19780. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19781. */
  19782. _this.isPickable = true;
  19783. /**
  19784. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19785. */
  19786. _this.showBoundingBox = false;
  19787. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19788. _this.showSubMeshesBoundingBox = false;
  19789. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19790. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19791. */
  19792. _this.isBlocker = false;
  19793. /**
  19794. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19795. */
  19796. _this.enablePointerMoveEvents = false;
  19797. /**
  19798. * Specifies the rendering group id for this mesh (0 by default)
  19799. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19800. */
  19801. _this.renderingGroupId = 0;
  19802. _this._receiveShadows = false;
  19803. /**
  19804. * Gets or sets a boolean indicating if the outline must be rendered as well
  19805. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19806. */
  19807. _this.renderOutline = false;
  19808. /** Defines color to use when rendering outline */
  19809. _this.outlineColor = BABYLON.Color3.Red();
  19810. /** Define width to use when rendering outline */
  19811. _this.outlineWidth = 0.02;
  19812. /**
  19813. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19814. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19815. */
  19816. _this.renderOverlay = false;
  19817. /** Defines color to use when rendering overlay */
  19818. _this.overlayColor = BABYLON.Color3.Red();
  19819. /** Defines alpha to use when rendering overlay */
  19820. _this.overlayAlpha = 0.5;
  19821. _this._hasVertexAlpha = false;
  19822. _this._useVertexColors = true;
  19823. _this._computeBonesUsingShaders = true;
  19824. _this._numBoneInfluencers = 4;
  19825. _this._applyFog = true;
  19826. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19827. _this.useOctreeForRenderingSelection = true;
  19828. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19829. _this.useOctreeForPicking = true;
  19830. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19831. _this.useOctreeForCollisions = true;
  19832. _this._layerMask = 0x0FFFFFFF;
  19833. /**
  19834. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19835. */
  19836. _this.alwaysSelectAsActiveMesh = false;
  19837. /**
  19838. * Gets or sets the current action manager
  19839. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19840. */
  19841. _this.actionManager = null;
  19842. /**
  19843. * Gets or sets impostor used for physic simulation
  19844. * @see http://doc.babylonjs.com/features/physics_engine
  19845. */
  19846. _this.physicsImpostor = null;
  19847. // Collisions
  19848. _this._checkCollisions = false;
  19849. _this._collisionMask = -1;
  19850. _this._collisionGroup = -1;
  19851. /**
  19852. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19853. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19854. */
  19855. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19856. /**
  19857. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19858. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19859. */
  19860. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19861. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19862. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19863. // Edges
  19864. /**
  19865. * Defines edge width used when edgesRenderer is enabled
  19866. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19867. */
  19868. _this.edgesWidth = 1;
  19869. /**
  19870. * Defines edge color used when edgesRenderer is enabled
  19871. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19872. */
  19873. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19874. // Cache
  19875. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19876. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19877. /** @hidden */
  19878. _this._renderId = 0;
  19879. /** @hidden */
  19880. _this._intersectionsInProgress = new Array();
  19881. /** @hidden */
  19882. _this._unIndexed = false;
  19883. /** @hidden */
  19884. _this._lightSources = new Array();
  19885. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19886. if (collidedMesh === void 0) { collidedMesh = null; }
  19887. //TODO move this to the collision coordinator!
  19888. if (_this.getScene().workerCollisions)
  19889. newPosition.multiplyInPlace(_this._collider._radius);
  19890. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19891. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19892. _this.position.addInPlace(_this._diffPositionForCollisions);
  19893. }
  19894. if (collidedMesh) {
  19895. _this.onCollideObservable.notifyObservers(collidedMesh);
  19896. }
  19897. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19898. };
  19899. _this.getScene().addMesh(_this);
  19900. _this._resyncLightSources();
  19901. return _this;
  19902. }
  19903. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19904. /**
  19905. * No billboard
  19906. */
  19907. get: function () {
  19908. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19914. /** Billboard on X axis */
  19915. get: function () {
  19916. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19917. },
  19918. enumerable: true,
  19919. configurable: true
  19920. });
  19921. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19922. /** Billboard on Y axis */
  19923. get: function () {
  19924. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19925. },
  19926. enumerable: true,
  19927. configurable: true
  19928. });
  19929. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19930. /** Billboard on Z axis */
  19931. get: function () {
  19932. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19938. /** Billboard on all axes */
  19939. get: function () {
  19940. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19941. },
  19942. enumerable: true,
  19943. configurable: true
  19944. });
  19945. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19946. /**
  19947. * Gets the number of facets in the mesh
  19948. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19949. */
  19950. get: function () {
  19951. return this._facetNb;
  19952. },
  19953. enumerable: true,
  19954. configurable: true
  19955. });
  19956. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19957. /**
  19958. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19959. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19960. */
  19961. get: function () {
  19962. return this._partitioningSubdivisions;
  19963. },
  19964. set: function (nb) {
  19965. this._partitioningSubdivisions = nb;
  19966. },
  19967. enumerable: true,
  19968. configurable: true
  19969. });
  19970. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19971. /**
  19972. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19973. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19974. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19975. */
  19976. get: function () {
  19977. return this._partitioningBBoxRatio;
  19978. },
  19979. set: function (ratio) {
  19980. this._partitioningBBoxRatio = ratio;
  19981. },
  19982. enumerable: true,
  19983. configurable: true
  19984. });
  19985. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19986. /**
  19987. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19988. * Works only for updatable meshes.
  19989. * Doesn't work with multi-materials
  19990. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19991. */
  19992. get: function () {
  19993. return this._facetDepthSort;
  19994. },
  19995. set: function (sort) {
  19996. this._facetDepthSort = sort;
  19997. },
  19998. enumerable: true,
  19999. configurable: true
  20000. });
  20001. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20002. /**
  20003. * The location (Vector3) where the facet depth sort must be computed from.
  20004. * By default, the active camera position.
  20005. * Used only when facet depth sort is enabled
  20006. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20007. */
  20008. get: function () {
  20009. return this._facetDepthSortFrom;
  20010. },
  20011. set: function (location) {
  20012. this._facetDepthSortFrom = location;
  20013. },
  20014. enumerable: true,
  20015. configurable: true
  20016. });
  20017. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20018. /**
  20019. * gets a boolean indicating if facetData is enabled
  20020. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20021. */
  20022. get: function () {
  20023. return this._facetDataEnabled;
  20024. },
  20025. enumerable: true,
  20026. configurable: true
  20027. });
  20028. /** @hidden */
  20029. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20030. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20031. return false;
  20032. }
  20033. this._markSubMeshesAsMiscDirty();
  20034. return true;
  20035. };
  20036. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20037. /** Set a function to call when this mesh collides with another one */
  20038. set: function (callback) {
  20039. if (this._onCollideObserver) {
  20040. this.onCollideObservable.remove(this._onCollideObserver);
  20041. }
  20042. this._onCollideObserver = this.onCollideObservable.add(callback);
  20043. },
  20044. enumerable: true,
  20045. configurable: true
  20046. });
  20047. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20048. /** Set a function to call when the collision's position changes */
  20049. set: function (callback) {
  20050. if (this._onCollisionPositionChangeObserver) {
  20051. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20052. }
  20053. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20054. },
  20055. enumerable: true,
  20056. configurable: true
  20057. });
  20058. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  20059. /**
  20060. * 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
  20061. * @see http://doc.babylonjs.com/features/occlusionquery
  20062. */
  20063. get: function () {
  20064. return this._isOccluded;
  20065. },
  20066. set: function (value) {
  20067. this._isOccluded = value;
  20068. },
  20069. enumerable: true,
  20070. configurable: true
  20071. });
  20072. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  20073. /**
  20074. * Flag to check the progress status of the query
  20075. * @see http://doc.babylonjs.com/features/occlusionquery
  20076. */
  20077. get: function () {
  20078. return this._isOcclusionQueryInProgress;
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20084. /**
  20085. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20086. */
  20087. get: function () {
  20088. return this._visibility;
  20089. },
  20090. /**
  20091. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20092. */
  20093. set: function (value) {
  20094. if (this._visibility === value) {
  20095. return;
  20096. }
  20097. this._visibility = value;
  20098. this._markSubMeshesAsMiscDirty();
  20099. },
  20100. enumerable: true,
  20101. configurable: true
  20102. });
  20103. Object.defineProperty(AbstractMesh.prototype, "material", {
  20104. /** Gets or sets current material */
  20105. get: function () {
  20106. return this._material;
  20107. },
  20108. set: function (value) {
  20109. if (this._material === value) {
  20110. return;
  20111. }
  20112. this._material = value;
  20113. if (this.onMaterialChangedObservable.hasObservers) {
  20114. this.onMaterialChangedObservable.notifyObservers(this);
  20115. }
  20116. if (!this.subMeshes) {
  20117. return;
  20118. }
  20119. this._unBindEffect();
  20120. },
  20121. enumerable: true,
  20122. configurable: true
  20123. });
  20124. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20125. /**
  20126. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20127. * @see http://doc.babylonjs.com/babylon101/shadows
  20128. */
  20129. get: function () {
  20130. return this._receiveShadows;
  20131. },
  20132. set: function (value) {
  20133. if (this._receiveShadows === value) {
  20134. return;
  20135. }
  20136. this._receiveShadows = value;
  20137. this._markSubMeshesAsLightDirty();
  20138. },
  20139. enumerable: true,
  20140. configurable: true
  20141. });
  20142. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20143. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20144. get: function () {
  20145. return this._hasVertexAlpha;
  20146. },
  20147. set: function (value) {
  20148. if (this._hasVertexAlpha === value) {
  20149. return;
  20150. }
  20151. this._hasVertexAlpha = value;
  20152. this._markSubMeshesAsAttributesDirty();
  20153. this._markSubMeshesAsMiscDirty();
  20154. },
  20155. enumerable: true,
  20156. configurable: true
  20157. });
  20158. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20159. /** 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) */
  20160. get: function () {
  20161. return this._useVertexColors;
  20162. },
  20163. set: function (value) {
  20164. if (this._useVertexColors === value) {
  20165. return;
  20166. }
  20167. this._useVertexColors = value;
  20168. this._markSubMeshesAsAttributesDirty();
  20169. },
  20170. enumerable: true,
  20171. configurable: true
  20172. });
  20173. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20174. /**
  20175. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20176. */
  20177. get: function () {
  20178. return this._computeBonesUsingShaders;
  20179. },
  20180. set: function (value) {
  20181. if (this._computeBonesUsingShaders === value) {
  20182. return;
  20183. }
  20184. this._computeBonesUsingShaders = value;
  20185. this._markSubMeshesAsAttributesDirty();
  20186. },
  20187. enumerable: true,
  20188. configurable: true
  20189. });
  20190. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20191. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20192. get: function () {
  20193. return this._numBoneInfluencers;
  20194. },
  20195. set: function (value) {
  20196. if (this._numBoneInfluencers === value) {
  20197. return;
  20198. }
  20199. this._numBoneInfluencers = value;
  20200. this._markSubMeshesAsAttributesDirty();
  20201. },
  20202. enumerable: true,
  20203. configurable: true
  20204. });
  20205. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20206. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20207. get: function () {
  20208. return this._applyFog;
  20209. },
  20210. set: function (value) {
  20211. if (this._applyFog === value) {
  20212. return;
  20213. }
  20214. this._applyFog = value;
  20215. this._markSubMeshesAsMiscDirty();
  20216. },
  20217. enumerable: true,
  20218. configurable: true
  20219. });
  20220. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20221. /**
  20222. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20223. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20224. */
  20225. get: function () {
  20226. return this._layerMask;
  20227. },
  20228. set: function (value) {
  20229. if (value === this._layerMask) {
  20230. return;
  20231. }
  20232. this._layerMask = value;
  20233. this._resyncLightSources();
  20234. },
  20235. enumerable: true,
  20236. configurable: true
  20237. });
  20238. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20239. /**
  20240. * Gets or sets a collision mask used to mask collisions (default is -1).
  20241. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20242. */
  20243. get: function () {
  20244. return this._collisionMask;
  20245. },
  20246. set: function (mask) {
  20247. this._collisionMask = !isNaN(mask) ? mask : -1;
  20248. },
  20249. enumerable: true,
  20250. configurable: true
  20251. });
  20252. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20253. /**
  20254. * Gets or sets the current collision group mask (-1 by default).
  20255. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20256. */
  20257. get: function () {
  20258. return this._collisionGroup;
  20259. },
  20260. set: function (mask) {
  20261. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20262. },
  20263. enumerable: true,
  20264. configurable: true
  20265. });
  20266. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20267. /** @hidden */
  20268. get: function () {
  20269. return null;
  20270. },
  20271. enumerable: true,
  20272. configurable: true
  20273. });
  20274. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20275. get: function () {
  20276. return this._skeleton;
  20277. },
  20278. /**
  20279. * Gets or sets a skeleton to apply skining transformations
  20280. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20281. */
  20282. set: function (value) {
  20283. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20284. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20285. }
  20286. if (value && value.needInitialSkinMatrix) {
  20287. value._registerMeshWithPoseMatrix(this);
  20288. }
  20289. this._skeleton = value;
  20290. if (!this._skeleton) {
  20291. this._bonesTransformMatrices = null;
  20292. }
  20293. this._markSubMeshesAsAttributesDirty();
  20294. },
  20295. enumerable: true,
  20296. configurable: true
  20297. });
  20298. /**
  20299. * Returns the string "AbstractMesh"
  20300. * @returns "AbstractMesh"
  20301. */
  20302. AbstractMesh.prototype.getClassName = function () {
  20303. return "AbstractMesh";
  20304. };
  20305. /**
  20306. * Gets a string representation of the current mesh
  20307. * @param fullDetails defines a boolean indicating if full details must be included
  20308. * @returns a string representation of the current mesh
  20309. */
  20310. AbstractMesh.prototype.toString = function (fullDetails) {
  20311. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20312. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20313. if (this._skeleton) {
  20314. ret += ", skeleton: " + this._skeleton.name;
  20315. }
  20316. if (fullDetails) {
  20317. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20318. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20319. }
  20320. return ret;
  20321. };
  20322. /** @hidden */
  20323. AbstractMesh.prototype._rebuild = function () {
  20324. if (this._occlusionQuery) {
  20325. this._occlusionQuery = null;
  20326. }
  20327. if (this._edgesRenderer) {
  20328. this._edgesRenderer._rebuild();
  20329. }
  20330. if (!this.subMeshes) {
  20331. return;
  20332. }
  20333. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20334. var subMesh = _a[_i];
  20335. subMesh._rebuild();
  20336. }
  20337. };
  20338. /** @hidden */
  20339. AbstractMesh.prototype._resyncLightSources = function () {
  20340. this._lightSources.length = 0;
  20341. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20342. var light = _a[_i];
  20343. if (!light.isEnabled()) {
  20344. continue;
  20345. }
  20346. if (light.canAffectMesh(this)) {
  20347. this._lightSources.push(light);
  20348. }
  20349. }
  20350. this._markSubMeshesAsLightDirty();
  20351. };
  20352. /** @hidden */
  20353. AbstractMesh.prototype._resyncLighSource = function (light) {
  20354. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20355. var index = this._lightSources.indexOf(light);
  20356. if (index === -1) {
  20357. if (!isIn) {
  20358. return;
  20359. }
  20360. this._lightSources.push(light);
  20361. }
  20362. else {
  20363. if (isIn) {
  20364. return;
  20365. }
  20366. this._lightSources.splice(index, 1);
  20367. }
  20368. this._markSubMeshesAsLightDirty();
  20369. };
  20370. /** @hidden */
  20371. AbstractMesh.prototype._unBindEffect = function () {
  20372. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20373. var subMesh = _a[_i];
  20374. subMesh.setEffect(null);
  20375. }
  20376. };
  20377. /** @hidden */
  20378. AbstractMesh.prototype._removeLightSource = function (light) {
  20379. var index = this._lightSources.indexOf(light);
  20380. if (index === -1) {
  20381. return;
  20382. }
  20383. this._lightSources.splice(index, 1);
  20384. this._markSubMeshesAsLightDirty();
  20385. };
  20386. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20387. if (!this.subMeshes) {
  20388. return;
  20389. }
  20390. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20391. var subMesh = _a[_i];
  20392. if (subMesh._materialDefines) {
  20393. func(subMesh._materialDefines);
  20394. }
  20395. }
  20396. };
  20397. /** @hidden */
  20398. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20399. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20400. };
  20401. /** @hidden */
  20402. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20403. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20404. };
  20405. /** @hidden */
  20406. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20407. if (!this.subMeshes) {
  20408. return;
  20409. }
  20410. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20411. var subMesh = _a[_i];
  20412. var material = subMesh.getMaterial();
  20413. if (material) {
  20414. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20415. }
  20416. }
  20417. };
  20418. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20419. /**
  20420. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20421. */
  20422. get: function () {
  20423. return this._scaling;
  20424. },
  20425. set: function (newScaling) {
  20426. this._scaling = newScaling;
  20427. if (this.physicsImpostor) {
  20428. this.physicsImpostor.forceUpdate();
  20429. }
  20430. },
  20431. enumerable: true,
  20432. configurable: true
  20433. });
  20434. // Methods
  20435. /**
  20436. * Disables the mesh edge rendering mode
  20437. * @returns the currentAbstractMesh
  20438. */
  20439. AbstractMesh.prototype.disableEdgesRendering = function () {
  20440. if (this._edgesRenderer) {
  20441. this._edgesRenderer.dispose();
  20442. this._edgesRenderer = null;
  20443. }
  20444. return this;
  20445. };
  20446. /**
  20447. * Enables the edge rendering mode on the mesh.
  20448. * This mode makes the mesh edges visible
  20449. * @param epsilon defines the maximal distance between two angles to detect a face
  20450. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20451. * @returns the currentAbstractMesh
  20452. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20453. */
  20454. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20455. if (epsilon === void 0) { epsilon = 0.95; }
  20456. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20457. this.disableEdgesRendering();
  20458. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20459. return this;
  20460. };
  20461. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20462. /**
  20463. * Gets the edgesRenderer associated with the mesh
  20464. */
  20465. get: function () {
  20466. return this._edgesRenderer;
  20467. },
  20468. enumerable: true,
  20469. configurable: true
  20470. });
  20471. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20472. /**
  20473. * Returns true if the mesh is blocked. Implemented by child classes
  20474. */
  20475. get: function () {
  20476. return false;
  20477. },
  20478. enumerable: true,
  20479. configurable: true
  20480. });
  20481. /**
  20482. * Returns the mesh itself by default. Implemented by child classes
  20483. * @param camera defines the camera to use to pick the right LOD level
  20484. * @returns the currentAbstractMesh
  20485. */
  20486. AbstractMesh.prototype.getLOD = function (camera) {
  20487. return this;
  20488. };
  20489. /**
  20490. * Returns 0 by default. Implemented by child classes
  20491. * @returns an integer
  20492. */
  20493. AbstractMesh.prototype.getTotalVertices = function () {
  20494. return 0;
  20495. };
  20496. /**
  20497. * Returns null by default. Implemented by child classes
  20498. * @returns null
  20499. */
  20500. AbstractMesh.prototype.getIndices = function () {
  20501. return null;
  20502. };
  20503. /**
  20504. * Returns the array of the requested vertex data kind. Implemented by child classes
  20505. * @param kind defines the vertex data kind to use
  20506. * @returns null
  20507. */
  20508. AbstractMesh.prototype.getVerticesData = function (kind) {
  20509. return null;
  20510. };
  20511. /**
  20512. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20513. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20514. * Note that a new underlying VertexBuffer object is created each call.
  20515. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20516. * @param kind defines vertex data kind:
  20517. * * BABYLON.VertexBuffer.PositionKind
  20518. * * BABYLON.VertexBuffer.UVKind
  20519. * * BABYLON.VertexBuffer.UV2Kind
  20520. * * BABYLON.VertexBuffer.UV3Kind
  20521. * * BABYLON.VertexBuffer.UV4Kind
  20522. * * BABYLON.VertexBuffer.UV5Kind
  20523. * * BABYLON.VertexBuffer.UV6Kind
  20524. * * BABYLON.VertexBuffer.ColorKind
  20525. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20526. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20527. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20528. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20529. * @param data defines the data source
  20530. * @param updatable defines if the data must be flagged as updatable (or static)
  20531. * @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
  20532. * @returns the current mesh
  20533. */
  20534. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20535. return this;
  20536. };
  20537. /**
  20538. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20539. * If the mesh has no geometry, it is simply returned as it is.
  20540. * @param kind defines vertex data kind:
  20541. * * BABYLON.VertexBuffer.PositionKind
  20542. * * BABYLON.VertexBuffer.UVKind
  20543. * * BABYLON.VertexBuffer.UV2Kind
  20544. * * BABYLON.VertexBuffer.UV3Kind
  20545. * * BABYLON.VertexBuffer.UV4Kind
  20546. * * BABYLON.VertexBuffer.UV5Kind
  20547. * * BABYLON.VertexBuffer.UV6Kind
  20548. * * BABYLON.VertexBuffer.ColorKind
  20549. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20550. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20551. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20552. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20553. * @param data defines the data source
  20554. * @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
  20555. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20556. * @returns the current mesh
  20557. */
  20558. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20559. return this;
  20560. };
  20561. /**
  20562. * Sets the mesh indices,
  20563. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20564. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20565. * @param totalVertices Defines the total number of vertices
  20566. * @returns the current mesh
  20567. */
  20568. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20569. return this;
  20570. };
  20571. /**
  20572. * Gets a boolean indicating if specific vertex data is present
  20573. * @param kind defines the vertex data kind to use
  20574. * @returns true is data kind is present
  20575. */
  20576. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20577. return false;
  20578. };
  20579. /**
  20580. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20581. * @returns a BoundingInfo
  20582. */
  20583. AbstractMesh.prototype.getBoundingInfo = function () {
  20584. if (this._masterMesh) {
  20585. return this._masterMesh.getBoundingInfo();
  20586. }
  20587. if (!this._boundingInfo) {
  20588. // this._boundingInfo is being created here
  20589. this._updateBoundingInfo();
  20590. }
  20591. // cannot be null.
  20592. return this._boundingInfo;
  20593. };
  20594. /**
  20595. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20596. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20597. * @returns the current mesh
  20598. */
  20599. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20600. if (includeDescendants === void 0) { includeDescendants = true; }
  20601. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20602. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20603. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20604. if (maxDimension === 0) {
  20605. return this;
  20606. }
  20607. var scale = 1 / maxDimension;
  20608. this.scaling.scaleInPlace(scale);
  20609. return this;
  20610. };
  20611. /**
  20612. * Overwrite the current bounding info
  20613. * @param boundingInfo defines the new bounding info
  20614. * @returns the current mesh
  20615. */
  20616. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20617. this._boundingInfo = boundingInfo;
  20618. return this;
  20619. };
  20620. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20621. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20622. get: function () {
  20623. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20624. },
  20625. enumerable: true,
  20626. configurable: true
  20627. });
  20628. /** @hidden */
  20629. AbstractMesh.prototype._preActivate = function () {
  20630. };
  20631. /** @hidden */
  20632. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20633. };
  20634. /** @hidden */
  20635. AbstractMesh.prototype._activate = function (renderId) {
  20636. this._renderId = renderId;
  20637. };
  20638. /**
  20639. * Gets the current world matrix
  20640. * @returns a Matrix
  20641. */
  20642. AbstractMesh.prototype.getWorldMatrix = function () {
  20643. if (this._masterMesh) {
  20644. return this._masterMesh.getWorldMatrix();
  20645. }
  20646. return _super.prototype.getWorldMatrix.call(this);
  20647. };
  20648. /** @hidden */
  20649. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20650. if (this._masterMesh) {
  20651. return this._masterMesh._getWorldMatrixDeterminant();
  20652. }
  20653. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20654. };
  20655. // ================================== Point of View Movement =================================
  20656. /**
  20657. * Perform relative position change from the point of view of behind the front of the mesh.
  20658. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20659. * Supports definition of mesh facing forward or backward
  20660. * @param amountRight defines the distance on the right axis
  20661. * @param amountUp defines the distance on the up axis
  20662. * @param amountForward defines the distance on the forward axis
  20663. * @returns the current mesh
  20664. */
  20665. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20666. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20667. return this;
  20668. };
  20669. /**
  20670. * Calculate relative position change from the point of view of behind the front of the mesh.
  20671. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20672. * Supports definition of mesh facing forward or backward
  20673. * @param amountRight defines the distance on the right axis
  20674. * @param amountUp defines the distance on the up axis
  20675. * @param amountForward defines the distance on the forward axis
  20676. * @returns the new displacement vector
  20677. */
  20678. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20679. var rotMatrix = new BABYLON.Matrix();
  20680. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20681. rotQuaternion.toRotationMatrix(rotMatrix);
  20682. var translationDelta = BABYLON.Vector3.Zero();
  20683. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20685. return translationDelta;
  20686. };
  20687. // ================================== Point of View Rotation =================================
  20688. /**
  20689. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20690. * Supports definition of mesh facing forward or backward
  20691. * @param flipBack defines the flip
  20692. * @param twirlClockwise defines the twirl
  20693. * @param tiltRight defines the tilt
  20694. * @returns the current mesh
  20695. */
  20696. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20697. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20698. return this;
  20699. };
  20700. /**
  20701. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20702. * Supports definition of mesh facing forward or backward.
  20703. * @param flipBack defines the flip
  20704. * @param twirlClockwise defines the twirl
  20705. * @param tiltRight defines the tilt
  20706. * @returns the new rotation vector
  20707. */
  20708. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20709. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20710. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20711. };
  20712. /**
  20713. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20714. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20715. * @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
  20716. * @returns the new bounding vectors
  20717. */
  20718. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20719. if (includeDescendants === void 0) { includeDescendants = true; }
  20720. if (predicate === void 0) { predicate = null; }
  20721. // Ensures that all world matrix will be recomputed.
  20722. this.getScene().incrementRenderId();
  20723. this.computeWorldMatrix(true);
  20724. var min;
  20725. var max;
  20726. var boundingInfo = this.getBoundingInfo();
  20727. if (!this.subMeshes) {
  20728. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20729. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20730. }
  20731. else {
  20732. min = boundingInfo.boundingBox.minimumWorld;
  20733. max = boundingInfo.boundingBox.maximumWorld;
  20734. }
  20735. if (includeDescendants) {
  20736. var descendants = this.getDescendants(false);
  20737. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20738. var descendant = descendants_1[_i];
  20739. var childMesh = descendant;
  20740. childMesh.computeWorldMatrix(true);
  20741. // Filters meshes based on custom predicate function.
  20742. if (predicate && !predicate(childMesh)) {
  20743. continue;
  20744. }
  20745. //make sure we have the needed params to get mix and max
  20746. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20747. continue;
  20748. }
  20749. var childBoundingInfo = childMesh.getBoundingInfo();
  20750. var boundingBox = childBoundingInfo.boundingBox;
  20751. var minBox = boundingBox.minimumWorld;
  20752. var maxBox = boundingBox.maximumWorld;
  20753. BABYLON.Tools.CheckExtends(minBox, min, max);
  20754. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20755. }
  20756. }
  20757. return {
  20758. min: min,
  20759. max: max
  20760. };
  20761. };
  20762. /** @hidden */
  20763. AbstractMesh.prototype._updateBoundingInfo = function () {
  20764. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20765. this._boundingInfo.update(this.worldMatrixFromCache);
  20766. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20767. return this;
  20768. };
  20769. /** @hidden */
  20770. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20771. if (!this.subMeshes) {
  20772. return this;
  20773. }
  20774. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20775. var subMesh = this.subMeshes[subIndex];
  20776. if (!subMesh.IsGlobal) {
  20777. subMesh.updateBoundingInfo(matrix);
  20778. }
  20779. }
  20780. return this;
  20781. };
  20782. /** @hidden */
  20783. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20784. // Bounding info
  20785. this._updateBoundingInfo();
  20786. };
  20787. /**
  20788. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20789. * A mesh is in the frustum if its bounding box intersects the frustum
  20790. * @param frustumPlanes defines the frustum to test
  20791. * @returns true if the mesh is in the frustum planes
  20792. */
  20793. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20794. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20795. };
  20796. /**
  20797. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20798. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20799. * @param frustumPlanes defines the frustum to test
  20800. * @returns true if the mesh is completely in the frustum planes
  20801. */
  20802. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20803. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20804. };
  20805. /**
  20806. * True if the mesh intersects another mesh or a SolidParticle object
  20807. * @param mesh defines a target mesh or SolidParticle to test
  20808. * @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)
  20809. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20810. * @returns true if there is an intersection
  20811. */
  20812. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20813. if (precise === void 0) { precise = false; }
  20814. if (!this._boundingInfo || !mesh._boundingInfo) {
  20815. return false;
  20816. }
  20817. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20818. return true;
  20819. }
  20820. if (includeDescendants) {
  20821. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20822. var child = _a[_i];
  20823. if (child.intersectsMesh(mesh, precise, true)) {
  20824. return true;
  20825. }
  20826. }
  20827. }
  20828. return false;
  20829. };
  20830. /**
  20831. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20832. * @param point defines the point to test
  20833. * @returns true if there is an intersection
  20834. */
  20835. AbstractMesh.prototype.intersectsPoint = function (point) {
  20836. if (!this._boundingInfo) {
  20837. return false;
  20838. }
  20839. return this._boundingInfo.intersectsPoint(point);
  20840. };
  20841. /**
  20842. * Gets the current physics impostor
  20843. * @see http://doc.babylonjs.com/features/physics_engine
  20844. * @returns a physics impostor or null
  20845. */
  20846. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20847. return this.physicsImpostor;
  20848. };
  20849. /**
  20850. * Gets the position of the current mesh in camera space
  20851. * @param camera defines the camera to use
  20852. * @returns a position
  20853. */
  20854. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20855. if (camera === void 0) { camera = null; }
  20856. if (!camera) {
  20857. camera = this.getScene().activeCamera;
  20858. }
  20859. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20860. };
  20861. /**
  20862. * Returns the distance from the mesh to the active camera
  20863. * @param camera defines the camera to use
  20864. * @returns the distance
  20865. */
  20866. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20867. if (camera === void 0) { camera = null; }
  20868. if (!camera) {
  20869. camera = this.getScene().activeCamera;
  20870. }
  20871. return this.absolutePosition.subtract(camera.position).length();
  20872. };
  20873. /**
  20874. * Apply a physic impulse to the mesh
  20875. * @param force defines the force to apply
  20876. * @param contactPoint defines where to apply the force
  20877. * @returns the current mesh
  20878. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20879. */
  20880. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20881. if (!this.physicsImpostor) {
  20882. return this;
  20883. }
  20884. this.physicsImpostor.applyImpulse(force, contactPoint);
  20885. return this;
  20886. };
  20887. /**
  20888. * Creates a physic joint between two meshes
  20889. * @param otherMesh defines the other mesh to use
  20890. * @param pivot1 defines the pivot to use on this mesh
  20891. * @param pivot2 defines the pivot to use on the other mesh
  20892. * @param options defines additional options (can be plugin dependent)
  20893. * @returns the current mesh
  20894. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20895. */
  20896. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20897. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20898. return this;
  20899. }
  20900. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20901. mainPivot: pivot1,
  20902. connectedPivot: pivot2,
  20903. nativeParams: options
  20904. });
  20905. return this;
  20906. };
  20907. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20908. // Collisions
  20909. /**
  20910. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20911. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20912. */
  20913. get: function () {
  20914. return this._checkCollisions;
  20915. },
  20916. set: function (collisionEnabled) {
  20917. this._checkCollisions = collisionEnabled;
  20918. if (this.getScene().workerCollisions) {
  20919. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20920. }
  20921. },
  20922. enumerable: true,
  20923. configurable: true
  20924. });
  20925. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20926. /**
  20927. * Gets Collider object used to compute collisions (not physics)
  20928. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20929. */
  20930. get: function () {
  20931. return this._collider;
  20932. },
  20933. enumerable: true,
  20934. configurable: true
  20935. });
  20936. /**
  20937. * Move the mesh using collision engine
  20938. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20939. * @param displacement defines the requested displacement vector
  20940. * @returns the current mesh
  20941. */
  20942. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20943. var globalPosition = this.getAbsolutePosition();
  20944. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20945. if (!this._collider) {
  20946. this._collider = new BABYLON.Collider();
  20947. }
  20948. this._collider._radius = this.ellipsoid;
  20949. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20950. return this;
  20951. };
  20952. // Submeshes octree
  20953. /**
  20954. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20955. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20956. * @param maxCapacity defines the maximum size of each block (64 by default)
  20957. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20958. * @returns the new octree
  20959. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20960. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20961. */
  20962. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20963. if (maxCapacity === void 0) { maxCapacity = 64; }
  20964. if (maxDepth === void 0) { maxDepth = 2; }
  20965. if (!this._submeshesOctree) {
  20966. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20967. }
  20968. this.computeWorldMatrix(true);
  20969. var boundingInfo = this.getBoundingInfo();
  20970. // Update octree
  20971. var bbox = boundingInfo.boundingBox;
  20972. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20973. return this._submeshesOctree;
  20974. };
  20975. // Collisions
  20976. /** @hidden */
  20977. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20978. this._generatePointsArray();
  20979. if (!this._positions) {
  20980. return this;
  20981. }
  20982. // Transformation
  20983. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20984. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20985. subMesh._lastColliderWorldVertices = [];
  20986. subMesh._trianglePlanes = [];
  20987. var start = subMesh.verticesStart;
  20988. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20989. for (var i = start; i < end; i++) {
  20990. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20991. }
  20992. }
  20993. // Collide
  20994. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20995. if (collider.collisionFound) {
  20996. collider.collidedMesh = this;
  20997. }
  20998. return this;
  20999. };
  21000. /** @hidden */
  21001. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21002. var subMeshes;
  21003. var len;
  21004. // Octrees
  21005. if (this._submeshesOctree && this.useOctreeForCollisions) {
  21006. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  21007. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  21008. len = intersections.length;
  21009. subMeshes = intersections.data;
  21010. }
  21011. else {
  21012. subMeshes = this.subMeshes;
  21013. len = subMeshes.length;
  21014. }
  21015. for (var index = 0; index < len; index++) {
  21016. var subMesh = subMeshes[index];
  21017. // Bounding test
  21018. if (len > 1 && !subMesh._checkCollision(collider))
  21019. continue;
  21020. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21021. }
  21022. return this;
  21023. };
  21024. /** @hidden */
  21025. AbstractMesh.prototype._checkCollision = function (collider) {
  21026. // Bounding box test
  21027. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21028. return this;
  21029. // Transformation matrix
  21030. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  21031. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  21032. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  21033. return this;
  21034. };
  21035. // Picking
  21036. /** @hidden */
  21037. AbstractMesh.prototype._generatePointsArray = function () {
  21038. return false;
  21039. };
  21040. /**
  21041. * Checks if the passed Ray intersects with the mesh
  21042. * @param ray defines the ray to use
  21043. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21044. * @returns the picking info
  21045. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21046. */
  21047. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21048. var pickingInfo = new BABYLON.PickingInfo();
  21049. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21050. return pickingInfo;
  21051. }
  21052. if (!this._generatePointsArray()) {
  21053. return pickingInfo;
  21054. }
  21055. var intersectInfo = null;
  21056. // Octrees
  21057. var subMeshes;
  21058. var len;
  21059. if (this._submeshesOctree && this.useOctreeForPicking) {
  21060. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  21061. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  21062. len = intersections.length;
  21063. subMeshes = intersections.data;
  21064. }
  21065. else {
  21066. subMeshes = this.subMeshes;
  21067. len = subMeshes.length;
  21068. }
  21069. for (var index = 0; index < len; index++) {
  21070. var subMesh = subMeshes[index];
  21071. // Bounding test
  21072. if (len > 1 && !subMesh.canIntersects(ray))
  21073. continue;
  21074. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21075. if (currentIntersectInfo) {
  21076. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21077. intersectInfo = currentIntersectInfo;
  21078. intersectInfo.subMeshId = index;
  21079. if (fastCheck) {
  21080. break;
  21081. }
  21082. }
  21083. }
  21084. }
  21085. if (intersectInfo) {
  21086. // Get picked point
  21087. var world = this.getWorldMatrix();
  21088. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21089. var direction = ray.direction.clone();
  21090. direction = direction.scale(intersectInfo.distance);
  21091. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21092. var pickedPoint = worldOrigin.add(worldDirection);
  21093. // Return result
  21094. pickingInfo.hit = true;
  21095. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21096. pickingInfo.pickedPoint = pickedPoint;
  21097. pickingInfo.pickedMesh = this;
  21098. pickingInfo.bu = intersectInfo.bu || 0;
  21099. pickingInfo.bv = intersectInfo.bv || 0;
  21100. pickingInfo.faceId = intersectInfo.faceId;
  21101. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21102. return pickingInfo;
  21103. }
  21104. return pickingInfo;
  21105. };
  21106. /**
  21107. * Clones the current mesh
  21108. * @param name defines the mesh name
  21109. * @param newParent defines the new mesh parent
  21110. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21111. * @returns the new mesh
  21112. */
  21113. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21114. return null;
  21115. };
  21116. /**
  21117. * Disposes all the submeshes of the current meshnp
  21118. * @returns the current mesh
  21119. */
  21120. AbstractMesh.prototype.releaseSubMeshes = function () {
  21121. if (this.subMeshes) {
  21122. while (this.subMeshes.length) {
  21123. this.subMeshes[0].dispose();
  21124. }
  21125. }
  21126. else {
  21127. this.subMeshes = new Array();
  21128. }
  21129. return this;
  21130. };
  21131. /**
  21132. * Releases resources associated with this abstract mesh.
  21133. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21134. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21135. */
  21136. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21137. var _this = this;
  21138. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21139. var index;
  21140. // Smart Array Retainers.
  21141. this.getScene().freeActiveMeshes();
  21142. this.getScene().freeRenderingGroups();
  21143. // Action manager
  21144. if (this.actionManager !== undefined && this.actionManager !== null) {
  21145. this.actionManager.dispose();
  21146. this.actionManager = null;
  21147. }
  21148. // Skeleton
  21149. this._skeleton = null;
  21150. // Physics
  21151. if (this.physicsImpostor) {
  21152. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  21153. }
  21154. // Intersections in progress
  21155. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21156. var other = this._intersectionsInProgress[index];
  21157. var pos = other._intersectionsInProgress.indexOf(this);
  21158. other._intersectionsInProgress.splice(pos, 1);
  21159. }
  21160. this._intersectionsInProgress = [];
  21161. // Lights
  21162. var lights = this.getScene().lights;
  21163. lights.forEach(function (light) {
  21164. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21165. if (meshIndex !== -1) {
  21166. light.includedOnlyMeshes.splice(meshIndex, 1);
  21167. }
  21168. meshIndex = light.excludedMeshes.indexOf(_this);
  21169. if (meshIndex !== -1) {
  21170. light.excludedMeshes.splice(meshIndex, 1);
  21171. }
  21172. // Shadow generators
  21173. var generator = light.getShadowGenerator();
  21174. if (generator) {
  21175. var shadowMap = generator.getShadowMap();
  21176. if (shadowMap && shadowMap.renderList) {
  21177. meshIndex = shadowMap.renderList.indexOf(_this);
  21178. if (meshIndex !== -1) {
  21179. shadowMap.renderList.splice(meshIndex, 1);
  21180. }
  21181. }
  21182. }
  21183. });
  21184. // Edges
  21185. if (this._edgesRenderer) {
  21186. this._edgesRenderer.dispose();
  21187. this._edgesRenderer = null;
  21188. }
  21189. // SubMeshes
  21190. if (this.getClassName() !== "InstancedMesh") {
  21191. this.releaseSubMeshes();
  21192. }
  21193. // Octree
  21194. var sceneOctree = this.getScene().selectionOctree;
  21195. if (sceneOctree !== undefined && sceneOctree !== null) {
  21196. var index = sceneOctree.dynamicContent.indexOf(this);
  21197. if (index !== -1) {
  21198. sceneOctree.dynamicContent.splice(index, 1);
  21199. }
  21200. }
  21201. // Query
  21202. var engine = this.getScene().getEngine();
  21203. if (this._occlusionQuery) {
  21204. this._isOcclusionQueryInProgress = false;
  21205. engine.deleteQuery(this._occlusionQuery);
  21206. this._occlusionQuery = null;
  21207. }
  21208. // Engine
  21209. engine.wipeCaches();
  21210. // Remove from scene
  21211. this.getScene().removeMesh(this);
  21212. if (disposeMaterialAndTextures) {
  21213. if (this.material) {
  21214. this.material.dispose(false, true);
  21215. }
  21216. }
  21217. if (!doNotRecurse) {
  21218. // Particles
  21219. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21220. if (this.getScene().particleSystems[index].emitter === this) {
  21221. this.getScene().particleSystems[index].dispose();
  21222. index--;
  21223. }
  21224. }
  21225. }
  21226. // facet data
  21227. if (this._facetDataEnabled) {
  21228. this.disableFacetData();
  21229. }
  21230. this.onAfterWorldMatrixUpdateObservable.clear();
  21231. this.onCollideObservable.clear();
  21232. this.onCollisionPositionChangeObservable.clear();
  21233. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21234. };
  21235. /**
  21236. * Adds the passed mesh as a child to the current mesh
  21237. * @param mesh defines the child mesh
  21238. * @returns the current mesh
  21239. */
  21240. AbstractMesh.prototype.addChild = function (mesh) {
  21241. mesh.setParent(this);
  21242. return this;
  21243. };
  21244. /**
  21245. * Removes the passed mesh from the current mesh children list
  21246. * @param mesh defines the child mesh
  21247. * @returns the current mesh
  21248. */
  21249. AbstractMesh.prototype.removeChild = function (mesh) {
  21250. mesh.setParent(null);
  21251. return this;
  21252. };
  21253. // Facet data
  21254. /** @hidden */
  21255. AbstractMesh.prototype._initFacetData = function () {
  21256. if (!this._facetNormals) {
  21257. this._facetNormals = new Array();
  21258. }
  21259. if (!this._facetPositions) {
  21260. this._facetPositions = new Array();
  21261. }
  21262. if (!this._facetPartitioning) {
  21263. this._facetPartitioning = new Array();
  21264. }
  21265. this._facetNb = (this.getIndices().length / 3) | 0;
  21266. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21267. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21268. for (var f = 0; f < this._facetNb; f++) {
  21269. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21270. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21271. }
  21272. this._facetDataEnabled = true;
  21273. return this;
  21274. };
  21275. /**
  21276. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21277. * This method can be called within the render loop.
  21278. * 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
  21279. * @returns the current mesh
  21280. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21281. */
  21282. AbstractMesh.prototype.updateFacetData = function () {
  21283. if (!this._facetDataEnabled) {
  21284. this._initFacetData();
  21285. }
  21286. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21287. var indices = this.getIndices();
  21288. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21289. var bInfo = this.getBoundingInfo();
  21290. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21291. // init arrays, matrix and sort function on first call
  21292. this._facetDepthSortEnabled = true;
  21293. if (indices instanceof Uint16Array) {
  21294. this._depthSortedIndices = new Uint16Array(indices);
  21295. }
  21296. else if (indices instanceof Uint32Array) {
  21297. this._depthSortedIndices = new Uint32Array(indices);
  21298. }
  21299. else {
  21300. var needs32bits = false;
  21301. for (var i = 0; i < indices.length; i++) {
  21302. if (indices[i] > 65535) {
  21303. needs32bits = true;
  21304. break;
  21305. }
  21306. }
  21307. if (needs32bits) {
  21308. this._depthSortedIndices = new Uint32Array(indices);
  21309. }
  21310. else {
  21311. this._depthSortedIndices = new Uint16Array(indices);
  21312. }
  21313. }
  21314. this._facetDepthSortFunction = function (f1, f2) {
  21315. return (f2.sqDistance - f1.sqDistance);
  21316. };
  21317. if (!this._facetDepthSortFrom) {
  21318. var camera = this.getScene().activeCamera;
  21319. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21320. }
  21321. this._depthSortedFacets = [];
  21322. for (var f = 0; f < this._facetNb; f++) {
  21323. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21324. this._depthSortedFacets.push(depthSortedFacet);
  21325. }
  21326. this._invertedMatrix = BABYLON.Matrix.Identity();
  21327. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21328. }
  21329. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21330. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21331. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21332. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21333. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21334. this._subDiv.max = this._partitioningSubdivisions;
  21335. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21336. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21337. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21338. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21339. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21340. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21341. // set the parameters for ComputeNormals()
  21342. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21343. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21344. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21345. this._facetParameters.bInfo = bInfo;
  21346. this._facetParameters.bbSize = this._bbSize;
  21347. this._facetParameters.subDiv = this._subDiv;
  21348. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21349. this._facetParameters.depthSort = this._facetDepthSort;
  21350. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21351. this.computeWorldMatrix(true);
  21352. this._worldMatrix.invertToRef(this._invertedMatrix);
  21353. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21354. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21355. }
  21356. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21357. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21358. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21359. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21360. var l = (this._depthSortedIndices.length / 3) | 0;
  21361. for (var f = 0; f < l; f++) {
  21362. var sind = this._depthSortedFacets[f].ind;
  21363. this._depthSortedIndices[f * 3] = indices[sind];
  21364. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21365. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21366. }
  21367. this.updateIndices(this._depthSortedIndices);
  21368. }
  21369. return this;
  21370. };
  21371. /**
  21372. * Returns the facetLocalNormals array.
  21373. * The normals are expressed in the mesh local spac
  21374. * @returns an array of Vector3
  21375. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21376. */
  21377. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21378. if (!this._facetNormals) {
  21379. this.updateFacetData();
  21380. }
  21381. return this._facetNormals;
  21382. };
  21383. /**
  21384. * Returns the facetLocalPositions array.
  21385. * The facet positions are expressed in the mesh local space
  21386. * @returns an array of Vector3
  21387. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21388. */
  21389. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21390. if (!this._facetPositions) {
  21391. this.updateFacetData();
  21392. }
  21393. return this._facetPositions;
  21394. };
  21395. /**
  21396. * Returns the facetLocalPartioning array
  21397. * @returns an array of array of numbers
  21398. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21399. */
  21400. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21401. if (!this._facetPartitioning) {
  21402. this.updateFacetData();
  21403. }
  21404. return this._facetPartitioning;
  21405. };
  21406. /**
  21407. * Returns the i-th facet position in the world system.
  21408. * This method allocates a new Vector3 per call
  21409. * @param i defines the facet index
  21410. * @returns a new Vector3
  21411. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21412. */
  21413. AbstractMesh.prototype.getFacetPosition = function (i) {
  21414. var pos = BABYLON.Vector3.Zero();
  21415. this.getFacetPositionToRef(i, pos);
  21416. return pos;
  21417. };
  21418. /**
  21419. * Sets the reference Vector3 with the i-th facet position in the world system
  21420. * @param i defines the facet index
  21421. * @param ref defines the target vector
  21422. * @returns the current mesh
  21423. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21424. */
  21425. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21426. var localPos = (this.getFacetLocalPositions())[i];
  21427. var world = this.getWorldMatrix();
  21428. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21429. return this;
  21430. };
  21431. /**
  21432. * Returns the i-th facet normal in the world system.
  21433. * This method allocates a new Vector3 per call
  21434. * @param i defines the facet index
  21435. * @returns a new Vector3
  21436. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21437. */
  21438. AbstractMesh.prototype.getFacetNormal = function (i) {
  21439. var norm = BABYLON.Vector3.Zero();
  21440. this.getFacetNormalToRef(i, norm);
  21441. return norm;
  21442. };
  21443. /**
  21444. * Sets the reference Vector3 with the i-th facet normal in the world system
  21445. * @param i defines the facet index
  21446. * @param ref defines the target vector
  21447. * @returns the current mesh
  21448. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21449. */
  21450. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21451. var localNorm = (this.getFacetLocalNormals())[i];
  21452. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21453. return this;
  21454. };
  21455. /**
  21456. * 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)
  21457. * @param x defines x coordinate
  21458. * @param y defines y coordinate
  21459. * @param z defines z coordinate
  21460. * @returns the array of facet indexes
  21461. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21462. */
  21463. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21464. var bInfo = this.getBoundingInfo();
  21465. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21466. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21467. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21468. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21469. return null;
  21470. }
  21471. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21472. };
  21473. /**
  21474. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21475. * @param projected sets as the (x,y,z) world projection on the facet
  21476. * @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
  21477. * @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
  21478. * @param x defines x coordinate
  21479. * @param y defines y coordinate
  21480. * @param z defines z coordinate
  21481. * @returns the face index if found (or null instead)
  21482. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21483. */
  21484. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21485. if (checkFace === void 0) { checkFace = false; }
  21486. if (facing === void 0) { facing = true; }
  21487. var world = this.getWorldMatrix();
  21488. var invMat = BABYLON.Tmp.Matrix[5];
  21489. world.invertToRef(invMat);
  21490. var invVect = BABYLON.Tmp.Vector3[8];
  21491. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21492. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21493. if (projected) {
  21494. // tranform the local computed projected vector to world coordinates
  21495. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21496. }
  21497. return closest;
  21498. };
  21499. /**
  21500. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21501. * @param projected sets as the (x,y,z) local projection on the facet
  21502. * @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
  21503. * @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
  21504. * @param x defines x coordinate
  21505. * @param y defines y coordinate
  21506. * @param z defines z coordinate
  21507. * @returns the face index if found (or null instead)
  21508. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21509. */
  21510. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21511. if (checkFace === void 0) { checkFace = false; }
  21512. if (facing === void 0) { facing = true; }
  21513. var closest = null;
  21514. var tmpx = 0.0;
  21515. var tmpy = 0.0;
  21516. var tmpz = 0.0;
  21517. var d = 0.0; // tmp dot facet normal * facet position
  21518. var t0 = 0.0;
  21519. var projx = 0.0;
  21520. var projy = 0.0;
  21521. var projz = 0.0;
  21522. // Get all the facets in the same partitioning block than (x, y, z)
  21523. var facetPositions = this.getFacetLocalPositions();
  21524. var facetNormals = this.getFacetLocalNormals();
  21525. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21526. if (!facetsInBlock) {
  21527. return null;
  21528. }
  21529. // Get the closest facet to (x, y, z)
  21530. var shortest = Number.MAX_VALUE; // init distance vars
  21531. var tmpDistance = shortest;
  21532. var fib; // current facet in the block
  21533. var norm; // current facet normal
  21534. var p0; // current facet barycenter position
  21535. // loop on all the facets in the current partitioning block
  21536. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21537. fib = facetsInBlock[idx];
  21538. norm = facetNormals[fib];
  21539. p0 = facetPositions[fib];
  21540. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21541. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21542. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21543. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21544. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21545. projx = x + norm.x * t0;
  21546. projy = y + norm.y * t0;
  21547. projz = z + norm.z * t0;
  21548. tmpx = projx - x;
  21549. tmpy = projy - y;
  21550. tmpz = projz - z;
  21551. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21552. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21553. shortest = tmpDistance;
  21554. closest = fib;
  21555. if (projected) {
  21556. projected.x = projx;
  21557. projected.y = projy;
  21558. projected.z = projz;
  21559. }
  21560. }
  21561. }
  21562. }
  21563. return closest;
  21564. };
  21565. /**
  21566. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21567. * @returns the parameters
  21568. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21569. */
  21570. AbstractMesh.prototype.getFacetDataParameters = function () {
  21571. return this._facetParameters;
  21572. };
  21573. /**
  21574. * Disables the feature FacetData and frees the related memory
  21575. * @returns the current mesh
  21576. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21577. */
  21578. AbstractMesh.prototype.disableFacetData = function () {
  21579. if (this._facetDataEnabled) {
  21580. this._facetDataEnabled = false;
  21581. this._facetPositions = new Array();
  21582. this._facetNormals = new Array();
  21583. this._facetPartitioning = new Array();
  21584. this._facetParameters = null;
  21585. this._depthSortedIndices = new Uint32Array(0);
  21586. }
  21587. return this;
  21588. };
  21589. /**
  21590. * Updates the AbstractMesh indices array
  21591. * @param indices defines the data source
  21592. * @returns the current mesh
  21593. */
  21594. AbstractMesh.prototype.updateIndices = function (indices) {
  21595. return this;
  21596. };
  21597. /**
  21598. * Creates new normals data for the mesh
  21599. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21600. * @returns the current mesh
  21601. */
  21602. AbstractMesh.prototype.createNormals = function (updatable) {
  21603. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21604. var indices = this.getIndices();
  21605. var normals;
  21606. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21607. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21608. }
  21609. else {
  21610. normals = [];
  21611. }
  21612. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21613. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21614. return this;
  21615. };
  21616. /**
  21617. * Align the mesh with a normal
  21618. * @param normal defines the normal to use
  21619. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21620. * @returns the current mesh
  21621. */
  21622. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21623. if (!upDirection) {
  21624. upDirection = BABYLON.Axis.Y;
  21625. }
  21626. var axisX = BABYLON.Tmp.Vector3[0];
  21627. var axisZ = BABYLON.Tmp.Vector3[1];
  21628. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21629. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21630. if (this.rotationQuaternion) {
  21631. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21632. }
  21633. else {
  21634. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21635. }
  21636. return this;
  21637. };
  21638. /** @hidden */
  21639. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21640. var engine = this.getEngine();
  21641. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21642. this._isOccluded = false;
  21643. return;
  21644. }
  21645. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21646. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21647. if (isOcclusionQueryAvailable) {
  21648. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21649. this._isOcclusionQueryInProgress = false;
  21650. this._occlusionInternalRetryCounter = 0;
  21651. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21652. }
  21653. else {
  21654. this._occlusionInternalRetryCounter++;
  21655. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21656. this._isOcclusionQueryInProgress = false;
  21657. this._occlusionInternalRetryCounter = 0;
  21658. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21659. // if strict continue the last state of the object.
  21660. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21661. }
  21662. else {
  21663. return;
  21664. }
  21665. }
  21666. }
  21667. var scene = this.getScene();
  21668. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21669. if (!this._occlusionQuery) {
  21670. this._occlusionQuery = engine.createQuery();
  21671. }
  21672. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21673. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21674. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21675. this._isOcclusionQueryInProgress = true;
  21676. };
  21677. /** No occlusion */
  21678. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21679. /** Occlusion set to optimisitic */
  21680. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21681. /** Occlusion set to strict */
  21682. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21683. /** Use an accurante occlusion algorithm */
  21684. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21685. /** Use a conservative occlusion algorithm */
  21686. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21687. return AbstractMesh;
  21688. }(BABYLON.TransformNode));
  21689. BABYLON.AbstractMesh = AbstractMesh;
  21690. })(BABYLON || (BABYLON = {}));
  21691. //# sourceMappingURL=babylon.abstractMesh.js.map
  21692. var BABYLON;
  21693. (function (BABYLON) {
  21694. /**
  21695. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21696. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21697. * 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.
  21698. */
  21699. var Light = /** @class */ (function (_super) {
  21700. __extends(Light, _super);
  21701. /**
  21702. * Creates a Light object in the scene.
  21703. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21704. * @param name The firendly name of the light
  21705. * @param scene The scene the light belongs too
  21706. */
  21707. function Light(name, scene) {
  21708. var _this = _super.call(this, name, scene) || this;
  21709. /**
  21710. * Diffuse gives the basic color to an object.
  21711. */
  21712. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21713. /**
  21714. * Specular produces a highlight color on an object.
  21715. * Note: This is note affecting PBR materials.
  21716. */
  21717. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21718. /**
  21719. * Strength of the light.
  21720. * Note: By default it is define in the framework own unit.
  21721. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21722. */
  21723. _this.intensity = 1.0;
  21724. /**
  21725. * Defines how far from the source the light is impacting in scene units.
  21726. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21727. */
  21728. _this.range = Number.MAX_VALUE;
  21729. /**
  21730. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21731. * of light.
  21732. */
  21733. _this._photometricScale = 1.0;
  21734. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21735. _this._radius = 0.00001;
  21736. /**
  21737. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21738. * exceeding the number allowed of the materials.
  21739. */
  21740. _this.renderPriority = 0;
  21741. _this._shadowEnabled = true;
  21742. _this._excludeWithLayerMask = 0;
  21743. _this._includeOnlyWithLayerMask = 0;
  21744. _this._lightmapMode = 0;
  21745. /**
  21746. * @hidden Internal use only.
  21747. */
  21748. _this._excludedMeshesIds = new Array();
  21749. /**
  21750. * @hidden Internal use only.
  21751. */
  21752. _this._includedOnlyMeshesIds = new Array();
  21753. _this.getScene().addLight(_this);
  21754. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21755. _this._buildUniformLayout();
  21756. _this.includedOnlyMeshes = new Array();
  21757. _this.excludedMeshes = new Array();
  21758. _this._resyncMeshes();
  21759. return _this;
  21760. }
  21761. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21762. /**
  21763. * If every light affecting the material is in this lightmapMode,
  21764. * material.lightmapTexture adds or multiplies
  21765. * (depends on material.useLightmapAsShadowmap)
  21766. * after every other light calculations.
  21767. */
  21768. get: function () {
  21769. return Light._LIGHTMAP_DEFAULT;
  21770. },
  21771. enumerable: true,
  21772. configurable: true
  21773. });
  21774. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21775. /**
  21776. * material.lightmapTexture as only diffuse lighting from this light
  21777. * adds only specular lighting from this light
  21778. * adds dynamic shadows
  21779. */
  21780. get: function () {
  21781. return Light._LIGHTMAP_SPECULAR;
  21782. },
  21783. enumerable: true,
  21784. configurable: true
  21785. });
  21786. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21787. /**
  21788. * material.lightmapTexture as only lighting
  21789. * no light calculation from this light
  21790. * only adds dynamic shadows from this light
  21791. */
  21792. get: function () {
  21793. return Light._LIGHTMAP_SHADOWSONLY;
  21794. },
  21795. enumerable: true,
  21796. configurable: true
  21797. });
  21798. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21799. /**
  21800. * Each light type uses the default quantity according to its type:
  21801. * point/spot lights use luminous intensity
  21802. * directional lights use illuminance
  21803. */
  21804. get: function () {
  21805. return Light._INTENSITYMODE_AUTOMATIC;
  21806. },
  21807. enumerable: true,
  21808. configurable: true
  21809. });
  21810. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21811. /**
  21812. * lumen (lm)
  21813. */
  21814. get: function () {
  21815. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21816. },
  21817. enumerable: true,
  21818. configurable: true
  21819. });
  21820. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21821. /**
  21822. * candela (lm/sr)
  21823. */
  21824. get: function () {
  21825. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21826. },
  21827. enumerable: true,
  21828. configurable: true
  21829. });
  21830. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21831. /**
  21832. * lux (lm/m^2)
  21833. */
  21834. get: function () {
  21835. return Light._INTENSITYMODE_ILLUMINANCE;
  21836. },
  21837. enumerable: true,
  21838. configurable: true
  21839. });
  21840. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21841. /**
  21842. * nit (cd/m^2)
  21843. */
  21844. get: function () {
  21845. return Light._INTENSITYMODE_LUMINANCE;
  21846. },
  21847. enumerable: true,
  21848. configurable: true
  21849. });
  21850. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21851. /**
  21852. * Light type const id of the point light.
  21853. */
  21854. get: function () {
  21855. return Light._LIGHTTYPEID_POINTLIGHT;
  21856. },
  21857. enumerable: true,
  21858. configurable: true
  21859. });
  21860. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21861. /**
  21862. * Light type const id of the directional light.
  21863. */
  21864. get: function () {
  21865. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21866. },
  21867. enumerable: true,
  21868. configurable: true
  21869. });
  21870. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21871. /**
  21872. * Light type const id of the spot light.
  21873. */
  21874. get: function () {
  21875. return Light._LIGHTTYPEID_SPOTLIGHT;
  21876. },
  21877. enumerable: true,
  21878. configurable: true
  21879. });
  21880. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21881. /**
  21882. * Light type const id of the hemispheric light.
  21883. */
  21884. get: function () {
  21885. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21886. },
  21887. enumerable: true,
  21888. configurable: true
  21889. });
  21890. Object.defineProperty(Light.prototype, "intensityMode", {
  21891. /**
  21892. * Gets the photometric scale used to interpret the intensity.
  21893. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21894. */
  21895. get: function () {
  21896. return this._intensityMode;
  21897. },
  21898. /**
  21899. * Sets the photometric scale used to interpret the intensity.
  21900. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21901. */
  21902. set: function (value) {
  21903. this._intensityMode = value;
  21904. this._computePhotometricScale();
  21905. },
  21906. enumerable: true,
  21907. configurable: true
  21908. });
  21909. ;
  21910. ;
  21911. Object.defineProperty(Light.prototype, "radius", {
  21912. /**
  21913. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21914. */
  21915. get: function () {
  21916. return this._radius;
  21917. },
  21918. /**
  21919. * sets the light radius used by PBR Materials to simulate soft area lights.
  21920. */
  21921. set: function (value) {
  21922. this._radius = value;
  21923. this._computePhotometricScale();
  21924. },
  21925. enumerable: true,
  21926. configurable: true
  21927. });
  21928. ;
  21929. ;
  21930. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21931. /**
  21932. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21933. * the current shadow generator.
  21934. */
  21935. get: function () {
  21936. return this._shadowEnabled;
  21937. },
  21938. /**
  21939. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21940. * the current shadow generator.
  21941. */
  21942. set: function (value) {
  21943. if (this._shadowEnabled === value) {
  21944. return;
  21945. }
  21946. this._shadowEnabled = value;
  21947. this._markMeshesAsLightDirty();
  21948. },
  21949. enumerable: true,
  21950. configurable: true
  21951. });
  21952. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21953. /**
  21954. * Gets the only meshes impacted by this light.
  21955. */
  21956. get: function () {
  21957. return this._includedOnlyMeshes;
  21958. },
  21959. /**
  21960. * Sets the only meshes impacted by this light.
  21961. */
  21962. set: function (value) {
  21963. this._includedOnlyMeshes = value;
  21964. this._hookArrayForIncludedOnly(value);
  21965. },
  21966. enumerable: true,
  21967. configurable: true
  21968. });
  21969. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21970. /**
  21971. * Gets the meshes not impacted by this light.
  21972. */
  21973. get: function () {
  21974. return this._excludedMeshes;
  21975. },
  21976. /**
  21977. * Sets the meshes not impacted by this light.
  21978. */
  21979. set: function (value) {
  21980. this._excludedMeshes = value;
  21981. this._hookArrayForExcluded(value);
  21982. },
  21983. enumerable: true,
  21984. configurable: true
  21985. });
  21986. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21987. /**
  21988. * Gets the layer id use to find what meshes are not impacted by the light.
  21989. * Inactive if 0
  21990. */
  21991. get: function () {
  21992. return this._excludeWithLayerMask;
  21993. },
  21994. /**
  21995. * Sets the layer id use to find what meshes are not impacted by the light.
  21996. * Inactive if 0
  21997. */
  21998. set: function (value) {
  21999. this._excludeWithLayerMask = value;
  22000. this._resyncMeshes();
  22001. },
  22002. enumerable: true,
  22003. configurable: true
  22004. });
  22005. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22006. /**
  22007. * Gets the layer id use to find what meshes are impacted by the light.
  22008. * Inactive if 0
  22009. */
  22010. get: function () {
  22011. return this._includeOnlyWithLayerMask;
  22012. },
  22013. /**
  22014. * Sets the layer id use to find what meshes are impacted by the light.
  22015. * Inactive if 0
  22016. */
  22017. set: function (value) {
  22018. this._includeOnlyWithLayerMask = value;
  22019. this._resyncMeshes();
  22020. },
  22021. enumerable: true,
  22022. configurable: true
  22023. });
  22024. Object.defineProperty(Light.prototype, "lightmapMode", {
  22025. /**
  22026. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22027. */
  22028. get: function () {
  22029. return this._lightmapMode;
  22030. },
  22031. /**
  22032. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22033. */
  22034. set: function (value) {
  22035. if (this._lightmapMode === value) {
  22036. return;
  22037. }
  22038. this._lightmapMode = value;
  22039. this._markMeshesAsLightDirty();
  22040. },
  22041. enumerable: true,
  22042. configurable: true
  22043. });
  22044. /**
  22045. * Returns the string "Light".
  22046. * @returns the class name
  22047. */
  22048. Light.prototype.getClassName = function () {
  22049. return "Light";
  22050. };
  22051. /**
  22052. * Converts the light information to a readable string for debug purpose.
  22053. * @param fullDetails Supports for multiple levels of logging within scene loading
  22054. * @returns the human readable light info
  22055. */
  22056. Light.prototype.toString = function (fullDetails) {
  22057. var ret = "Name: " + this.name;
  22058. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22059. if (this.animations) {
  22060. for (var i = 0; i < this.animations.length; i++) {
  22061. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22062. }
  22063. }
  22064. if (fullDetails) {
  22065. }
  22066. return ret;
  22067. };
  22068. /**
  22069. * Set the enabled state of this node.
  22070. * @param value - the new enabled state
  22071. */
  22072. Light.prototype.setEnabled = function (value) {
  22073. _super.prototype.setEnabled.call(this, value);
  22074. this._resyncMeshes();
  22075. };
  22076. /**
  22077. * Returns the Light associated shadow generator if any.
  22078. * @return the associated shadow generator.
  22079. */
  22080. Light.prototype.getShadowGenerator = function () {
  22081. return this._shadowGenerator;
  22082. };
  22083. /**
  22084. * Returns a Vector3, the absolute light position in the World.
  22085. * @returns the world space position of the light
  22086. */
  22087. Light.prototype.getAbsolutePosition = function () {
  22088. return BABYLON.Vector3.Zero();
  22089. };
  22090. /**
  22091. * Specifies if the light will affect the passed mesh.
  22092. * @param mesh The mesh to test against the light
  22093. * @return true the mesh is affected otherwise, false.
  22094. */
  22095. Light.prototype.canAffectMesh = function (mesh) {
  22096. if (!mesh) {
  22097. return true;
  22098. }
  22099. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22100. return false;
  22101. }
  22102. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22103. return false;
  22104. }
  22105. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22106. return false;
  22107. }
  22108. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22109. return false;
  22110. }
  22111. return true;
  22112. };
  22113. /**
  22114. * Computes and Returns the light World matrix.
  22115. * @returns the world matrix
  22116. */
  22117. Light.prototype.getWorldMatrix = function () {
  22118. this._currentRenderId = this.getScene().getRenderId();
  22119. this._childRenderId = this._currentRenderId;
  22120. var worldMatrix = this._getWorldMatrix();
  22121. if (this.parent && this.parent.getWorldMatrix) {
  22122. if (!this._parentedWorldMatrix) {
  22123. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  22124. }
  22125. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  22126. this._markSyncedWithParent();
  22127. return this._parentedWorldMatrix;
  22128. }
  22129. return worldMatrix;
  22130. };
  22131. /**
  22132. * Sort function to order lights for rendering.
  22133. * @param a First Light object to compare to second.
  22134. * @param b Second Light object to compare first.
  22135. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22136. */
  22137. Light.CompareLightsPriority = function (a, b) {
  22138. //shadow-casting lights have priority over non-shadow-casting lights
  22139. //the renderPrioirty is a secondary sort criterion
  22140. if (a.shadowEnabled !== b.shadowEnabled) {
  22141. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22142. }
  22143. return b.renderPriority - a.renderPriority;
  22144. };
  22145. /**
  22146. * Releases resources associated with this node.
  22147. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22148. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22149. */
  22150. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22151. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22152. if (this._shadowGenerator) {
  22153. this._shadowGenerator.dispose();
  22154. this._shadowGenerator = null;
  22155. }
  22156. // Animations
  22157. this.getScene().stopAnimation(this);
  22158. // Remove from meshes
  22159. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22160. var mesh = _a[_i];
  22161. mesh._removeLightSource(this);
  22162. }
  22163. this._uniformBuffer.dispose();
  22164. // Remove from scene
  22165. this.getScene().removeLight(this);
  22166. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22167. };
  22168. /**
  22169. * Returns the light type ID (integer).
  22170. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22171. */
  22172. Light.prototype.getTypeID = function () {
  22173. return 0;
  22174. };
  22175. /**
  22176. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22177. * @returns the scaled intensity in intensity mode unit
  22178. */
  22179. Light.prototype.getScaledIntensity = function () {
  22180. return this._photometricScale * this.intensity;
  22181. };
  22182. /**
  22183. * Returns a new Light object, named "name", from the current one.
  22184. * @param name The name of the cloned light
  22185. * @returns the new created light
  22186. */
  22187. Light.prototype.clone = function (name) {
  22188. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22189. if (!constructor) {
  22190. return null;
  22191. }
  22192. return BABYLON.SerializationHelper.Clone(constructor, this);
  22193. };
  22194. /**
  22195. * Serializes the current light into a Serialization object.
  22196. * @returns the serialized object.
  22197. */
  22198. Light.prototype.serialize = function () {
  22199. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22200. // Type
  22201. serializationObject.type = this.getTypeID();
  22202. // Parent
  22203. if (this.parent) {
  22204. serializationObject.parentId = this.parent.id;
  22205. }
  22206. // Inclusion / exclusions
  22207. if (this.excludedMeshes.length > 0) {
  22208. serializationObject.excludedMeshesIds = [];
  22209. this.excludedMeshes.forEach(function (mesh) {
  22210. serializationObject.excludedMeshesIds.push(mesh.id);
  22211. });
  22212. }
  22213. if (this.includedOnlyMeshes.length > 0) {
  22214. serializationObject.includedOnlyMeshesIds = [];
  22215. this.includedOnlyMeshes.forEach(function (mesh) {
  22216. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22217. });
  22218. }
  22219. // Animations
  22220. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22221. serializationObject.ranges = this.serializeAnimationRanges();
  22222. return serializationObject;
  22223. };
  22224. /**
  22225. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22226. * This new light is named "name" and added to the passed scene.
  22227. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22228. * @param name The friendly name of the light
  22229. * @param scene The scene the new light will belong to
  22230. * @returns the constructor function
  22231. */
  22232. Light.GetConstructorFromName = function (type, name, scene) {
  22233. switch (type) {
  22234. case 0:
  22235. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22236. case 1:
  22237. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22238. case 2:
  22239. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22240. case 3:
  22241. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22242. }
  22243. return null;
  22244. };
  22245. /**
  22246. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22247. * @param parsedLight The JSON representation of the light
  22248. * @param scene The scene to create the parsed light in
  22249. * @returns the created light after parsing
  22250. */
  22251. Light.Parse = function (parsedLight, scene) {
  22252. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22253. if (!constructor) {
  22254. return null;
  22255. }
  22256. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22257. // Inclusion / exclusions
  22258. if (parsedLight.excludedMeshesIds) {
  22259. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22260. }
  22261. if (parsedLight.includedOnlyMeshesIds) {
  22262. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22263. }
  22264. // Parent
  22265. if (parsedLight.parentId) {
  22266. light._waitingParentId = parsedLight.parentId;
  22267. }
  22268. // Animations
  22269. if (parsedLight.animations) {
  22270. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22271. var parsedAnimation = parsedLight.animations[animationIndex];
  22272. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22273. }
  22274. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22275. }
  22276. if (parsedLight.autoAnimate) {
  22277. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22278. }
  22279. return light;
  22280. };
  22281. Light.prototype._hookArrayForExcluded = function (array) {
  22282. var _this = this;
  22283. var oldPush = array.push;
  22284. array.push = function () {
  22285. var items = [];
  22286. for (var _i = 0; _i < arguments.length; _i++) {
  22287. items[_i] = arguments[_i];
  22288. }
  22289. var result = oldPush.apply(array, items);
  22290. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22291. var item = items_1[_a];
  22292. item._resyncLighSource(_this);
  22293. }
  22294. return result;
  22295. };
  22296. var oldSplice = array.splice;
  22297. array.splice = function (index, deleteCount) {
  22298. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22299. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22300. var item = deleted_1[_i];
  22301. item._resyncLighSource(_this);
  22302. }
  22303. return deleted;
  22304. };
  22305. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22306. var item = array_1[_i];
  22307. item._resyncLighSource(this);
  22308. }
  22309. };
  22310. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22311. var _this = this;
  22312. var oldPush = array.push;
  22313. array.push = function () {
  22314. var items = [];
  22315. for (var _i = 0; _i < arguments.length; _i++) {
  22316. items[_i] = arguments[_i];
  22317. }
  22318. var result = oldPush.apply(array, items);
  22319. _this._resyncMeshes();
  22320. return result;
  22321. };
  22322. var oldSplice = array.splice;
  22323. array.splice = function (index, deleteCount) {
  22324. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22325. _this._resyncMeshes();
  22326. return deleted;
  22327. };
  22328. this._resyncMeshes();
  22329. };
  22330. Light.prototype._resyncMeshes = function () {
  22331. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22332. var mesh = _a[_i];
  22333. mesh._resyncLighSource(this);
  22334. }
  22335. };
  22336. /**
  22337. * Forces the meshes to update their light related information in their rendering used effects
  22338. * @hidden Internal Use Only
  22339. */
  22340. Light.prototype._markMeshesAsLightDirty = function () {
  22341. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22342. var mesh = _a[_i];
  22343. if (mesh._lightSources.indexOf(this) !== -1) {
  22344. mesh._markSubMeshesAsLightDirty();
  22345. }
  22346. }
  22347. };
  22348. /**
  22349. * Recomputes the cached photometric scale if needed.
  22350. */
  22351. Light.prototype._computePhotometricScale = function () {
  22352. this._photometricScale = this._getPhotometricScale();
  22353. this.getScene().resetCachedMaterial();
  22354. };
  22355. /**
  22356. * Returns the Photometric Scale according to the light type and intensity mode.
  22357. */
  22358. Light.prototype._getPhotometricScale = function () {
  22359. var photometricScale = 0.0;
  22360. var lightTypeID = this.getTypeID();
  22361. //get photometric mode
  22362. var photometricMode = this.intensityMode;
  22363. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22364. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22365. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22366. }
  22367. else {
  22368. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22369. }
  22370. }
  22371. //compute photometric scale
  22372. switch (lightTypeID) {
  22373. case Light.LIGHTTYPEID_POINTLIGHT:
  22374. case Light.LIGHTTYPEID_SPOTLIGHT:
  22375. switch (photometricMode) {
  22376. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22377. photometricScale = 1.0 / (4.0 * Math.PI);
  22378. break;
  22379. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22380. photometricScale = 1.0;
  22381. break;
  22382. case Light.INTENSITYMODE_LUMINANCE:
  22383. photometricScale = this.radius * this.radius;
  22384. break;
  22385. }
  22386. break;
  22387. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22388. switch (photometricMode) {
  22389. case Light.INTENSITYMODE_ILLUMINANCE:
  22390. photometricScale = 1.0;
  22391. break;
  22392. case Light.INTENSITYMODE_LUMINANCE:
  22393. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22394. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22395. var apexAngleRadians = this.radius;
  22396. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22397. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22398. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22399. photometricScale = solidAngle;
  22400. break;
  22401. }
  22402. break;
  22403. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22404. // No fall off in hemisperic light.
  22405. photometricScale = 1.0;
  22406. break;
  22407. }
  22408. return photometricScale;
  22409. };
  22410. /**
  22411. * Reorder the light in the scene according to their defined priority.
  22412. * @hidden Internal Use Only
  22413. */
  22414. Light.prototype._reorderLightsInScene = function () {
  22415. var scene = this.getScene();
  22416. if (this._renderPriority != 0) {
  22417. scene.requireLightSorting = true;
  22418. }
  22419. this.getScene().sortLightsByPriority();
  22420. };
  22421. //lightmapMode Consts
  22422. Light._LIGHTMAP_DEFAULT = 0;
  22423. Light._LIGHTMAP_SPECULAR = 1;
  22424. Light._LIGHTMAP_SHADOWSONLY = 2;
  22425. // Intensity Mode Consts
  22426. Light._INTENSITYMODE_AUTOMATIC = 0;
  22427. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22428. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22429. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22430. Light._INTENSITYMODE_LUMINANCE = 4;
  22431. // Light types ids const.
  22432. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22433. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22434. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22435. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22436. __decorate([
  22437. BABYLON.serializeAsColor3()
  22438. ], Light.prototype, "diffuse", void 0);
  22439. __decorate([
  22440. BABYLON.serializeAsColor3()
  22441. ], Light.prototype, "specular", void 0);
  22442. __decorate([
  22443. BABYLON.serialize()
  22444. ], Light.prototype, "intensity", void 0);
  22445. __decorate([
  22446. BABYLON.serialize()
  22447. ], Light.prototype, "range", void 0);
  22448. __decorate([
  22449. BABYLON.serialize()
  22450. ], Light.prototype, "intensityMode", null);
  22451. __decorate([
  22452. BABYLON.serialize()
  22453. ], Light.prototype, "radius", null);
  22454. __decorate([
  22455. BABYLON.serialize()
  22456. ], Light.prototype, "_renderPriority", void 0);
  22457. __decorate([
  22458. BABYLON.expandToProperty("_reorderLightsInScene")
  22459. ], Light.prototype, "renderPriority", void 0);
  22460. __decorate([
  22461. BABYLON.serialize("shadowEnabled")
  22462. ], Light.prototype, "_shadowEnabled", void 0);
  22463. __decorate([
  22464. BABYLON.serialize("excludeWithLayerMask")
  22465. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22466. __decorate([
  22467. BABYLON.serialize("includeOnlyWithLayerMask")
  22468. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22469. __decorate([
  22470. BABYLON.serialize("lightmapMode")
  22471. ], Light.prototype, "_lightmapMode", void 0);
  22472. return Light;
  22473. }(BABYLON.Node));
  22474. BABYLON.Light = Light;
  22475. })(BABYLON || (BABYLON = {}));
  22476. //# sourceMappingURL=babylon.light.js.map
  22477. var BABYLON;
  22478. (function (BABYLON) {
  22479. var Camera = /** @class */ (function (_super) {
  22480. __extends(Camera, _super);
  22481. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22482. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22483. var _this = _super.call(this, name, scene) || this;
  22484. /**
  22485. * The vector the camera should consider as up.
  22486. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22487. */
  22488. _this.upVector = BABYLON.Vector3.Up();
  22489. _this.orthoLeft = null;
  22490. _this.orthoRight = null;
  22491. _this.orthoBottom = null;
  22492. _this.orthoTop = null;
  22493. /**
  22494. * FOV is set in Radians. (default is 0.8)
  22495. */
  22496. _this.fov = 0.8;
  22497. _this.minZ = 1;
  22498. _this.maxZ = 10000.0;
  22499. _this.inertia = 0.9;
  22500. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22501. _this.isIntermediate = false;
  22502. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22503. /**
  22504. * Restricts the camera to viewing objects with the same layerMask.
  22505. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22506. */
  22507. _this.layerMask = 0x0FFFFFFF;
  22508. /**
  22509. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22510. */
  22511. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22512. // Camera rig members
  22513. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22514. _this._rigCameras = new Array();
  22515. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22516. _this._skipRendering = false;
  22517. _this.customRenderTargets = new Array();
  22518. // Observables
  22519. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22520. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22521. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22522. _this.onRestoreStateObservable = new BABYLON.Observable();
  22523. // Cache
  22524. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22525. _this._projectionMatrix = new BABYLON.Matrix();
  22526. _this._doNotComputeProjectionMatrix = false;
  22527. _this._worldMatrix = BABYLON.Matrix.Identity();
  22528. _this._postProcesses = new Array();
  22529. _this._transformMatrix = BABYLON.Matrix.Zero();
  22530. _this._activeMeshes = new BABYLON.SmartArray(256);
  22531. _this._globalPosition = BABYLON.Vector3.Zero();
  22532. _this._refreshFrustumPlanes = true;
  22533. _this.getScene().addCamera(_this);
  22534. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22535. _this.getScene().activeCamera = _this;
  22536. }
  22537. _this.position = position;
  22538. return _this;
  22539. }
  22540. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22541. get: function () {
  22542. return Camera._PERSPECTIVE_CAMERA;
  22543. },
  22544. enumerable: true,
  22545. configurable: true
  22546. });
  22547. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22548. get: function () {
  22549. return Camera._ORTHOGRAPHIC_CAMERA;
  22550. },
  22551. enumerable: true,
  22552. configurable: true
  22553. });
  22554. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22555. /**
  22556. * This is the default FOV mode for perspective cameras.
  22557. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22558. *
  22559. */
  22560. get: function () {
  22561. return Camera._FOVMODE_VERTICAL_FIXED;
  22562. },
  22563. enumerable: true,
  22564. configurable: true
  22565. });
  22566. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22567. /**
  22568. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22569. *
  22570. */
  22571. get: function () {
  22572. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22573. },
  22574. enumerable: true,
  22575. configurable: true
  22576. });
  22577. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22578. get: function () {
  22579. return Camera._RIG_MODE_NONE;
  22580. },
  22581. enumerable: true,
  22582. configurable: true
  22583. });
  22584. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22585. get: function () {
  22586. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22587. },
  22588. enumerable: true,
  22589. configurable: true
  22590. });
  22591. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22592. get: function () {
  22593. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22594. },
  22595. enumerable: true,
  22596. configurable: true
  22597. });
  22598. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22599. get: function () {
  22600. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22601. },
  22602. enumerable: true,
  22603. configurable: true
  22604. });
  22605. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22606. get: function () {
  22607. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22608. },
  22609. enumerable: true,
  22610. configurable: true
  22611. });
  22612. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22613. get: function () {
  22614. return Camera._RIG_MODE_VR;
  22615. },
  22616. enumerable: true,
  22617. configurable: true
  22618. });
  22619. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22620. get: function () {
  22621. return Camera._RIG_MODE_WEBVR;
  22622. },
  22623. enumerable: true,
  22624. configurable: true
  22625. });
  22626. /**
  22627. * Store current camera state (fov, position, etc..)
  22628. */
  22629. Camera.prototype.storeState = function () {
  22630. this._stateStored = true;
  22631. this._storedFov = this.fov;
  22632. return this;
  22633. };
  22634. /**
  22635. * Restores the camera state values if it has been stored. You must call storeState() first
  22636. */
  22637. Camera.prototype._restoreStateValues = function () {
  22638. if (!this._stateStored) {
  22639. return false;
  22640. }
  22641. this.fov = this._storedFov;
  22642. return true;
  22643. };
  22644. /**
  22645. * Restored camera state. You must call storeState() first
  22646. */
  22647. Camera.prototype.restoreState = function () {
  22648. if (this._restoreStateValues()) {
  22649. this.onRestoreStateObservable.notifyObservers(this);
  22650. return true;
  22651. }
  22652. return false;
  22653. };
  22654. Camera.prototype.getClassName = function () {
  22655. return "Camera";
  22656. };
  22657. /**
  22658. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22659. */
  22660. Camera.prototype.toString = function (fullDetails) {
  22661. var ret = "Name: " + this.name;
  22662. ret += ", type: " + this.getClassName();
  22663. if (this.animations) {
  22664. for (var i = 0; i < this.animations.length; i++) {
  22665. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22666. }
  22667. }
  22668. if (fullDetails) {
  22669. }
  22670. return ret;
  22671. };
  22672. Object.defineProperty(Camera.prototype, "globalPosition", {
  22673. get: function () {
  22674. return this._globalPosition;
  22675. },
  22676. enumerable: true,
  22677. configurable: true
  22678. });
  22679. Camera.prototype.getActiveMeshes = function () {
  22680. return this._activeMeshes;
  22681. };
  22682. Camera.prototype.isActiveMesh = function (mesh) {
  22683. return (this._activeMeshes.indexOf(mesh) !== -1);
  22684. };
  22685. /**
  22686. * Is this camera ready to be used/rendered
  22687. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22688. * @return true if the camera is ready
  22689. */
  22690. Camera.prototype.isReady = function (completeCheck) {
  22691. if (completeCheck === void 0) { completeCheck = false; }
  22692. if (completeCheck) {
  22693. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22694. var pp = _a[_i];
  22695. if (pp && !pp.isReady()) {
  22696. return false;
  22697. }
  22698. }
  22699. }
  22700. return _super.prototype.isReady.call(this, completeCheck);
  22701. };
  22702. //Cache
  22703. Camera.prototype._initCache = function () {
  22704. _super.prototype._initCache.call(this);
  22705. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22706. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22707. this._cache.mode = undefined;
  22708. this._cache.minZ = undefined;
  22709. this._cache.maxZ = undefined;
  22710. this._cache.fov = undefined;
  22711. this._cache.fovMode = undefined;
  22712. this._cache.aspectRatio = undefined;
  22713. this._cache.orthoLeft = undefined;
  22714. this._cache.orthoRight = undefined;
  22715. this._cache.orthoBottom = undefined;
  22716. this._cache.orthoTop = undefined;
  22717. this._cache.renderWidth = undefined;
  22718. this._cache.renderHeight = undefined;
  22719. };
  22720. Camera.prototype._updateCache = function (ignoreParentClass) {
  22721. if (!ignoreParentClass) {
  22722. _super.prototype._updateCache.call(this);
  22723. }
  22724. this._cache.position.copyFrom(this.position);
  22725. this._cache.upVector.copyFrom(this.upVector);
  22726. };
  22727. // Synchronized
  22728. Camera.prototype._isSynchronized = function () {
  22729. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22730. };
  22731. Camera.prototype._isSynchronizedViewMatrix = function () {
  22732. if (!_super.prototype._isSynchronized.call(this))
  22733. return false;
  22734. return this._cache.position.equals(this.position)
  22735. && this._cache.upVector.equals(this.upVector)
  22736. && this.isSynchronizedWithParent();
  22737. };
  22738. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22739. var check = this._cache.mode === this.mode
  22740. && this._cache.minZ === this.minZ
  22741. && this._cache.maxZ === this.maxZ;
  22742. if (!check) {
  22743. return false;
  22744. }
  22745. var engine = this.getEngine();
  22746. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22747. check = this._cache.fov === this.fov
  22748. && this._cache.fovMode === this.fovMode
  22749. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22750. }
  22751. else {
  22752. check = this._cache.orthoLeft === this.orthoLeft
  22753. && this._cache.orthoRight === this.orthoRight
  22754. && this._cache.orthoBottom === this.orthoBottom
  22755. && this._cache.orthoTop === this.orthoTop
  22756. && this._cache.renderWidth === engine.getRenderWidth()
  22757. && this._cache.renderHeight === engine.getRenderHeight();
  22758. }
  22759. return check;
  22760. };
  22761. // Controls
  22762. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22763. };
  22764. Camera.prototype.detachControl = function (element) {
  22765. };
  22766. Camera.prototype.update = function () {
  22767. this._checkInputs();
  22768. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22769. this._updateRigCameras();
  22770. }
  22771. };
  22772. Camera.prototype._checkInputs = function () {
  22773. this.onAfterCheckInputsObservable.notifyObservers(this);
  22774. };
  22775. Object.defineProperty(Camera.prototype, "rigCameras", {
  22776. get: function () {
  22777. return this._rigCameras;
  22778. },
  22779. enumerable: true,
  22780. configurable: true
  22781. });
  22782. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22783. get: function () {
  22784. return this._rigPostProcess;
  22785. },
  22786. enumerable: true,
  22787. configurable: true
  22788. });
  22789. /**
  22790. * Internal, gets the first post proces.
  22791. * @returns the first post process to be run on this camera.
  22792. */
  22793. Camera.prototype._getFirstPostProcess = function () {
  22794. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22795. if (this._postProcesses[ppIndex] !== null) {
  22796. return this._postProcesses[ppIndex];
  22797. }
  22798. }
  22799. return null;
  22800. };
  22801. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22802. // invalidate framebuffer
  22803. var firstPostProcess = this._getFirstPostProcess();
  22804. if (firstPostProcess) {
  22805. firstPostProcess.markTextureDirty();
  22806. }
  22807. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22808. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22809. var cam = this._rigCameras[i];
  22810. var rigPostProcess = cam._rigPostProcess;
  22811. // for VR rig, there does not have to be a post process
  22812. if (rigPostProcess) {
  22813. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22814. if (isPass) {
  22815. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22816. cam.isIntermediate = this._postProcesses.length === 0;
  22817. }
  22818. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22819. rigPostProcess.markTextureDirty();
  22820. }
  22821. else {
  22822. cam._postProcesses = this._postProcesses.slice(0);
  22823. }
  22824. }
  22825. };
  22826. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22827. if (insertAt === void 0) { insertAt = null; }
  22828. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22829. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22830. return 0;
  22831. }
  22832. if (insertAt == null || insertAt < 0) {
  22833. this._postProcesses.push(postProcess);
  22834. }
  22835. else if (this._postProcesses[insertAt] === null) {
  22836. this._postProcesses[insertAt] = postProcess;
  22837. }
  22838. else {
  22839. this._postProcesses.splice(insertAt, 0, postProcess);
  22840. }
  22841. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22842. return this._postProcesses.indexOf(postProcess);
  22843. };
  22844. Camera.prototype.detachPostProcess = function (postProcess) {
  22845. var idx = this._postProcesses.indexOf(postProcess);
  22846. if (idx !== -1) {
  22847. this._postProcesses[idx] = null;
  22848. }
  22849. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22850. };
  22851. Camera.prototype.getWorldMatrix = function () {
  22852. if (this._isSynchronizedViewMatrix()) {
  22853. return this._worldMatrix;
  22854. }
  22855. // Getting the the view matrix will also compute the world matrix.
  22856. this.getViewMatrix();
  22857. return this._worldMatrix;
  22858. };
  22859. Camera.prototype._getViewMatrix = function () {
  22860. return BABYLON.Matrix.Identity();
  22861. };
  22862. Camera.prototype.getViewMatrix = function (force) {
  22863. if (!force && this._isSynchronizedViewMatrix()) {
  22864. return this._computedViewMatrix;
  22865. }
  22866. this.updateCache();
  22867. this._computedViewMatrix = this._getViewMatrix();
  22868. this._currentRenderId = this.getScene().getRenderId();
  22869. this._childRenderId = this._currentRenderId;
  22870. this._refreshFrustumPlanes = true;
  22871. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22872. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22873. }
  22874. this.onViewMatrixChangedObservable.notifyObservers(this);
  22875. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22876. return this._computedViewMatrix;
  22877. };
  22878. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22879. this._doNotComputeProjectionMatrix = true;
  22880. if (projection !== undefined) {
  22881. this._projectionMatrix = projection;
  22882. }
  22883. };
  22884. ;
  22885. Camera.prototype.unfreezeProjectionMatrix = function () {
  22886. this._doNotComputeProjectionMatrix = false;
  22887. };
  22888. ;
  22889. Camera.prototype.getProjectionMatrix = function (force) {
  22890. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22891. return this._projectionMatrix;
  22892. }
  22893. // Cache
  22894. this._cache.mode = this.mode;
  22895. this._cache.minZ = this.minZ;
  22896. this._cache.maxZ = this.maxZ;
  22897. // Matrix
  22898. this._refreshFrustumPlanes = true;
  22899. var engine = this.getEngine();
  22900. var scene = this.getScene();
  22901. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22902. this._cache.fov = this.fov;
  22903. this._cache.fovMode = this.fovMode;
  22904. this._cache.aspectRatio = engine.getAspectRatio(this);
  22905. if (this.minZ <= 0) {
  22906. this.minZ = 0.1;
  22907. }
  22908. if (scene.useRightHandedSystem) {
  22909. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22910. }
  22911. else {
  22912. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22913. }
  22914. }
  22915. else {
  22916. var halfWidth = engine.getRenderWidth() / 2.0;
  22917. var halfHeight = engine.getRenderHeight() / 2.0;
  22918. if (scene.useRightHandedSystem) {
  22919. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22920. }
  22921. else {
  22922. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22923. }
  22924. this._cache.orthoLeft = this.orthoLeft;
  22925. this._cache.orthoRight = this.orthoRight;
  22926. this._cache.orthoBottom = this.orthoBottom;
  22927. this._cache.orthoTop = this.orthoTop;
  22928. this._cache.renderWidth = engine.getRenderWidth();
  22929. this._cache.renderHeight = engine.getRenderHeight();
  22930. }
  22931. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22932. return this._projectionMatrix;
  22933. };
  22934. Camera.prototype.getTranformationMatrix = function () {
  22935. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22936. return this._transformMatrix;
  22937. };
  22938. Camera.prototype.updateFrustumPlanes = function () {
  22939. if (!this._refreshFrustumPlanes) {
  22940. return;
  22941. }
  22942. this.getTranformationMatrix();
  22943. if (!this._frustumPlanes) {
  22944. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22945. }
  22946. else {
  22947. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22948. }
  22949. this._refreshFrustumPlanes = false;
  22950. };
  22951. Camera.prototype.isInFrustum = function (target) {
  22952. this.updateFrustumPlanes();
  22953. return target.isInFrustum(this._frustumPlanes);
  22954. };
  22955. Camera.prototype.isCompletelyInFrustum = function (target) {
  22956. this.updateFrustumPlanes();
  22957. return target.isCompletelyInFrustum(this._frustumPlanes);
  22958. };
  22959. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22960. if (length === void 0) { length = 100; }
  22961. if (!transform) {
  22962. transform = this.getWorldMatrix();
  22963. }
  22964. if (!origin) {
  22965. origin = this.position;
  22966. }
  22967. var forward = new BABYLON.Vector3(0, 0, 1);
  22968. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22969. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22970. return new BABYLON.Ray(origin, direction, length);
  22971. };
  22972. /**
  22973. * Releases resources associated with this node.
  22974. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22975. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22976. */
  22977. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22978. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22979. // Observables
  22980. this.onViewMatrixChangedObservable.clear();
  22981. this.onProjectionMatrixChangedObservable.clear();
  22982. this.onAfterCheckInputsObservable.clear();
  22983. this.onRestoreStateObservable.clear();
  22984. // Inputs
  22985. if (this.inputs) {
  22986. this.inputs.clear();
  22987. }
  22988. // Animations
  22989. this.getScene().stopAnimation(this);
  22990. // Remove from scene
  22991. this.getScene().removeCamera(this);
  22992. while (this._rigCameras.length > 0) {
  22993. var camera = this._rigCameras.pop();
  22994. if (camera) {
  22995. camera.dispose();
  22996. }
  22997. }
  22998. // Postprocesses
  22999. if (this._rigPostProcess) {
  23000. this._rigPostProcess.dispose(this);
  23001. this._rigPostProcess = null;
  23002. this._postProcesses = [];
  23003. }
  23004. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23005. this._rigPostProcess = null;
  23006. this._postProcesses = [];
  23007. }
  23008. else {
  23009. var i = this._postProcesses.length;
  23010. while (--i >= 0) {
  23011. var postProcess = this._postProcesses[i];
  23012. if (postProcess) {
  23013. postProcess.dispose(this);
  23014. }
  23015. }
  23016. }
  23017. // Render targets
  23018. var i = this.customRenderTargets.length;
  23019. while (--i >= 0) {
  23020. this.customRenderTargets[i].dispose();
  23021. }
  23022. this.customRenderTargets = [];
  23023. // Active Meshes
  23024. this._activeMeshes.dispose();
  23025. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23026. };
  23027. Object.defineProperty(Camera.prototype, "leftCamera", {
  23028. // ---- Camera rigs section ----
  23029. get: function () {
  23030. if (this._rigCameras.length < 1) {
  23031. return null;
  23032. }
  23033. return this._rigCameras[0];
  23034. },
  23035. enumerable: true,
  23036. configurable: true
  23037. });
  23038. Object.defineProperty(Camera.prototype, "rightCamera", {
  23039. get: function () {
  23040. if (this._rigCameras.length < 2) {
  23041. return null;
  23042. }
  23043. return this._rigCameras[1];
  23044. },
  23045. enumerable: true,
  23046. configurable: true
  23047. });
  23048. Camera.prototype.getLeftTarget = function () {
  23049. if (this._rigCameras.length < 1) {
  23050. return null;
  23051. }
  23052. return this._rigCameras[0].getTarget();
  23053. };
  23054. Camera.prototype.getRightTarget = function () {
  23055. if (this._rigCameras.length < 2) {
  23056. return null;
  23057. }
  23058. return this._rigCameras[1].getTarget();
  23059. };
  23060. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23061. if (this.cameraRigMode === mode) {
  23062. return;
  23063. }
  23064. while (this._rigCameras.length > 0) {
  23065. var camera = this._rigCameras.pop();
  23066. if (camera) {
  23067. camera.dispose();
  23068. }
  23069. }
  23070. this.cameraRigMode = mode;
  23071. this._cameraRigParams = {};
  23072. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23073. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23074. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23075. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23076. // create the rig cameras, unless none
  23077. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23078. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23079. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23080. if (leftCamera && rightCamera) {
  23081. this._rigCameras.push(leftCamera);
  23082. this._rigCameras.push(rightCamera);
  23083. }
  23084. }
  23085. switch (this.cameraRigMode) {
  23086. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23087. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23088. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23089. break;
  23090. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23091. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23092. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23093. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23094. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23095. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23096. break;
  23097. case Camera.RIG_MODE_VR:
  23098. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23099. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23100. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23101. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23102. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23103. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23104. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23105. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23106. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23107. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23108. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23109. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23110. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23111. if (metrics.compensateDistortion) {
  23112. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23113. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23114. }
  23115. break;
  23116. case Camera.RIG_MODE_WEBVR:
  23117. if (rigParams.vrDisplay) {
  23118. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23119. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23120. //Left eye
  23121. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23122. this._rigCameras[0].setCameraRigParameter("left", true);
  23123. //leaving this for future reference
  23124. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23125. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23126. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23127. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23128. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23129. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23130. this._rigCameras[0].parent = this;
  23131. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23132. //Right eye
  23133. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23134. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23135. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23136. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23137. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23138. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23139. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23140. this._rigCameras[1].parent = this;
  23141. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23142. if (Camera.UseAlternateWebVRRendering) {
  23143. this._rigCameras[1]._skipRendering = true;
  23144. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23145. }
  23146. }
  23147. break;
  23148. }
  23149. this._cascadePostProcessesToRigCams();
  23150. this.update();
  23151. };
  23152. Camera.prototype._getVRProjectionMatrix = function () {
  23153. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23154. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23155. return this._projectionMatrix;
  23156. };
  23157. Camera.prototype._updateCameraRotationMatrix = function () {
  23158. //Here for WebVR
  23159. };
  23160. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23161. //Here for WebVR
  23162. };
  23163. /**
  23164. * This function MUST be overwritten by the different WebVR cameras available.
  23165. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23166. */
  23167. Camera.prototype._getWebVRProjectionMatrix = function () {
  23168. return BABYLON.Matrix.Identity();
  23169. };
  23170. /**
  23171. * This function MUST be overwritten by the different WebVR cameras available.
  23172. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23173. */
  23174. Camera.prototype._getWebVRViewMatrix = function () {
  23175. return BABYLON.Matrix.Identity();
  23176. };
  23177. Camera.prototype.setCameraRigParameter = function (name, value) {
  23178. if (!this._cameraRigParams) {
  23179. this._cameraRigParams = {};
  23180. }
  23181. this._cameraRigParams[name] = value;
  23182. //provisionnally:
  23183. if (name === "interaxialDistance") {
  23184. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23185. }
  23186. };
  23187. /**
  23188. * needs to be overridden by children so sub has required properties to be copied
  23189. */
  23190. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23191. return null;
  23192. };
  23193. /**
  23194. * May need to be overridden by children
  23195. */
  23196. Camera.prototype._updateRigCameras = function () {
  23197. for (var i = 0; i < this._rigCameras.length; i++) {
  23198. this._rigCameras[i].minZ = this.minZ;
  23199. this._rigCameras[i].maxZ = this.maxZ;
  23200. this._rigCameras[i].fov = this.fov;
  23201. }
  23202. // only update viewport when ANAGLYPH
  23203. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23204. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23205. }
  23206. };
  23207. Camera.prototype._setupInputs = function () {
  23208. };
  23209. Camera.prototype.serialize = function () {
  23210. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23211. // Type
  23212. serializationObject.type = this.getClassName();
  23213. // Parent
  23214. if (this.parent) {
  23215. serializationObject.parentId = this.parent.id;
  23216. }
  23217. if (this.inputs) {
  23218. this.inputs.serialize(serializationObject);
  23219. }
  23220. // Animations
  23221. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23222. serializationObject.ranges = this.serializeAnimationRanges();
  23223. return serializationObject;
  23224. };
  23225. Camera.prototype.clone = function (name) {
  23226. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23227. };
  23228. Camera.prototype.getDirection = function (localAxis) {
  23229. var result = BABYLON.Vector3.Zero();
  23230. this.getDirectionToRef(localAxis, result);
  23231. return result;
  23232. };
  23233. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23234. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23235. };
  23236. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23237. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23238. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23239. switch (type) {
  23240. case "ArcRotateCamera":
  23241. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23242. case "DeviceOrientationCamera":
  23243. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23244. case "FollowCamera":
  23245. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23246. case "ArcFollowCamera":
  23247. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23248. case "GamepadCamera":
  23249. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23250. case "TouchCamera":
  23251. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23252. case "VirtualJoysticksCamera":
  23253. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23254. case "WebVRFreeCamera":
  23255. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23256. case "WebVRGamepadCamera":
  23257. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23258. case "VRDeviceOrientationFreeCamera":
  23259. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23260. case "VRDeviceOrientationGamepadCamera":
  23261. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23262. case "AnaglyphArcRotateCamera":
  23263. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23264. case "AnaglyphFreeCamera":
  23265. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23266. case "AnaglyphGamepadCamera":
  23267. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23268. case "AnaglyphUniversalCamera":
  23269. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23270. case "StereoscopicArcRotateCamera":
  23271. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23272. case "StereoscopicFreeCamera":
  23273. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23274. case "StereoscopicGamepadCamera":
  23275. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23276. case "StereoscopicUniversalCamera":
  23277. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23278. case "FreeCamera": // Forcing Universal here
  23279. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23280. default: // Universal Camera is the default value
  23281. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23282. }
  23283. };
  23284. Camera.prototype.computeWorldMatrix = function () {
  23285. return this.getWorldMatrix();
  23286. };
  23287. Camera.Parse = function (parsedCamera, scene) {
  23288. var type = parsedCamera.type;
  23289. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23290. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23291. // Parent
  23292. if (parsedCamera.parentId) {
  23293. camera._waitingParentId = parsedCamera.parentId;
  23294. }
  23295. //If camera has an input manager, let it parse inputs settings
  23296. if (camera.inputs) {
  23297. camera.inputs.parse(parsedCamera);
  23298. camera._setupInputs();
  23299. }
  23300. if (camera.setPosition) { // need to force position
  23301. camera.position.copyFromFloats(0, 0, 0);
  23302. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23303. }
  23304. // Target
  23305. if (parsedCamera.target) {
  23306. if (camera.setTarget) {
  23307. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23308. }
  23309. }
  23310. // Apply 3d rig, when found
  23311. if (parsedCamera.cameraRigMode) {
  23312. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23313. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23314. }
  23315. // Animations
  23316. if (parsedCamera.animations) {
  23317. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23318. var parsedAnimation = parsedCamera.animations[animationIndex];
  23319. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23320. }
  23321. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23322. }
  23323. if (parsedCamera.autoAnimate) {
  23324. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23325. }
  23326. return camera;
  23327. };
  23328. // Statics
  23329. Camera._PERSPECTIVE_CAMERA = 0;
  23330. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23331. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23332. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23333. Camera._RIG_MODE_NONE = 0;
  23334. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23335. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23336. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23337. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23338. Camera._RIG_MODE_VR = 20;
  23339. Camera._RIG_MODE_WEBVR = 21;
  23340. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23341. Camera.UseAlternateWebVRRendering = false;
  23342. __decorate([
  23343. BABYLON.serializeAsVector3()
  23344. ], Camera.prototype, "position", void 0);
  23345. __decorate([
  23346. BABYLON.serializeAsVector3()
  23347. ], Camera.prototype, "upVector", void 0);
  23348. __decorate([
  23349. BABYLON.serialize()
  23350. ], Camera.prototype, "orthoLeft", void 0);
  23351. __decorate([
  23352. BABYLON.serialize()
  23353. ], Camera.prototype, "orthoRight", void 0);
  23354. __decorate([
  23355. BABYLON.serialize()
  23356. ], Camera.prototype, "orthoBottom", void 0);
  23357. __decorate([
  23358. BABYLON.serialize()
  23359. ], Camera.prototype, "orthoTop", void 0);
  23360. __decorate([
  23361. BABYLON.serialize()
  23362. ], Camera.prototype, "fov", void 0);
  23363. __decorate([
  23364. BABYLON.serialize()
  23365. ], Camera.prototype, "minZ", void 0);
  23366. __decorate([
  23367. BABYLON.serialize()
  23368. ], Camera.prototype, "maxZ", void 0);
  23369. __decorate([
  23370. BABYLON.serialize()
  23371. ], Camera.prototype, "inertia", void 0);
  23372. __decorate([
  23373. BABYLON.serialize()
  23374. ], Camera.prototype, "mode", void 0);
  23375. __decorate([
  23376. BABYLON.serialize()
  23377. ], Camera.prototype, "layerMask", void 0);
  23378. __decorate([
  23379. BABYLON.serialize()
  23380. ], Camera.prototype, "fovMode", void 0);
  23381. __decorate([
  23382. BABYLON.serialize()
  23383. ], Camera.prototype, "cameraRigMode", void 0);
  23384. __decorate([
  23385. BABYLON.serialize()
  23386. ], Camera.prototype, "interaxialDistance", void 0);
  23387. __decorate([
  23388. BABYLON.serialize()
  23389. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23390. return Camera;
  23391. }(BABYLON.Node));
  23392. BABYLON.Camera = Camera;
  23393. })(BABYLON || (BABYLON = {}));
  23394. //# sourceMappingURL=babylon.camera.js.map
  23395. var BABYLON;
  23396. (function (BABYLON) {
  23397. var RenderingManager = /** @class */ (function () {
  23398. function RenderingManager(scene) {
  23399. this._renderingGroups = new Array();
  23400. this._autoClearDepthStencil = {};
  23401. this._customOpaqueSortCompareFn = {};
  23402. this._customAlphaTestSortCompareFn = {};
  23403. this._customTransparentSortCompareFn = {};
  23404. this._renderinGroupInfo = null;
  23405. this._scene = scene;
  23406. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23407. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23408. }
  23409. }
  23410. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23411. if (depth === void 0) { depth = true; }
  23412. if (stencil === void 0) { stencil = true; }
  23413. if (this._depthStencilBufferAlreadyCleaned) {
  23414. return;
  23415. }
  23416. this._scene.getEngine().clear(null, false, depth, stencil);
  23417. this._depthStencilBufferAlreadyCleaned = true;
  23418. };
  23419. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23420. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23421. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23422. var info = null;
  23423. if (observable) {
  23424. if (!this._renderinGroupInfo) {
  23425. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23426. }
  23427. info = this._renderinGroupInfo;
  23428. info.scene = this._scene;
  23429. info.camera = this._scene.activeCamera;
  23430. }
  23431. // Dispatch sprites
  23432. if (renderSprites) {
  23433. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23434. var manager = this._scene.spriteManagers[index];
  23435. this.dispatchSprites(manager);
  23436. }
  23437. }
  23438. // Render
  23439. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23440. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23441. var renderingGroup = this._renderingGroups[index];
  23442. if (!renderingGroup && !observable)
  23443. continue;
  23444. var renderingGroupMask = 0;
  23445. // Fire PRECLEAR stage
  23446. if (observable && info) {
  23447. renderingGroupMask = Math.pow(2, index);
  23448. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23449. info.renderingGroupId = index;
  23450. observable.notifyObservers(info, renderingGroupMask);
  23451. }
  23452. // Clear depth/stencil if needed
  23453. if (RenderingManager.AUTOCLEAR) {
  23454. var autoClear = this._autoClearDepthStencil[index];
  23455. if (autoClear && autoClear.autoClear) {
  23456. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23457. }
  23458. }
  23459. if (observable && info) {
  23460. // Fire PREOPAQUE stage
  23461. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23462. observable.notifyObservers(info, renderingGroupMask);
  23463. // Fire PRETRANSPARENT stage
  23464. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23465. observable.notifyObservers(info, renderingGroupMask);
  23466. }
  23467. if (renderingGroup)
  23468. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23469. // Fire POSTTRANSPARENT stage
  23470. if (observable && info) {
  23471. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23472. observable.notifyObservers(info, renderingGroupMask);
  23473. }
  23474. }
  23475. };
  23476. RenderingManager.prototype.reset = function () {
  23477. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23478. var renderingGroup = this._renderingGroups[index];
  23479. if (renderingGroup) {
  23480. renderingGroup.prepare();
  23481. }
  23482. }
  23483. };
  23484. RenderingManager.prototype.dispose = function () {
  23485. this.freeRenderingGroups();
  23486. this._renderingGroups.length = 0;
  23487. };
  23488. /**
  23489. * Clear the info related to rendering groups preventing retention points during dispose.
  23490. */
  23491. RenderingManager.prototype.freeRenderingGroups = function () {
  23492. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23493. var renderingGroup = this._renderingGroups[index];
  23494. if (renderingGroup) {
  23495. renderingGroup.dispose();
  23496. }
  23497. }
  23498. };
  23499. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23500. if (this._renderingGroups[renderingGroupId] === undefined) {
  23501. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23502. }
  23503. };
  23504. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23505. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23506. this._prepareRenderingGroup(renderingGroupId);
  23507. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23508. };
  23509. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23510. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23511. this._prepareRenderingGroup(renderingGroupId);
  23512. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23513. };
  23514. /**
  23515. * @param subMesh The submesh to dispatch
  23516. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23517. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23518. */
  23519. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23520. if (mesh === undefined) {
  23521. mesh = subMesh.getMesh();
  23522. }
  23523. var renderingGroupId = mesh.renderingGroupId || 0;
  23524. this._prepareRenderingGroup(renderingGroupId);
  23525. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23526. };
  23527. /**
  23528. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23529. * This allowed control for front to back rendering or reversly depending of the special needs.
  23530. *
  23531. * @param renderingGroupId The rendering group id corresponding to its index
  23532. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23533. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23534. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23535. */
  23536. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23537. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23538. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23539. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23540. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23541. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23542. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23543. if (this._renderingGroups[renderingGroupId]) {
  23544. var group = this._renderingGroups[renderingGroupId];
  23545. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23546. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23547. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23548. }
  23549. };
  23550. /**
  23551. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23552. *
  23553. * @param renderingGroupId The rendering group id corresponding to its index
  23554. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23555. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23556. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23557. */
  23558. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23559. if (depth === void 0) { depth = true; }
  23560. if (stencil === void 0) { stencil = true; }
  23561. this._autoClearDepthStencil[renderingGroupId] = {
  23562. autoClear: autoClearDepthStencil,
  23563. depth: depth,
  23564. stencil: stencil
  23565. };
  23566. };
  23567. /**
  23568. * The max id used for rendering groups (not included)
  23569. */
  23570. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23571. /**
  23572. * The min id used for rendering groups (included)
  23573. */
  23574. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23575. /**
  23576. * Used to globally prevent autoclearing scenes.
  23577. */
  23578. RenderingManager.AUTOCLEAR = true;
  23579. return RenderingManager;
  23580. }());
  23581. BABYLON.RenderingManager = RenderingManager;
  23582. })(BABYLON || (BABYLON = {}));
  23583. //# sourceMappingURL=babylon.renderingManager.js.map
  23584. var BABYLON;
  23585. (function (BABYLON) {
  23586. var RenderingGroup = /** @class */ (function () {
  23587. /**
  23588. * Creates a new rendering group.
  23589. * @param index The rendering group index
  23590. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23591. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23592. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23593. */
  23594. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23595. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23596. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23597. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23598. this.index = index;
  23599. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23600. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23601. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23602. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23603. this._particleSystems = new BABYLON.SmartArray(256);
  23604. this._spriteManagers = new BABYLON.SmartArray(256);
  23605. this._edgesRenderers = new BABYLON.SmartArray(16);
  23606. this._scene = scene;
  23607. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23608. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23609. this.transparentSortCompareFn = transparentSortCompareFn;
  23610. }
  23611. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23612. /**
  23613. * Set the opaque sort comparison function.
  23614. * If null the sub meshes will be render in the order they were created
  23615. */
  23616. set: function (value) {
  23617. this._opaqueSortCompareFn = value;
  23618. if (value) {
  23619. this._renderOpaque = this.renderOpaqueSorted;
  23620. }
  23621. else {
  23622. this._renderOpaque = RenderingGroup.renderUnsorted;
  23623. }
  23624. },
  23625. enumerable: true,
  23626. configurable: true
  23627. });
  23628. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23629. /**
  23630. * Set the alpha test sort comparison function.
  23631. * If null the sub meshes will be render in the order they were created
  23632. */
  23633. set: function (value) {
  23634. this._alphaTestSortCompareFn = value;
  23635. if (value) {
  23636. this._renderAlphaTest = this.renderAlphaTestSorted;
  23637. }
  23638. else {
  23639. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23640. }
  23641. },
  23642. enumerable: true,
  23643. configurable: true
  23644. });
  23645. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23646. /**
  23647. * Set the transparent sort comparison function.
  23648. * If null the sub meshes will be render in the order they were created
  23649. */
  23650. set: function (value) {
  23651. if (value) {
  23652. this._transparentSortCompareFn = value;
  23653. }
  23654. else {
  23655. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23656. }
  23657. this._renderTransparent = this.renderTransparentSorted;
  23658. },
  23659. enumerable: true,
  23660. configurable: true
  23661. });
  23662. /**
  23663. * Render all the sub meshes contained in the group.
  23664. * @param customRenderFunction Used to override the default render behaviour of the group.
  23665. * @returns true if rendered some submeshes.
  23666. */
  23667. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23668. if (customRenderFunction) {
  23669. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23670. return;
  23671. }
  23672. var engine = this._scene.getEngine();
  23673. // Depth only
  23674. if (this._depthOnlySubMeshes.length !== 0) {
  23675. engine.setColorWrite(false);
  23676. this._renderAlphaTest(this._depthOnlySubMeshes);
  23677. engine.setColorWrite(true);
  23678. }
  23679. // Opaque
  23680. if (this._opaqueSubMeshes.length !== 0) {
  23681. this._renderOpaque(this._opaqueSubMeshes);
  23682. }
  23683. // Alpha test
  23684. if (this._alphaTestSubMeshes.length !== 0) {
  23685. this._renderAlphaTest(this._alphaTestSubMeshes);
  23686. }
  23687. var stencilState = engine.getStencilBuffer();
  23688. engine.setStencilBuffer(false);
  23689. // Sprites
  23690. if (renderSprites) {
  23691. this._renderSprites();
  23692. }
  23693. // Particles
  23694. if (renderParticles) {
  23695. this._renderParticles(activeMeshes);
  23696. }
  23697. if (this.onBeforeTransparentRendering) {
  23698. this.onBeforeTransparentRendering();
  23699. }
  23700. // Transparent
  23701. if (this._transparentSubMeshes.length !== 0) {
  23702. this._renderTransparent(this._transparentSubMeshes);
  23703. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23704. }
  23705. // Set back stencil to false in case it changes before the edge renderer.
  23706. engine.setStencilBuffer(false);
  23707. // Edges
  23708. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23709. this._edgesRenderers.data[edgesRendererIndex].render();
  23710. }
  23711. // Restore Stencil state.
  23712. engine.setStencilBuffer(stencilState);
  23713. };
  23714. /**
  23715. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23716. * @param subMeshes The submeshes to render
  23717. */
  23718. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23719. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23720. };
  23721. /**
  23722. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23723. * @param subMeshes The submeshes to render
  23724. */
  23725. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23726. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23727. };
  23728. /**
  23729. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23730. * @param subMeshes The submeshes to render
  23731. */
  23732. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23733. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23734. };
  23735. /**
  23736. * Renders the submeshes in a specified order.
  23737. * @param subMeshes The submeshes to sort before render
  23738. * @param sortCompareFn The comparison function use to sort
  23739. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23740. * @param transparent Specifies to activate blending if true
  23741. */
  23742. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23743. var subIndex = 0;
  23744. var subMesh;
  23745. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23746. for (; subIndex < subMeshes.length; subIndex++) {
  23747. subMesh = subMeshes.data[subIndex];
  23748. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23749. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23750. }
  23751. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23752. if (sortCompareFn) {
  23753. sortedArray.sort(sortCompareFn);
  23754. }
  23755. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23756. subMesh = sortedArray[subIndex];
  23757. if (transparent) {
  23758. var material = subMesh.getMaterial();
  23759. if (material && material.needDepthPrePass) {
  23760. var engine = material.getScene().getEngine();
  23761. engine.setColorWrite(false);
  23762. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23763. subMesh.render(false);
  23764. engine.setColorWrite(true);
  23765. }
  23766. }
  23767. subMesh.render(transparent);
  23768. }
  23769. };
  23770. /**
  23771. * Renders the submeshes in the order they were dispatched (no sort applied).
  23772. * @param subMeshes The submeshes to render
  23773. */
  23774. RenderingGroup.renderUnsorted = function (subMeshes) {
  23775. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23776. var submesh = subMeshes.data[subIndex];
  23777. submesh.render(false);
  23778. }
  23779. };
  23780. /**
  23781. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23782. * are rendered back to front if in the same alpha index.
  23783. *
  23784. * @param a The first submesh
  23785. * @param b The second submesh
  23786. * @returns The result of the comparison
  23787. */
  23788. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23789. // Alpha index first
  23790. if (a._alphaIndex > b._alphaIndex) {
  23791. return 1;
  23792. }
  23793. if (a._alphaIndex < b._alphaIndex) {
  23794. return -1;
  23795. }
  23796. // Then distance to camera
  23797. return RenderingGroup.backToFrontSortCompare(a, b);
  23798. };
  23799. /**
  23800. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23801. * are rendered back to front.
  23802. *
  23803. * @param a The first submesh
  23804. * @param b The second submesh
  23805. * @returns The result of the comparison
  23806. */
  23807. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23808. // Then distance to camera
  23809. if (a._distanceToCamera < b._distanceToCamera) {
  23810. return 1;
  23811. }
  23812. if (a._distanceToCamera > b._distanceToCamera) {
  23813. return -1;
  23814. }
  23815. return 0;
  23816. };
  23817. /**
  23818. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23819. * are rendered front to back (prevent overdraw).
  23820. *
  23821. * @param a The first submesh
  23822. * @param b The second submesh
  23823. * @returns The result of the comparison
  23824. */
  23825. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23826. // Then distance to camera
  23827. if (a._distanceToCamera < b._distanceToCamera) {
  23828. return -1;
  23829. }
  23830. if (a._distanceToCamera > b._distanceToCamera) {
  23831. return 1;
  23832. }
  23833. return 0;
  23834. };
  23835. /**
  23836. * Resets the different lists of submeshes to prepare a new frame.
  23837. */
  23838. RenderingGroup.prototype.prepare = function () {
  23839. this._opaqueSubMeshes.reset();
  23840. this._transparentSubMeshes.reset();
  23841. this._alphaTestSubMeshes.reset();
  23842. this._depthOnlySubMeshes.reset();
  23843. this._particleSystems.reset();
  23844. this._spriteManagers.reset();
  23845. this._edgesRenderers.reset();
  23846. };
  23847. RenderingGroup.prototype.dispose = function () {
  23848. this._opaqueSubMeshes.dispose();
  23849. this._transparentSubMeshes.dispose();
  23850. this._alphaTestSubMeshes.dispose();
  23851. this._depthOnlySubMeshes.dispose();
  23852. this._particleSystems.dispose();
  23853. this._spriteManagers.dispose();
  23854. this._edgesRenderers.dispose();
  23855. };
  23856. /**
  23857. * Inserts the submesh in its correct queue depending on its material.
  23858. * @param subMesh The submesh to dispatch
  23859. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23860. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23861. */
  23862. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23863. // Get mesh and materials if not provided
  23864. if (mesh === undefined) {
  23865. mesh = subMesh.getMesh();
  23866. }
  23867. if (material === undefined) {
  23868. material = subMesh.getMaterial();
  23869. }
  23870. if (material === null || material === undefined) {
  23871. return;
  23872. }
  23873. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23874. this._transparentSubMeshes.push(subMesh);
  23875. }
  23876. else if (material.needAlphaTesting()) { // Alpha test
  23877. if (material.needDepthPrePass) {
  23878. this._depthOnlySubMeshes.push(subMesh);
  23879. }
  23880. this._alphaTestSubMeshes.push(subMesh);
  23881. }
  23882. else {
  23883. if (material.needDepthPrePass) {
  23884. this._depthOnlySubMeshes.push(subMesh);
  23885. }
  23886. this._opaqueSubMeshes.push(subMesh); // Opaque
  23887. }
  23888. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23889. this._edgesRenderers.push(mesh._edgesRenderer);
  23890. }
  23891. };
  23892. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23893. this._spriteManagers.push(spriteManager);
  23894. };
  23895. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23896. this._particleSystems.push(particleSystem);
  23897. };
  23898. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23899. if (this._particleSystems.length === 0) {
  23900. return;
  23901. }
  23902. // Particles
  23903. var activeCamera = this._scene.activeCamera;
  23904. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23905. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23906. var particleSystem = this._particleSystems.data[particleIndex];
  23907. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23908. continue;
  23909. }
  23910. var emitter = particleSystem.emitter;
  23911. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23912. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23913. }
  23914. }
  23915. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23916. };
  23917. RenderingGroup.prototype._renderSprites = function () {
  23918. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23919. return;
  23920. }
  23921. // Sprites
  23922. var activeCamera = this._scene.activeCamera;
  23923. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23924. for (var id = 0; id < this._spriteManagers.length; id++) {
  23925. var spriteManager = this._spriteManagers.data[id];
  23926. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23927. spriteManager.render();
  23928. }
  23929. }
  23930. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23931. };
  23932. return RenderingGroup;
  23933. }());
  23934. BABYLON.RenderingGroup = RenderingGroup;
  23935. })(BABYLON || (BABYLON = {}));
  23936. //# sourceMappingURL=babylon.renderingGroup.js.map
  23937. var BABYLON;
  23938. (function (BABYLON) {
  23939. /**
  23940. * Groups all the scene component constants in one place to ease maintenance.
  23941. * @hidden
  23942. */
  23943. var SceneComponentConstants = /** @class */ (function () {
  23944. function SceneComponentConstants() {
  23945. }
  23946. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23947. SceneComponentConstants.NAME_LAYER = "Layer";
  23948. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23949. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23950. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23951. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23952. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23953. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23954. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23955. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23956. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23957. return SceneComponentConstants;
  23958. }());
  23959. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23960. /**
  23961. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23962. * @hidden
  23963. */
  23964. var Stage = /** @class */ (function (_super) {
  23965. __extends(Stage, _super);
  23966. /**
  23967. * Hide ctor from the rest of the world.
  23968. * @param items The items to add.
  23969. */
  23970. function Stage(items) {
  23971. return _super.apply(this, items) || this;
  23972. }
  23973. /**
  23974. * Creates a new Stage.
  23975. * @returns A new instance of a Stage
  23976. */
  23977. Stage.Create = function () {
  23978. return Object.create(Stage.prototype);
  23979. };
  23980. /**
  23981. * Registers a step in an ordered way in the targeted stage.
  23982. * @param index Defines the position to register the step in
  23983. * @param component Defines the component attached to the step
  23984. * @param action Defines the action to launch during the step
  23985. */
  23986. Stage.prototype.registerStep = function (index, component, action) {
  23987. var i = 0;
  23988. var maxIndex = Number.MAX_VALUE;
  23989. for (; i < this.length && i < maxIndex; i++) {
  23990. var step = this[i];
  23991. maxIndex = step.index;
  23992. }
  23993. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23994. };
  23995. /**
  23996. * Clears all the steps from the stage.
  23997. */
  23998. Stage.prototype.clear = function () {
  23999. this.length = 0;
  24000. };
  24001. return Stage;
  24002. }(Array));
  24003. BABYLON.Stage = Stage;
  24004. })(BABYLON || (BABYLON = {}));
  24005. //# sourceMappingURL=babylon.sceneComponent.js.map
  24006. var BABYLON;
  24007. (function (BABYLON) {
  24008. /**
  24009. * Base class of the scene acting as a container for the different elements composing a scene.
  24010. * This class is dynamically extended by the different components of the scene increasing
  24011. * flexibility and reducing coupling.
  24012. */
  24013. var AbstractScene = /** @class */ (function () {
  24014. function AbstractScene() {
  24015. /** All of the cameras added to this scene
  24016. * @see http://doc.babylonjs.com/babylon101/cameras
  24017. */
  24018. this.cameras = new Array();
  24019. /**
  24020. * All of the lights added to this scene
  24021. * @see http://doc.babylonjs.com/babylon101/lights
  24022. */
  24023. this.lights = new Array();
  24024. /**
  24025. * All of the (abstract) meshes added to this scene
  24026. */
  24027. this.meshes = new Array();
  24028. /**
  24029. * The list of skeletons added to the scene
  24030. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24031. */
  24032. this.skeletons = new Array();
  24033. /**
  24034. * All of the particle systems added to this scene
  24035. * @see http://doc.babylonjs.com/babylon101/particles
  24036. */
  24037. this.particleSystems = new Array();
  24038. /**
  24039. * Gets a list of Animations associated with the scene
  24040. */
  24041. this.animations = [];
  24042. /**
  24043. * All of the animation groups added to this scene
  24044. * @see http://doc.babylonjs.com/how_to/group
  24045. */
  24046. this.animationGroups = new Array();
  24047. /**
  24048. * All of the multi-materials added to this scene
  24049. * @see http://doc.babylonjs.com/how_to/multi_materials
  24050. */
  24051. this.multiMaterials = new Array();
  24052. /**
  24053. * All of the materials added to this scene
  24054. * @see http://doc.babylonjs.com/babylon101/materials
  24055. */
  24056. this.materials = new Array();
  24057. /**
  24058. * The list of morph target managers added to the scene
  24059. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24060. */
  24061. this.morphTargetManagers = new Array();
  24062. /**
  24063. * The list of geometries used in the scene.
  24064. */
  24065. this.geometries = new Array();
  24066. /**
  24067. * All of the tranform nodes added to this scene
  24068. * @see http://doc.babylonjs.com/how_to/transformnode
  24069. */
  24070. this.transformNodes = new Array();
  24071. /**
  24072. * ActionManagers available on the scene.
  24073. */
  24074. this.actionManagers = new Array();
  24075. /**
  24076. * Sounds to keep.
  24077. */
  24078. this.sounds = new Array();
  24079. /**
  24080. * Textures to keep.
  24081. */
  24082. this.textures = new Array();
  24083. }
  24084. /**
  24085. * Adds a parser in the list of availables ones.
  24086. * @param name Defines the name of the parser
  24087. * @param parser Defines the parser to add
  24088. */
  24089. AbstractScene.AddParser = function (name, parser) {
  24090. this._BabylonFileParsers[name] = parser;
  24091. };
  24092. /**
  24093. * Parser json data and populate both a scene and its associated container object
  24094. * @param jsonData Defines the data to parse
  24095. * @param scene Defines the scene to parse the data for
  24096. * @param container Defines the container attached to the parsing sequence
  24097. * @param rootUrl Defines the root url of the data
  24098. */
  24099. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24100. for (var parserName in this._BabylonFileParsers) {
  24101. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24102. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24103. }
  24104. }
  24105. };
  24106. /**
  24107. * Stores the list of available parsers in the application.
  24108. */
  24109. AbstractScene._BabylonFileParsers = {};
  24110. return AbstractScene;
  24111. }());
  24112. BABYLON.AbstractScene = AbstractScene;
  24113. })(BABYLON || (BABYLON = {}));
  24114. //# sourceMappingURL=babylon.abstractScene.js.map
  24115. var BABYLON;
  24116. (function (BABYLON) {
  24117. /** @hidden */
  24118. var ClickInfo = /** @class */ (function () {
  24119. function ClickInfo() {
  24120. this._singleClick = false;
  24121. this._doubleClick = false;
  24122. this._hasSwiped = false;
  24123. this._ignore = false;
  24124. }
  24125. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24126. get: function () {
  24127. return this._singleClick;
  24128. },
  24129. set: function (b) {
  24130. this._singleClick = b;
  24131. },
  24132. enumerable: true,
  24133. configurable: true
  24134. });
  24135. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24136. get: function () {
  24137. return this._doubleClick;
  24138. },
  24139. set: function (b) {
  24140. this._doubleClick = b;
  24141. },
  24142. enumerable: true,
  24143. configurable: true
  24144. });
  24145. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24146. get: function () {
  24147. return this._hasSwiped;
  24148. },
  24149. set: function (b) {
  24150. this._hasSwiped = b;
  24151. },
  24152. enumerable: true,
  24153. configurable: true
  24154. });
  24155. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24156. get: function () {
  24157. return this._ignore;
  24158. },
  24159. set: function (b) {
  24160. this._ignore = b;
  24161. },
  24162. enumerable: true,
  24163. configurable: true
  24164. });
  24165. return ClickInfo;
  24166. }());
  24167. /**
  24168. * This class is used by the onRenderingGroupObservable
  24169. */
  24170. var RenderingGroupInfo = /** @class */ (function () {
  24171. function RenderingGroupInfo() {
  24172. }
  24173. /**
  24174. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  24175. * This stage will be fired no matter what
  24176. */
  24177. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  24178. /**
  24179. * Called before opaque object are rendered.
  24180. * This stage will be fired only if there's 3D Opaque content to render
  24181. */
  24182. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  24183. /**
  24184. * Called after the opaque objects are rendered and before the transparent ones
  24185. * This stage will be fired only if there's 3D transparent content to render
  24186. */
  24187. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  24188. /**
  24189. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  24190. * This stage will be fired no matter what
  24191. */
  24192. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  24193. return RenderingGroupInfo;
  24194. }());
  24195. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24196. /**
  24197. * Represents a scene to be rendered by the engine.
  24198. * @see http://doc.babylonjs.com/features/scene
  24199. */
  24200. var Scene = /** @class */ (function (_super) {
  24201. __extends(Scene, _super);
  24202. /**
  24203. * Creates a new Scene
  24204. * @param engine defines the engine to use to render this scene
  24205. */
  24206. function Scene(engine) {
  24207. var _this = _super.call(this) || this;
  24208. // Members
  24209. /**
  24210. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24211. */
  24212. _this.autoClear = true;
  24213. /**
  24214. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24215. */
  24216. _this.autoClearDepthAndStencil = true;
  24217. /**
  24218. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24219. */
  24220. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24221. /**
  24222. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24223. */
  24224. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24225. _this._forceWireframe = false;
  24226. _this._forcePointsCloud = false;
  24227. /**
  24228. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  24229. */
  24230. _this.forceShowBoundingBoxes = false;
  24231. /**
  24232. * Gets or sets a boolean indicating if animations are enabled
  24233. */
  24234. _this.animationsEnabled = true;
  24235. _this._animationPropertiesOverride = null;
  24236. /**
  24237. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24238. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24239. */
  24240. _this.useConstantAnimationDeltaTime = false;
  24241. /**
  24242. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24243. * Please note that it requires to run a ray cast through the scene on every frame
  24244. */
  24245. _this.constantlyUpdateMeshUnderPointer = false;
  24246. /**
  24247. * Defines the HTML cursor to use when hovering over interactive elements
  24248. */
  24249. _this.hoverCursor = "pointer";
  24250. /**
  24251. * Defines the HTML default cursor to use (empty by default)
  24252. */
  24253. _this.defaultCursor = "";
  24254. /**
  24255. * This is used to call preventDefault() on pointer down
  24256. * in order to block unwanted artifacts like system double clicks
  24257. */
  24258. _this.preventDefaultOnPointerDown = true;
  24259. // Metadata
  24260. /**
  24261. * Gets or sets user defined metadata
  24262. */
  24263. _this.metadata = null;
  24264. /**
  24265. * Use this array to add regular expressions used to disable offline support for specific urls
  24266. */
  24267. _this.disableOfflineSupportExceptionRules = new Array();
  24268. /**
  24269. * An event triggered when the scene is disposed.
  24270. */
  24271. _this.onDisposeObservable = new BABYLON.Observable();
  24272. _this._onDisposeObserver = null;
  24273. /**
  24274. * An event triggered before rendering the scene (right after animations and physics)
  24275. */
  24276. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24277. _this._onBeforeRenderObserver = null;
  24278. /**
  24279. * An event triggered after rendering the scene
  24280. */
  24281. _this.onAfterRenderObservable = new BABYLON.Observable();
  24282. _this._onAfterRenderObserver = null;
  24283. /**
  24284. * An event triggered before animating the scene
  24285. */
  24286. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24287. /**
  24288. * An event triggered after animations processing
  24289. */
  24290. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24291. /**
  24292. * An event triggered before draw calls are ready to be sent
  24293. */
  24294. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24295. /**
  24296. * An event triggered after draw calls have been sent
  24297. */
  24298. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24299. /**
  24300. * An event triggered when physic simulation is about to be run
  24301. */
  24302. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24303. /**
  24304. * An event triggered when physic simulation has been done
  24305. */
  24306. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24307. /**
  24308. * An event triggered when the scene is ready
  24309. */
  24310. _this.onReadyObservable = new BABYLON.Observable();
  24311. /**
  24312. * An event triggered before rendering a camera
  24313. */
  24314. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24315. _this._onBeforeCameraRenderObserver = null;
  24316. /**
  24317. * An event triggered after rendering a camera
  24318. */
  24319. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24320. _this._onAfterCameraRenderObserver = null;
  24321. /**
  24322. * An event triggered when active meshes evaluation is about to start
  24323. */
  24324. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24325. /**
  24326. * An event triggered when active meshes evaluation is done
  24327. */
  24328. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24329. /**
  24330. * An event triggered when particles rendering is about to start
  24331. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24332. */
  24333. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24334. /**
  24335. * An event triggered when particles rendering is done
  24336. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24337. */
  24338. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24339. /**
  24340. * An event triggered when sprites rendering is about to start
  24341. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24342. */
  24343. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24344. /**
  24345. * An event triggered when sprites rendering is done
  24346. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24347. */
  24348. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24349. /**
  24350. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24351. */
  24352. _this.onDataLoadedObservable = new BABYLON.Observable();
  24353. /**
  24354. * An event triggered when a camera is created
  24355. */
  24356. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24357. /**
  24358. * An event triggered when a camera is removed
  24359. */
  24360. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24361. /**
  24362. * An event triggered when a light is created
  24363. */
  24364. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24365. /**
  24366. * An event triggered when a light is removed
  24367. */
  24368. _this.onLightRemovedObservable = new BABYLON.Observable();
  24369. /**
  24370. * An event triggered when a geometry is created
  24371. */
  24372. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24373. /**
  24374. * An event triggered when a geometry is removed
  24375. */
  24376. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24377. /**
  24378. * An event triggered when a transform node is created
  24379. */
  24380. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24381. /**
  24382. * An event triggered when a transform node is removed
  24383. */
  24384. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24385. /**
  24386. * An event triggered when a mesh is created
  24387. */
  24388. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24389. /**
  24390. * An event triggered when a mesh is removed
  24391. */
  24392. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24393. /**
  24394. * An event triggered when render targets are about to be rendered
  24395. * Can happen multiple times per frame.
  24396. */
  24397. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24398. /**
  24399. * An event triggered when render targets were rendered.
  24400. * Can happen multiple times per frame.
  24401. */
  24402. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24403. /**
  24404. * An event triggered before calculating deterministic simulation step
  24405. */
  24406. _this.onBeforeStepObservable = new BABYLON.Observable();
  24407. /**
  24408. * An event triggered after calculating deterministic simulation step
  24409. */
  24410. _this.onAfterStepObservable = new BABYLON.Observable();
  24411. /**
  24412. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24413. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24414. * 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)
  24415. */
  24416. _this.onRenderingGroupObservable = new BABYLON.Observable();
  24417. // Animations
  24418. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24419. /**
  24420. * 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).
  24421. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24422. */
  24423. _this.onPrePointerObservable = new BABYLON.Observable();
  24424. /**
  24425. * Observable event triggered each time an input event is received from the rendering canvas
  24426. */
  24427. _this.onPointerObservable = new BABYLON.Observable();
  24428. _this._meshPickProceed = false;
  24429. _this._currentPickResult = null;
  24430. _this._previousPickResult = null;
  24431. _this._totalPointersPressed = 0;
  24432. _this._doubleClickOccured = false;
  24433. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24434. _this.cameraToUseForPointers = null;
  24435. _this._pointerX = 0;
  24436. _this._pointerY = 0;
  24437. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24438. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24439. _this._startingPointerTime = 0;
  24440. _this._previousStartingPointerTime = 0;
  24441. _this._pointerCaptures = {};
  24442. // Deterministic lockstep
  24443. _this._timeAccumulator = 0;
  24444. _this._currentStepId = 0;
  24445. _this._currentInternalStep = 0;
  24446. // Keyboard
  24447. /**
  24448. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24449. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24450. */
  24451. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24452. /**
  24453. * Observable event triggered each time an keyboard event is received from the hosting window
  24454. */
  24455. _this.onKeyboardObservable = new BABYLON.Observable();
  24456. // Coordinates system
  24457. _this._useRightHandedSystem = false;
  24458. // Fog
  24459. _this._fogEnabled = true;
  24460. _this._fogMode = Scene.FOGMODE_NONE;
  24461. /**
  24462. * Gets or sets the fog color to use
  24463. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24464. */
  24465. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24466. /**
  24467. * Gets or sets the fog density to use
  24468. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24469. */
  24470. _this.fogDensity = 0.1;
  24471. /**
  24472. * Gets or sets the fog start distance to use
  24473. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24474. */
  24475. _this.fogStart = 0;
  24476. /**
  24477. * Gets or sets the fog end distance to use
  24478. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24479. */
  24480. _this.fogEnd = 1000.0;
  24481. // Lights
  24482. _this._shadowsEnabled = true;
  24483. _this._lightsEnabled = true;
  24484. /** All of the active cameras added to this scene. */
  24485. _this.activeCameras = new Array();
  24486. // Textures
  24487. _this._texturesEnabled = true;
  24488. // Particles
  24489. /**
  24490. * Gets or sets a boolean indicating if particles are enabled on this scene
  24491. */
  24492. _this.particlesEnabled = true;
  24493. // Sprites
  24494. /**
  24495. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24496. */
  24497. _this.spritesEnabled = true;
  24498. /**
  24499. * All of the sprite managers added to this scene
  24500. * @see http://doc.babylonjs.com/babylon101/sprites
  24501. */
  24502. _this.spriteManagers = new Array();
  24503. // Skeletons
  24504. _this._skeletonsEnabled = true;
  24505. // Lens flares
  24506. /**
  24507. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24508. */
  24509. _this.lensFlaresEnabled = true;
  24510. // Collisions
  24511. /**
  24512. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24513. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24514. */
  24515. _this.collisionsEnabled = true;
  24516. /**
  24517. * Defines the gravity applied to this scene (used only for collisions)
  24518. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24519. */
  24520. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24521. // Postprocesses
  24522. /**
  24523. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24524. */
  24525. _this.postProcessesEnabled = true;
  24526. /**
  24527. * The list of postprocesses added to the scene
  24528. */
  24529. _this.postProcesses = new Array();
  24530. // Customs render targets
  24531. /**
  24532. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24533. */
  24534. _this.renderTargetsEnabled = true;
  24535. /**
  24536. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24537. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24538. */
  24539. _this.dumpNextRenderTargets = false;
  24540. /**
  24541. * The list of user defined render targets added to the scene
  24542. */
  24543. _this.customRenderTargets = new Array();
  24544. /**
  24545. * Gets the list of meshes imported to the scene through SceneLoader
  24546. */
  24547. _this.importedMeshesFiles = new Array();
  24548. // Probes
  24549. /**
  24550. * Gets or sets a boolean indicating if probes are enabled on this scene
  24551. */
  24552. _this.probesEnabled = true;
  24553. /**
  24554. * The list of reflection probes added to the scene
  24555. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24556. */
  24557. _this.reflectionProbes = new Array();
  24558. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24559. // Procedural textures
  24560. /**
  24561. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24562. */
  24563. _this.proceduralTexturesEnabled = true;
  24564. /**
  24565. * The list of procedural textures added to the scene
  24566. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24567. */
  24568. _this.proceduralTextures = new Array();
  24569. /**
  24570. * The list of sound tracks added to the scene
  24571. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24572. */
  24573. _this.soundTracks = new Array();
  24574. _this._audioEnabled = true;
  24575. _this._headphone = false;
  24576. // Performance counters
  24577. _this._totalVertices = new BABYLON.PerfCounter();
  24578. /** @hidden */
  24579. _this._activeIndices = new BABYLON.PerfCounter();
  24580. /** @hidden */
  24581. _this._activeParticles = new BABYLON.PerfCounter();
  24582. /** @hidden */
  24583. _this._activeBones = new BABYLON.PerfCounter();
  24584. _this._animationTime = 0;
  24585. /**
  24586. * Gets or sets a general scale for animation speed
  24587. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24588. */
  24589. _this.animationTimeScale = 1;
  24590. _this._renderId = 0;
  24591. _this._executeWhenReadyTimeoutId = -1;
  24592. _this._intermediateRendering = false;
  24593. _this._viewUpdateFlag = -1;
  24594. _this._projectionUpdateFlag = -1;
  24595. _this._alternateViewUpdateFlag = -1;
  24596. _this._alternateProjectionUpdateFlag = -1;
  24597. /** @hidden */
  24598. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24599. _this._activeRequests = new Array();
  24600. _this._pendingData = new Array();
  24601. _this._isDisposed = false;
  24602. /**
  24603. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24604. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24605. */
  24606. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24607. _this._activeMeshes = new BABYLON.SmartArray(256);
  24608. _this._processedMaterials = new BABYLON.SmartArray(256);
  24609. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24610. /** @hidden */
  24611. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24612. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24613. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24614. /** @hidden */
  24615. _this._activeAnimatables = new Array();
  24616. _this._transformMatrix = BABYLON.Matrix.Zero();
  24617. _this._useAlternateCameraConfiguration = false;
  24618. _this._alternateRendering = false;
  24619. /**
  24620. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24621. * This is useful if there are more lights that the maximum simulteanous authorized
  24622. */
  24623. _this.requireLightSorting = false;
  24624. _this._depthRenderer = {};
  24625. /**
  24626. * Backing store of defined scene components.
  24627. */
  24628. _this._components = [];
  24629. /**
  24630. * List of components to register on the next registration step.
  24631. */
  24632. _this._transientComponents = [];
  24633. /**
  24634. * Defines the actions happening during the per mesh ready checks.
  24635. */
  24636. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24637. /**
  24638. * Defines the actions happening during the per camera render target step.
  24639. */
  24640. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24641. /**
  24642. * Defines the actions happening just before the active camera is drawing.
  24643. */
  24644. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24645. /**
  24646. * Defines the actions happening just after the active camera is drawing.
  24647. */
  24648. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24649. _this._activeMeshesFrozen = false;
  24650. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24651. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24652. _this._engine.scenes.push(_this);
  24653. _this._uid = null;
  24654. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24655. if (BABYLON.PostProcessManager) {
  24656. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24657. }
  24658. if (BABYLON.OutlineRenderer) {
  24659. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24660. }
  24661. if (BABYLON.Tools.IsWindowObjectExist()) {
  24662. _this.attachControl();
  24663. }
  24664. //simplification queue
  24665. if (BABYLON.SimplificationQueue) {
  24666. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24667. }
  24668. //collision coordinator initialization. For now legacy per default.
  24669. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24670. // Uniform Buffer
  24671. _this._createUbo();
  24672. // Default Image processing definition
  24673. if (BABYLON.ImageProcessingConfiguration) {
  24674. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24675. }
  24676. return _this;
  24677. }
  24678. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24679. /** The fog is deactivated */
  24680. get: function () {
  24681. return Scene._FOGMODE_NONE;
  24682. },
  24683. enumerable: true,
  24684. configurable: true
  24685. });
  24686. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24687. /** The fog density is following an exponential function */
  24688. get: function () {
  24689. return Scene._FOGMODE_EXP;
  24690. },
  24691. enumerable: true,
  24692. configurable: true
  24693. });
  24694. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24695. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24696. get: function () {
  24697. return Scene._FOGMODE_EXP2;
  24698. },
  24699. enumerable: true,
  24700. configurable: true
  24701. });
  24702. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24703. /** The fog density is following a linear function. */
  24704. get: function () {
  24705. return Scene._FOGMODE_LINEAR;
  24706. },
  24707. enumerable: true,
  24708. configurable: true
  24709. });
  24710. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24711. /**
  24712. * Texture used in all pbr material as the reflection texture.
  24713. * As in the majority of the scene they are the same (exception for multi room and so on),
  24714. * this is easier to reference from here than from all the materials.
  24715. */
  24716. get: function () {
  24717. return this._environmentTexture;
  24718. },
  24719. /**
  24720. * Texture used in all pbr material as the reflection texture.
  24721. * As in the majority of the scene they are the same (exception for multi room and so on),
  24722. * this is easier to set here than in all the materials.
  24723. */
  24724. set: function (value) {
  24725. if (this._environmentTexture === value) {
  24726. return;
  24727. }
  24728. this._environmentTexture = value;
  24729. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24730. },
  24731. enumerable: true,
  24732. configurable: true
  24733. });
  24734. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24735. /**
  24736. * Default image processing configuration used either in the rendering
  24737. * Forward main pass or through the imageProcessingPostProcess if present.
  24738. * As in the majority of the scene they are the same (exception for multi camera),
  24739. * this is easier to reference from here than from all the materials and post process.
  24740. *
  24741. * No setter as we it is a shared configuration, you can set the values instead.
  24742. */
  24743. get: function () {
  24744. return this._imageProcessingConfiguration;
  24745. },
  24746. enumerable: true,
  24747. configurable: true
  24748. });
  24749. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24750. get: function () {
  24751. return this._forceWireframe;
  24752. },
  24753. /**
  24754. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24755. */
  24756. set: function (value) {
  24757. if (this._forceWireframe === value) {
  24758. return;
  24759. }
  24760. this._forceWireframe = value;
  24761. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24762. },
  24763. enumerable: true,
  24764. configurable: true
  24765. });
  24766. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24767. get: function () {
  24768. return this._forcePointsCloud;
  24769. },
  24770. /**
  24771. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24772. */
  24773. set: function (value) {
  24774. if (this._forcePointsCloud === value) {
  24775. return;
  24776. }
  24777. this._forcePointsCloud = value;
  24778. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24779. },
  24780. enumerable: true,
  24781. configurable: true
  24782. });
  24783. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24784. /**
  24785. * Gets or sets the animation properties override
  24786. */
  24787. get: function () {
  24788. return this._animationPropertiesOverride;
  24789. },
  24790. set: function (value) {
  24791. this._animationPropertiesOverride = value;
  24792. },
  24793. enumerable: true,
  24794. configurable: true
  24795. });
  24796. Object.defineProperty(Scene.prototype, "onDispose", {
  24797. /** Sets a function to be executed when this scene is disposed. */
  24798. set: function (callback) {
  24799. if (this._onDisposeObserver) {
  24800. this.onDisposeObservable.remove(this._onDisposeObserver);
  24801. }
  24802. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24803. },
  24804. enumerable: true,
  24805. configurable: true
  24806. });
  24807. Object.defineProperty(Scene.prototype, "beforeRender", {
  24808. /** Sets a function to be executed before rendering this scene */
  24809. set: function (callback) {
  24810. if (this._onBeforeRenderObserver) {
  24811. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24812. }
  24813. if (callback) {
  24814. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24815. }
  24816. },
  24817. enumerable: true,
  24818. configurable: true
  24819. });
  24820. Object.defineProperty(Scene.prototype, "afterRender", {
  24821. /** Sets a function to be executed after rendering this scene */
  24822. set: function (callback) {
  24823. if (this._onAfterRenderObserver) {
  24824. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24825. }
  24826. if (callback) {
  24827. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24828. }
  24829. },
  24830. enumerable: true,
  24831. configurable: true
  24832. });
  24833. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24834. /** Sets a function to be executed before rendering a camera*/
  24835. set: function (callback) {
  24836. if (this._onBeforeCameraRenderObserver) {
  24837. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24838. }
  24839. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24840. },
  24841. enumerable: true,
  24842. configurable: true
  24843. });
  24844. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24845. /** Sets a function to be executed after rendering a camera*/
  24846. set: function (callback) {
  24847. if (this._onAfterCameraRenderObserver) {
  24848. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24849. }
  24850. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24851. },
  24852. enumerable: true,
  24853. configurable: true
  24854. });
  24855. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24856. /**
  24857. * Gets the gamepad manager associated with the scene
  24858. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24859. */
  24860. get: function () {
  24861. if (!this._gamepadManager) {
  24862. this._gamepadManager = new BABYLON.GamepadManager(this);
  24863. }
  24864. return this._gamepadManager;
  24865. },
  24866. enumerable: true,
  24867. configurable: true
  24868. });
  24869. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24870. /**
  24871. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24872. */
  24873. get: function () {
  24874. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24875. },
  24876. enumerable: true,
  24877. configurable: true
  24878. });
  24879. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24880. get: function () {
  24881. return this._useRightHandedSystem;
  24882. },
  24883. /**
  24884. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24885. */
  24886. set: function (value) {
  24887. if (this._useRightHandedSystem === value) {
  24888. return;
  24889. }
  24890. this._useRightHandedSystem = value;
  24891. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24892. },
  24893. enumerable: true,
  24894. configurable: true
  24895. });
  24896. /**
  24897. * Sets the step Id used by deterministic lock step
  24898. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24899. * @param newStepId defines the step Id
  24900. */
  24901. Scene.prototype.setStepId = function (newStepId) {
  24902. this._currentStepId = newStepId;
  24903. };
  24904. ;
  24905. /**
  24906. * Gets the step Id used by deterministic lock step
  24907. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24908. * @returns the step Id
  24909. */
  24910. Scene.prototype.getStepId = function () {
  24911. return this._currentStepId;
  24912. };
  24913. ;
  24914. /**
  24915. * Gets the internal step used by deterministic lock step
  24916. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24917. * @returns the internal step
  24918. */
  24919. Scene.prototype.getInternalStep = function () {
  24920. return this._currentInternalStep;
  24921. };
  24922. ;
  24923. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24924. get: function () {
  24925. return this._fogEnabled;
  24926. },
  24927. /**
  24928. * Gets or sets a boolean indicating if fog is enabled on this scene
  24929. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24930. */
  24931. set: function (value) {
  24932. if (this._fogEnabled === value) {
  24933. return;
  24934. }
  24935. this._fogEnabled = value;
  24936. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24937. },
  24938. enumerable: true,
  24939. configurable: true
  24940. });
  24941. Object.defineProperty(Scene.prototype, "fogMode", {
  24942. get: function () {
  24943. return this._fogMode;
  24944. },
  24945. /**
  24946. * Gets or sets the fog mode to use
  24947. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24948. */
  24949. set: function (value) {
  24950. if (this._fogMode === value) {
  24951. return;
  24952. }
  24953. this._fogMode = value;
  24954. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24955. },
  24956. enumerable: true,
  24957. configurable: true
  24958. });
  24959. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24960. get: function () {
  24961. return this._shadowsEnabled;
  24962. },
  24963. /**
  24964. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24965. */
  24966. set: function (value) {
  24967. if (this._shadowsEnabled === value) {
  24968. return;
  24969. }
  24970. this._shadowsEnabled = value;
  24971. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24972. },
  24973. enumerable: true,
  24974. configurable: true
  24975. });
  24976. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24977. get: function () {
  24978. return this._lightsEnabled;
  24979. },
  24980. /**
  24981. * Gets or sets a boolean indicating if lights are enabled on this scene
  24982. */
  24983. set: function (value) {
  24984. if (this._lightsEnabled === value) {
  24985. return;
  24986. }
  24987. this._lightsEnabled = value;
  24988. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24989. },
  24990. enumerable: true,
  24991. configurable: true
  24992. });
  24993. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24994. /** The default material used on meshes when no material is affected */
  24995. get: function () {
  24996. if (!this._defaultMaterial) {
  24997. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24998. }
  24999. return this._defaultMaterial;
  25000. },
  25001. /** The default material used on meshes when no material is affected */
  25002. set: function (value) {
  25003. this._defaultMaterial = value;
  25004. },
  25005. enumerable: true,
  25006. configurable: true
  25007. });
  25008. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25009. get: function () {
  25010. return this._texturesEnabled;
  25011. },
  25012. /**
  25013. * Gets or sets a boolean indicating if textures are enabled on this scene
  25014. */
  25015. set: function (value) {
  25016. if (this._texturesEnabled === value) {
  25017. return;
  25018. }
  25019. this._texturesEnabled = value;
  25020. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25021. },
  25022. enumerable: true,
  25023. configurable: true
  25024. });
  25025. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25026. get: function () {
  25027. return this._skeletonsEnabled;
  25028. },
  25029. /**
  25030. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25031. */
  25032. set: function (value) {
  25033. if (this._skeletonsEnabled === value) {
  25034. return;
  25035. }
  25036. this._skeletonsEnabled = value;
  25037. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25038. },
  25039. enumerable: true,
  25040. configurable: true
  25041. });
  25042. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  25043. /**
  25044. * Gets the postprocess render pipeline manager
  25045. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  25046. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  25047. */
  25048. get: function () {
  25049. if (!this._postProcessRenderPipelineManager) {
  25050. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  25051. }
  25052. return this._postProcessRenderPipelineManager;
  25053. },
  25054. enumerable: true,
  25055. configurable: true
  25056. });
  25057. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  25058. /**
  25059. * Gets the main soundtrack associated with the scene
  25060. */
  25061. get: function () {
  25062. if (!this._mainSoundTrack) {
  25063. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  25064. }
  25065. return this._mainSoundTrack;
  25066. },
  25067. enumerable: true,
  25068. configurable: true
  25069. });
  25070. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25071. /** @hidden */
  25072. get: function () {
  25073. return this._alternateRendering;
  25074. },
  25075. enumerable: true,
  25076. configurable: true
  25077. });
  25078. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25079. /**
  25080. * Gets the list of frustum planes (built from the active camera)
  25081. */
  25082. get: function () {
  25083. return this._frustumPlanes;
  25084. },
  25085. enumerable: true,
  25086. configurable: true
  25087. });
  25088. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  25089. /**
  25090. * Gets the current geometry buffer associated to the scene.
  25091. */
  25092. get: function () {
  25093. return this._geometryBufferRenderer;
  25094. },
  25095. /**
  25096. * Sets the current geometry buffer for the scene.
  25097. */
  25098. set: function (geometryBufferRenderer) {
  25099. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  25100. this._geometryBufferRenderer = geometryBufferRenderer;
  25101. }
  25102. },
  25103. enumerable: true,
  25104. configurable: true
  25105. });
  25106. /**
  25107. * Registers the transient components if needed.
  25108. */
  25109. Scene.prototype._registerTransientComponents = function () {
  25110. // Register components that have been associated lately to the scene.
  25111. if (this._transientComponents.length > 0) {
  25112. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25113. var component = _a[_i];
  25114. component.register();
  25115. }
  25116. this._transientComponents = [];
  25117. }
  25118. };
  25119. /**
  25120. * Add a component to the scene.
  25121. * Note that the ccomponent could be registered on th next frame if this is called after
  25122. * the register component stage.
  25123. * @param component Defines the component to add to the scene
  25124. */
  25125. Scene.prototype._addComponent = function (component) {
  25126. this._components.push(component);
  25127. this._transientComponents.push(component);
  25128. };
  25129. /**
  25130. * Gets a component from the scene.
  25131. * @param name defines the name of the component to retrieve
  25132. * @returns the component or null if not present
  25133. */
  25134. Scene.prototype._getComponent = function (name) {
  25135. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25136. var component = _a[_i];
  25137. if (component.name === name) {
  25138. return component;
  25139. }
  25140. }
  25141. return null;
  25142. };
  25143. Object.defineProperty(Scene.prototype, "debugLayer", {
  25144. /**
  25145. * Gets the debug layer (aka Inspector) associated with the scene
  25146. * @see http://doc.babylonjs.com/features/playground_debuglayer
  25147. */
  25148. get: function () {
  25149. if (!this._debugLayer) {
  25150. this._debugLayer = new BABYLON.DebugLayer(this);
  25151. }
  25152. return this._debugLayer;
  25153. },
  25154. enumerable: true,
  25155. configurable: true
  25156. });
  25157. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25158. /**
  25159. * Gets a boolean indicating if collisions are processed on a web worker
  25160. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25161. */
  25162. get: function () {
  25163. return this._workerCollisions;
  25164. },
  25165. set: function (enabled) {
  25166. if (!BABYLON.CollisionCoordinatorLegacy) {
  25167. return;
  25168. }
  25169. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25170. this._workerCollisions = enabled;
  25171. if (this.collisionCoordinator) {
  25172. this.collisionCoordinator.destroy();
  25173. }
  25174. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25175. this.collisionCoordinator.init(this);
  25176. },
  25177. enumerable: true,
  25178. configurable: true
  25179. });
  25180. Object.defineProperty(Scene.prototype, "selectionOctree", {
  25181. /**
  25182. * Gets the octree used to boost mesh selection (picking)
  25183. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  25184. */
  25185. get: function () {
  25186. return this._selectionOctree;
  25187. },
  25188. enumerable: true,
  25189. configurable: true
  25190. });
  25191. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25192. /**
  25193. * Gets the mesh that is currently under the pointer
  25194. */
  25195. get: function () {
  25196. return this._pointerOverMesh;
  25197. },
  25198. enumerable: true,
  25199. configurable: true
  25200. });
  25201. Object.defineProperty(Scene.prototype, "pointerX", {
  25202. /**
  25203. * Gets the current on-screen X position of the pointer
  25204. */
  25205. get: function () {
  25206. return this._pointerX;
  25207. },
  25208. enumerable: true,
  25209. configurable: true
  25210. });
  25211. Object.defineProperty(Scene.prototype, "pointerY", {
  25212. /**
  25213. * Gets the current on-screen Y position of the pointer
  25214. */
  25215. get: function () {
  25216. return this._pointerY;
  25217. },
  25218. enumerable: true,
  25219. configurable: true
  25220. });
  25221. /**
  25222. * Gets the cached material (ie. the latest rendered one)
  25223. * @returns the cached material
  25224. */
  25225. Scene.prototype.getCachedMaterial = function () {
  25226. return this._cachedMaterial;
  25227. };
  25228. /**
  25229. * Gets the cached effect (ie. the latest rendered one)
  25230. * @returns the cached effect
  25231. */
  25232. Scene.prototype.getCachedEffect = function () {
  25233. return this._cachedEffect;
  25234. };
  25235. /**
  25236. * Gets the cached visibility state (ie. the latest rendered one)
  25237. * @returns the cached visibility state
  25238. */
  25239. Scene.prototype.getCachedVisibility = function () {
  25240. return this._cachedVisibility;
  25241. };
  25242. /**
  25243. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25244. * @param material defines the current material
  25245. * @param effect defines the current effect
  25246. * @param visibility defines the current visibility state
  25247. * @returns true if one parameter is not cached
  25248. */
  25249. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25250. if (visibility === void 0) { visibility = 1; }
  25251. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25252. };
  25253. /**
  25254. * Gets the bounding box renderer associated with the scene
  25255. * @returns a BoundingBoxRenderer
  25256. */
  25257. Scene.prototype.getBoundingBoxRenderer = function () {
  25258. if (!this._boundingBoxRenderer) {
  25259. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  25260. }
  25261. return this._boundingBoxRenderer;
  25262. };
  25263. /**
  25264. * Gets the outline renderer associated with the scene
  25265. * @returns a OutlineRenderer
  25266. */
  25267. Scene.prototype.getOutlineRenderer = function () {
  25268. return this._outlineRenderer;
  25269. };
  25270. /**
  25271. * Gets the engine associated with the scene
  25272. * @returns an Engine
  25273. */
  25274. Scene.prototype.getEngine = function () {
  25275. return this._engine;
  25276. };
  25277. /**
  25278. * Gets the total number of vertices rendered per frame
  25279. * @returns the total number of vertices rendered per frame
  25280. */
  25281. Scene.prototype.getTotalVertices = function () {
  25282. return this._totalVertices.current;
  25283. };
  25284. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25285. /**
  25286. * Gets the performance counter for total vertices
  25287. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25288. */
  25289. get: function () {
  25290. return this._totalVertices;
  25291. },
  25292. enumerable: true,
  25293. configurable: true
  25294. });
  25295. /**
  25296. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25297. * @returns the total number of active indices rendered per frame
  25298. */
  25299. Scene.prototype.getActiveIndices = function () {
  25300. return this._activeIndices.current;
  25301. };
  25302. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25303. /**
  25304. * Gets the performance counter for active indices
  25305. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25306. */
  25307. get: function () {
  25308. return this._activeIndices;
  25309. },
  25310. enumerable: true,
  25311. configurable: true
  25312. });
  25313. /**
  25314. * Gets the total number of active particles rendered per frame
  25315. * @returns the total number of active particles rendered per frame
  25316. */
  25317. Scene.prototype.getActiveParticles = function () {
  25318. return this._activeParticles.current;
  25319. };
  25320. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25321. /**
  25322. * Gets the performance counter for active particles
  25323. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25324. */
  25325. get: function () {
  25326. return this._activeParticles;
  25327. },
  25328. enumerable: true,
  25329. configurable: true
  25330. });
  25331. /**
  25332. * Gets the total number of active bones rendered per frame
  25333. * @returns the total number of active bones rendered per frame
  25334. */
  25335. Scene.prototype.getActiveBones = function () {
  25336. return this._activeBones.current;
  25337. };
  25338. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25339. /**
  25340. * Gets the performance counter for active bones
  25341. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25342. */
  25343. get: function () {
  25344. return this._activeBones;
  25345. },
  25346. enumerable: true,
  25347. configurable: true
  25348. });
  25349. /** @hidden */
  25350. Scene.prototype.getInterFramePerfCounter = function () {
  25351. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25352. return 0;
  25353. };
  25354. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25355. /** @hidden */
  25356. get: function () {
  25357. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25358. return null;
  25359. },
  25360. enumerable: true,
  25361. configurable: true
  25362. });
  25363. /** @hidden */
  25364. Scene.prototype.getLastFrameDuration = function () {
  25365. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25366. return 0;
  25367. };
  25368. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25369. /** @hidden */
  25370. get: function () {
  25371. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25372. return null;
  25373. },
  25374. enumerable: true,
  25375. configurable: true
  25376. });
  25377. /** @hidden */
  25378. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25379. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25380. return 0;
  25381. };
  25382. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25383. /** @hidden */
  25384. get: function () {
  25385. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25386. return null;
  25387. },
  25388. enumerable: true,
  25389. configurable: true
  25390. });
  25391. /**
  25392. * Gets the array of active meshes
  25393. * @returns an array of AbstractMesh
  25394. */
  25395. Scene.prototype.getActiveMeshes = function () {
  25396. return this._activeMeshes;
  25397. };
  25398. /** @hidden */
  25399. Scene.prototype.getRenderTargetsDuration = function () {
  25400. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25401. return 0;
  25402. };
  25403. /** @hidden */
  25404. Scene.prototype.getRenderDuration = function () {
  25405. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25406. return 0;
  25407. };
  25408. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25409. /** @hidden */
  25410. get: function () {
  25411. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25412. return null;
  25413. },
  25414. enumerable: true,
  25415. configurable: true
  25416. });
  25417. /** @hidden */
  25418. Scene.prototype.getParticlesDuration = function () {
  25419. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25420. return 0;
  25421. };
  25422. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25423. /** @hidden */
  25424. get: function () {
  25425. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25426. return null;
  25427. },
  25428. enumerable: true,
  25429. configurable: true
  25430. });
  25431. /** @hidden */
  25432. Scene.prototype.getSpritesDuration = function () {
  25433. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25434. return 0;
  25435. };
  25436. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25437. /** @hidden */
  25438. get: function () {
  25439. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25440. return null;
  25441. },
  25442. enumerable: true,
  25443. configurable: true
  25444. });
  25445. /**
  25446. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25447. * @returns a number
  25448. */
  25449. Scene.prototype.getAnimationRatio = function () {
  25450. return this._animationRatio;
  25451. };
  25452. /**
  25453. * Gets an unique Id for the current frame
  25454. * @returns a number
  25455. */
  25456. Scene.prototype.getRenderId = function () {
  25457. return this._renderId;
  25458. };
  25459. /** Call this function if you want to manually increment the render Id*/
  25460. Scene.prototype.incrementRenderId = function () {
  25461. this._renderId++;
  25462. };
  25463. Scene.prototype._updatePointerPosition = function (evt) {
  25464. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25465. if (!canvasRect) {
  25466. return;
  25467. }
  25468. this._pointerX = evt.clientX - canvasRect.left;
  25469. this._pointerY = evt.clientY - canvasRect.top;
  25470. this._unTranslatedPointerX = this._pointerX;
  25471. this._unTranslatedPointerY = this._pointerY;
  25472. };
  25473. Scene.prototype._createUbo = function () {
  25474. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25475. this._sceneUbo.addUniform("viewProjection", 16);
  25476. this._sceneUbo.addUniform("view", 16);
  25477. };
  25478. Scene.prototype._createAlternateUbo = function () {
  25479. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25480. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25481. this._alternateSceneUbo.addUniform("view", 16);
  25482. };
  25483. // Pointers handling
  25484. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25485. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25486. if (result) {
  25487. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25488. }
  25489. return result;
  25490. };
  25491. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25492. if (pointerInfo.pickInfo) {
  25493. if (!pointerInfo.pickInfo.ray) {
  25494. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25495. }
  25496. }
  25497. };
  25498. /**
  25499. * Use this method to simulate a pointer move on a mesh
  25500. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25501. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25502. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25503. * @returns the current scene
  25504. */
  25505. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25506. var evt = new PointerEvent("pointermove", pointerEventInit);
  25507. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25508. return this;
  25509. }
  25510. return this._processPointerMove(pickResult, evt);
  25511. };
  25512. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25513. var canvas = this._engine.getRenderingCanvas();
  25514. if (!canvas) {
  25515. return this;
  25516. }
  25517. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25518. this.setPointerOverSprite(null);
  25519. this.setPointerOverMesh(pickResult.pickedMesh);
  25520. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25521. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25522. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25523. }
  25524. else {
  25525. canvas.style.cursor = this.hoverCursor;
  25526. }
  25527. }
  25528. else {
  25529. canvas.style.cursor = this.defaultCursor;
  25530. }
  25531. }
  25532. else {
  25533. this.setPointerOverMesh(null);
  25534. // Sprites
  25535. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25536. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25537. this.setPointerOverSprite(pickResult.pickedSprite);
  25538. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25539. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25540. }
  25541. else {
  25542. canvas.style.cursor = this.hoverCursor;
  25543. }
  25544. }
  25545. else {
  25546. this.setPointerOverSprite(null);
  25547. // Restore pointer
  25548. canvas.style.cursor = this.defaultCursor;
  25549. }
  25550. }
  25551. if (pickResult) {
  25552. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25553. if (this.onPointerMove) {
  25554. this.onPointerMove(evt, pickResult, type);
  25555. }
  25556. if (this.onPointerObservable.hasObservers()) {
  25557. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25558. this._setRayOnPointerInfo(pi);
  25559. this.onPointerObservable.notifyObservers(pi, type);
  25560. }
  25561. }
  25562. return this;
  25563. };
  25564. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25565. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25566. if (pickResult) {
  25567. pi.ray = pickResult.ray;
  25568. }
  25569. this.onPrePointerObservable.notifyObservers(pi, type);
  25570. if (pi.skipOnPointerObservable) {
  25571. return true;
  25572. }
  25573. else {
  25574. return false;
  25575. }
  25576. };
  25577. /**
  25578. * Use this method to simulate a pointer down on a mesh
  25579. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25580. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25581. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25582. * @returns the current scene
  25583. */
  25584. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25585. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25586. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25587. return this;
  25588. }
  25589. return this._processPointerDown(pickResult, evt);
  25590. };
  25591. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25592. var _this = this;
  25593. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25594. this._pickedDownMesh = pickResult.pickedMesh;
  25595. var actionManager = pickResult.pickedMesh.actionManager;
  25596. if (actionManager) {
  25597. if (actionManager.hasPickTriggers) {
  25598. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25599. switch (evt.button) {
  25600. case 0:
  25601. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25602. break;
  25603. case 1:
  25604. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25605. break;
  25606. case 2:
  25607. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25608. break;
  25609. }
  25610. }
  25611. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25612. window.setTimeout(function () {
  25613. 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);
  25614. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25615. if (_this._totalPointersPressed !== 0 &&
  25616. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25617. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25618. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25619. _this._startingPointerTime = 0;
  25620. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25621. }
  25622. }
  25623. }, Scene.LongPressDelay);
  25624. }
  25625. }
  25626. }
  25627. if (pickResult) {
  25628. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25629. if (this.onPointerDown) {
  25630. this.onPointerDown(evt, pickResult, type);
  25631. }
  25632. if (this.onPointerObservable.hasObservers()) {
  25633. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25634. this._setRayOnPointerInfo(pi);
  25635. this.onPointerObservable.notifyObservers(pi, type);
  25636. }
  25637. }
  25638. return this;
  25639. };
  25640. /**
  25641. * Use this method to simulate a pointer up on a mesh
  25642. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25643. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25644. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25645. * @returns the current scene
  25646. */
  25647. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25648. var evt = new PointerEvent("pointerup", pointerEventInit);
  25649. var clickInfo = new ClickInfo();
  25650. clickInfo.singleClick = true;
  25651. clickInfo.ignore = true;
  25652. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25653. return this;
  25654. }
  25655. return this._processPointerUp(pickResult, evt, clickInfo);
  25656. };
  25657. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25658. if (pickResult && pickResult && pickResult.pickedMesh) {
  25659. this._pickedUpMesh = pickResult.pickedMesh;
  25660. if (this._pickedDownMesh === this._pickedUpMesh) {
  25661. if (this.onPointerPick) {
  25662. this.onPointerPick(evt, pickResult);
  25663. }
  25664. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25665. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25666. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25667. this._setRayOnPointerInfo(pi);
  25668. this.onPointerObservable.notifyObservers(pi, type_1);
  25669. }
  25670. }
  25671. if (pickResult.pickedMesh.actionManager) {
  25672. if (clickInfo.ignore) {
  25673. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25674. }
  25675. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25676. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25677. }
  25678. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25679. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25680. }
  25681. }
  25682. }
  25683. if (this._pickedDownMesh &&
  25684. this._pickedDownMesh.actionManager &&
  25685. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25686. this._pickedDownMesh !== this._pickedUpMesh) {
  25687. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25688. }
  25689. var type = BABYLON.PointerEventTypes.POINTERUP;
  25690. if (this.onPointerObservable.hasObservers()) {
  25691. if (!clickInfo.ignore) {
  25692. if (!clickInfo.hasSwiped) {
  25693. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25694. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25695. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25696. this._setRayOnPointerInfo(pi);
  25697. this.onPointerObservable.notifyObservers(pi, type_2);
  25698. }
  25699. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25700. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25701. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25702. this._setRayOnPointerInfo(pi);
  25703. this.onPointerObservable.notifyObservers(pi, type_3);
  25704. }
  25705. }
  25706. }
  25707. else {
  25708. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25709. this._setRayOnPointerInfo(pi);
  25710. this.onPointerObservable.notifyObservers(pi, type);
  25711. }
  25712. }
  25713. if (this.onPointerUp) {
  25714. this.onPointerUp(evt, pickResult, type);
  25715. }
  25716. return this;
  25717. };
  25718. /**
  25719. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25720. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25721. * @returns true if the pointer was captured
  25722. */
  25723. Scene.prototype.isPointerCaptured = function (pointerId) {
  25724. if (pointerId === void 0) { pointerId = 0; }
  25725. return this._pointerCaptures[pointerId];
  25726. };
  25727. /**
  25728. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25729. * @param attachUp defines if you want to attach events to pointerup
  25730. * @param attachDown defines if you want to attach events to pointerdown
  25731. * @param attachMove defines if you want to attach events to pointermove
  25732. */
  25733. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25734. var _this = this;
  25735. if (attachUp === void 0) { attachUp = true; }
  25736. if (attachDown === void 0) { attachDown = true; }
  25737. if (attachMove === void 0) { attachMove = true; }
  25738. this._initActionManager = function (act, clickInfo) {
  25739. if (!_this._meshPickProceed) {
  25740. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25741. _this._currentPickResult = pickResult;
  25742. if (pickResult) {
  25743. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25744. }
  25745. _this._meshPickProceed = true;
  25746. }
  25747. return act;
  25748. };
  25749. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25750. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25751. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25752. btn !== _this._previousButtonPressed) {
  25753. _this._doubleClickOccured = false;
  25754. clickInfo.singleClick = true;
  25755. clickInfo.ignore = false;
  25756. cb(clickInfo, _this._currentPickResult);
  25757. }
  25758. };
  25759. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25760. var clickInfo = new ClickInfo();
  25761. _this._currentPickResult = null;
  25762. var act = null;
  25763. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25764. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25765. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25766. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25767. act = _this._initActionManager(act, clickInfo);
  25768. if (act)
  25769. checkPicking = act.hasPickTriggers;
  25770. }
  25771. if (checkPicking) {
  25772. var btn = evt.button;
  25773. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25774. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25775. if (!clickInfo.hasSwiped) {
  25776. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25777. if (!checkSingleClickImmediately) {
  25778. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25779. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25780. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25781. act = _this._initActionManager(act, clickInfo);
  25782. if (act)
  25783. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25784. }
  25785. }
  25786. if (checkSingleClickImmediately) {
  25787. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25788. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25789. btn !== _this._previousButtonPressed) {
  25790. clickInfo.singleClick = true;
  25791. cb(clickInfo, _this._currentPickResult);
  25792. }
  25793. }
  25794. // at least one double click is required to be check and exclusive double click is enabled
  25795. else {
  25796. // wait that no double click has been raised during the double click delay
  25797. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25798. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25799. }
  25800. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25801. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25802. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25803. act = _this._initActionManager(act, clickInfo);
  25804. if (act)
  25805. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25806. }
  25807. if (checkDoubleClick) {
  25808. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25809. if (btn === _this._previousButtonPressed &&
  25810. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25811. !_this._doubleClickOccured) {
  25812. // pointer has not moved for 2 clicks, it's a double click
  25813. if (!clickInfo.hasSwiped &&
  25814. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25815. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25816. _this._previousStartingPointerTime = 0;
  25817. _this._doubleClickOccured = true;
  25818. clickInfo.doubleClick = true;
  25819. clickInfo.ignore = false;
  25820. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25821. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25822. }
  25823. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25824. cb(clickInfo, _this._currentPickResult);
  25825. }
  25826. // if the two successive clicks are too far, it's just two simple clicks
  25827. else {
  25828. _this._doubleClickOccured = false;
  25829. _this._previousStartingPointerTime = _this._startingPointerTime;
  25830. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25831. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25832. _this._previousButtonPressed = btn;
  25833. if (Scene.ExclusiveDoubleClickMode) {
  25834. if (_this._previousDelayedSimpleClickTimeout) {
  25835. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25836. }
  25837. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25838. cb(clickInfo, _this._previousPickResult);
  25839. }
  25840. else {
  25841. cb(clickInfo, _this._currentPickResult);
  25842. }
  25843. }
  25844. }
  25845. // just the first click of the double has been raised
  25846. else {
  25847. _this._doubleClickOccured = false;
  25848. _this._previousStartingPointerTime = _this._startingPointerTime;
  25849. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25850. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25851. _this._previousButtonPressed = btn;
  25852. }
  25853. }
  25854. }
  25855. }
  25856. clickInfo.ignore = true;
  25857. cb(clickInfo, _this._currentPickResult);
  25858. };
  25859. this._spritePredicate = function (sprite) {
  25860. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25861. };
  25862. this._onPointerMove = function (evt) {
  25863. _this._updatePointerPosition(evt);
  25864. // PreObservable support
  25865. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25866. return;
  25867. }
  25868. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25869. return;
  25870. }
  25871. if (!_this.pointerMovePredicate) {
  25872. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25873. }
  25874. // Meshes
  25875. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25876. _this._processPointerMove(pickResult, evt);
  25877. };
  25878. this._onPointerDown = function (evt) {
  25879. _this._totalPointersPressed++;
  25880. _this._pickedDownMesh = null;
  25881. _this._meshPickProceed = false;
  25882. _this._updatePointerPosition(evt);
  25883. if (_this.preventDefaultOnPointerDown && canvas) {
  25884. evt.preventDefault();
  25885. canvas.focus();
  25886. }
  25887. // PreObservable support
  25888. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25889. return;
  25890. }
  25891. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25892. return;
  25893. }
  25894. _this._pointerCaptures[evt.pointerId] = true;
  25895. _this._startingPointerPosition.x = _this._pointerX;
  25896. _this._startingPointerPosition.y = _this._pointerY;
  25897. _this._startingPointerTime = Date.now();
  25898. if (!_this.pointerDownPredicate) {
  25899. _this.pointerDownPredicate = function (mesh) {
  25900. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25901. };
  25902. }
  25903. // Meshes
  25904. _this._pickedDownMesh = null;
  25905. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25906. _this._processPointerDown(pickResult, evt);
  25907. // Sprites
  25908. _this._pickedDownSprite = null;
  25909. if (_this.spriteManagers.length > 0) {
  25910. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25911. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25912. if (pickResult.pickedSprite.actionManager) {
  25913. _this._pickedDownSprite = pickResult.pickedSprite;
  25914. switch (evt.button) {
  25915. case 0:
  25916. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25917. break;
  25918. case 1:
  25919. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25920. break;
  25921. case 2:
  25922. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25923. break;
  25924. }
  25925. if (pickResult.pickedSprite.actionManager) {
  25926. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25927. }
  25928. }
  25929. }
  25930. }
  25931. };
  25932. this._onPointerUp = function (evt) {
  25933. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25934. return; // So we need to test it the pointer down was pressed before.
  25935. }
  25936. _this._totalPointersPressed--;
  25937. _this._pickedUpMesh = null;
  25938. _this._meshPickProceed = false;
  25939. _this._updatePointerPosition(evt);
  25940. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25941. // PreObservable support
  25942. if (_this.onPrePointerObservable.hasObservers()) {
  25943. if (!clickInfo.ignore) {
  25944. if (!clickInfo.hasSwiped) {
  25945. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25946. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25947. return;
  25948. }
  25949. }
  25950. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25951. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25952. return;
  25953. }
  25954. }
  25955. }
  25956. }
  25957. else {
  25958. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25959. return;
  25960. }
  25961. }
  25962. }
  25963. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25964. return;
  25965. }
  25966. _this._pointerCaptures[evt.pointerId] = false;
  25967. if (!_this.pointerUpPredicate) {
  25968. _this.pointerUpPredicate = function (mesh) {
  25969. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25970. };
  25971. }
  25972. // Meshes
  25973. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25974. _this._initActionManager(null, clickInfo);
  25975. }
  25976. if (!pickResult) {
  25977. pickResult = _this._currentPickResult;
  25978. }
  25979. _this._processPointerUp(pickResult, evt, clickInfo);
  25980. // Sprites
  25981. if (!clickInfo.ignore) {
  25982. if (_this.spriteManagers.length > 0) {
  25983. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25984. if (spritePickResult) {
  25985. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25986. if (spritePickResult.pickedSprite.actionManager) {
  25987. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25988. if (spritePickResult.pickedSprite.actionManager) {
  25989. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25990. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25991. }
  25992. }
  25993. }
  25994. }
  25995. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25996. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25997. }
  25998. }
  25999. }
  26000. }
  26001. _this._previousPickResult = _this._currentPickResult;
  26002. });
  26003. };
  26004. this._onKeyDown = function (evt) {
  26005. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26006. if (_this.onPreKeyboardObservable.hasObservers()) {
  26007. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26008. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26009. if (pi.skipOnPointerObservable) {
  26010. return;
  26011. }
  26012. }
  26013. if (_this.onKeyboardObservable.hasObservers()) {
  26014. var pi = new BABYLON.KeyboardInfo(type, evt);
  26015. _this.onKeyboardObservable.notifyObservers(pi, type);
  26016. }
  26017. if (_this.actionManager) {
  26018. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26019. }
  26020. };
  26021. this._onKeyUp = function (evt) {
  26022. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26023. if (_this.onPreKeyboardObservable.hasObservers()) {
  26024. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26025. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26026. if (pi.skipOnPointerObservable) {
  26027. return;
  26028. }
  26029. }
  26030. if (_this.onKeyboardObservable.hasObservers()) {
  26031. var pi = new BABYLON.KeyboardInfo(type, evt);
  26032. _this.onKeyboardObservable.notifyObservers(pi, type);
  26033. }
  26034. if (_this.actionManager) {
  26035. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26036. }
  26037. };
  26038. var engine = this.getEngine();
  26039. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26040. if (!canvas) {
  26041. return;
  26042. }
  26043. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26044. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26045. });
  26046. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26047. if (!canvas) {
  26048. return;
  26049. }
  26050. canvas.removeEventListener("keydown", _this._onKeyDown);
  26051. canvas.removeEventListener("keyup", _this._onKeyUp);
  26052. });
  26053. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26054. var canvas = this._engine.getRenderingCanvas();
  26055. if (!canvas) {
  26056. return;
  26057. }
  26058. if (attachMove) {
  26059. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26060. // Wheel
  26061. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26062. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26063. }
  26064. if (attachDown) {
  26065. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26066. }
  26067. if (attachUp) {
  26068. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26069. }
  26070. canvas.tabIndex = 1;
  26071. };
  26072. /** Detaches all event handlers*/
  26073. Scene.prototype.detachControl = function () {
  26074. var engine = this.getEngine();
  26075. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26076. var canvas = engine.getRenderingCanvas();
  26077. if (!canvas) {
  26078. return;
  26079. }
  26080. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26081. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26082. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26083. if (this._onCanvasBlurObserver) {
  26084. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26085. }
  26086. if (this._onCanvasFocusObserver) {
  26087. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26088. }
  26089. // Wheel
  26090. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26091. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26092. // Keyboard
  26093. canvas.removeEventListener("keydown", this._onKeyDown);
  26094. canvas.removeEventListener("keyup", this._onKeyUp);
  26095. // Observables
  26096. this.onKeyboardObservable.clear();
  26097. this.onPreKeyboardObservable.clear();
  26098. this.onPointerObservable.clear();
  26099. this.onPrePointerObservable.clear();
  26100. };
  26101. /**
  26102. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26103. * Delay loaded resources are not taking in account
  26104. * @return true if all required resources are ready
  26105. */
  26106. Scene.prototype.isReady = function () {
  26107. if (this._isDisposed) {
  26108. return false;
  26109. }
  26110. if (this._pendingData.length > 0) {
  26111. return false;
  26112. }
  26113. var index;
  26114. var engine = this.getEngine();
  26115. // Geometries
  26116. for (index = 0; index < this.geometries.length; index++) {
  26117. var geometry = this.geometries[index];
  26118. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26119. return false;
  26120. }
  26121. }
  26122. // Meshes
  26123. for (index = 0; index < this.meshes.length; index++) {
  26124. var mesh = this.meshes[index];
  26125. if (!mesh.isEnabled()) {
  26126. continue;
  26127. }
  26128. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26129. continue;
  26130. }
  26131. if (!mesh.isReady(true)) {
  26132. return false;
  26133. }
  26134. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26135. // Is Ready For Mesh
  26136. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26137. var step = _a[_i];
  26138. if (!step.action(mesh, hardwareInstancedRendering)) {
  26139. return false;
  26140. }
  26141. }
  26142. }
  26143. // Post-processes
  26144. if (this.activeCameras && this.activeCameras.length > 0) {
  26145. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26146. var camera = _c[_b];
  26147. if (!camera.isReady(true)) {
  26148. return false;
  26149. }
  26150. }
  26151. }
  26152. else if (this.activeCamera) {
  26153. if (!this.activeCamera.isReady(true)) {
  26154. return false;
  26155. }
  26156. }
  26157. // Particles
  26158. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26159. var particleSystem = _e[_d];
  26160. if (!particleSystem.isReady()) {
  26161. return false;
  26162. }
  26163. }
  26164. return true;
  26165. };
  26166. /** Resets all cached information relative to material (including effect and visibility) */
  26167. Scene.prototype.resetCachedMaterial = function () {
  26168. this._cachedMaterial = null;
  26169. this._cachedEffect = null;
  26170. this._cachedVisibility = null;
  26171. };
  26172. /**
  26173. * Registers a function to be called before every frame render
  26174. * @param func defines the function to register
  26175. */
  26176. Scene.prototype.registerBeforeRender = function (func) {
  26177. this.onBeforeRenderObservable.add(func);
  26178. };
  26179. /**
  26180. * Unregisters a function called before every frame render
  26181. * @param func defines the function to unregister
  26182. */
  26183. Scene.prototype.unregisterBeforeRender = function (func) {
  26184. this.onBeforeRenderObservable.removeCallback(func);
  26185. };
  26186. /**
  26187. * Registers a function to be called after every frame render
  26188. * @param func defines the function to register
  26189. */
  26190. Scene.prototype.registerAfterRender = function (func) {
  26191. this.onAfterRenderObservable.add(func);
  26192. };
  26193. /**
  26194. * Unregisters a function called after every frame render
  26195. * @param func defines the function to unregister
  26196. */
  26197. Scene.prototype.unregisterAfterRender = function (func) {
  26198. this.onAfterRenderObservable.removeCallback(func);
  26199. };
  26200. Scene.prototype._executeOnceBeforeRender = function (func) {
  26201. var _this = this;
  26202. var execFunc = function () {
  26203. func();
  26204. setTimeout(function () {
  26205. _this.unregisterBeforeRender(execFunc);
  26206. });
  26207. };
  26208. this.registerBeforeRender(execFunc);
  26209. };
  26210. /**
  26211. * The provided function will run before render once and will be disposed afterwards.
  26212. * A timeout delay can be provided so that the function will be executed in N ms.
  26213. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26214. * @param func The function to be executed.
  26215. * @param timeout optional delay in ms
  26216. */
  26217. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26218. var _this = this;
  26219. if (timeout !== undefined) {
  26220. setTimeout(function () {
  26221. _this._executeOnceBeforeRender(func);
  26222. }, timeout);
  26223. }
  26224. else {
  26225. this._executeOnceBeforeRender(func);
  26226. }
  26227. };
  26228. /** @hidden */
  26229. Scene.prototype._addPendingData = function (data) {
  26230. this._pendingData.push(data);
  26231. };
  26232. /** @hidden */
  26233. Scene.prototype._removePendingData = function (data) {
  26234. var wasLoading = this.isLoading;
  26235. var index = this._pendingData.indexOf(data);
  26236. if (index !== -1) {
  26237. this._pendingData.splice(index, 1);
  26238. }
  26239. if (wasLoading && !this.isLoading) {
  26240. this.onDataLoadedObservable.notifyObservers(this);
  26241. }
  26242. };
  26243. /**
  26244. * Returns the number of items waiting to be loaded
  26245. * @returns the number of items waiting to be loaded
  26246. */
  26247. Scene.prototype.getWaitingItemsCount = function () {
  26248. return this._pendingData.length;
  26249. };
  26250. Object.defineProperty(Scene.prototype, "isLoading", {
  26251. /**
  26252. * Returns a boolean indicating if the scene is still loading data
  26253. */
  26254. get: function () {
  26255. return this._pendingData.length > 0;
  26256. },
  26257. enumerable: true,
  26258. configurable: true
  26259. });
  26260. /**
  26261. * Registers a function to be executed when the scene is ready
  26262. * @param {Function} func - the function to be executed
  26263. */
  26264. Scene.prototype.executeWhenReady = function (func) {
  26265. var _this = this;
  26266. this.onReadyObservable.add(func);
  26267. if (this._executeWhenReadyTimeoutId !== -1) {
  26268. return;
  26269. }
  26270. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26271. _this._checkIsReady();
  26272. }, 150);
  26273. };
  26274. /**
  26275. * Returns a promise that resolves when the scene is ready
  26276. * @returns A promise that resolves when the scene is ready
  26277. */
  26278. Scene.prototype.whenReadyAsync = function () {
  26279. var _this = this;
  26280. return new Promise(function (resolve) {
  26281. _this.executeWhenReady(function () {
  26282. resolve();
  26283. });
  26284. });
  26285. };
  26286. /** @hidden */
  26287. Scene.prototype._checkIsReady = function () {
  26288. var _this = this;
  26289. this._registerTransientComponents();
  26290. if (this.isReady()) {
  26291. this.onReadyObservable.notifyObservers(this);
  26292. this.onReadyObservable.clear();
  26293. this._executeWhenReadyTimeoutId = -1;
  26294. return;
  26295. }
  26296. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26297. _this._checkIsReady();
  26298. }, 150);
  26299. };
  26300. // Animations
  26301. /**
  26302. * Will start the animation sequence of a given target
  26303. * @param target defines the target
  26304. * @param from defines from which frame should animation start
  26305. * @param to defines until which frame should animation run.
  26306. * @param weight defines the weight to apply to the animation (1.0 by default)
  26307. * @param loop defines if the animation loops
  26308. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26309. * @param onAnimationEnd defines the function to be executed when the animation ends
  26310. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26311. * @returns the animatable object created for this animation
  26312. */
  26313. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  26314. if (weight === void 0) { weight = 1.0; }
  26315. if (speedRatio === void 0) { speedRatio = 1.0; }
  26316. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  26317. returnedAnimatable.weight = weight;
  26318. return returnedAnimatable;
  26319. };
  26320. /**
  26321. * Will start the animation sequence of a given target
  26322. * @param target defines the target
  26323. * @param from defines from which frame should animation start
  26324. * @param to defines until which frame should animation run.
  26325. * @param loop defines if the animation loops
  26326. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26327. * @param onAnimationEnd defines the function to be executed when the animation ends
  26328. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26329. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26330. * @returns the animatable object created for this animation
  26331. */
  26332. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26333. if (speedRatio === void 0) { speedRatio = 1.0; }
  26334. if (stopCurrent === void 0) { stopCurrent = true; }
  26335. if (from > to && speedRatio > 0) {
  26336. speedRatio *= -1;
  26337. }
  26338. if (stopCurrent) {
  26339. this.stopAnimation(target);
  26340. }
  26341. if (!animatable) {
  26342. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26343. }
  26344. // Local animations
  26345. if (target.animations) {
  26346. animatable.appendAnimations(target, target.animations);
  26347. }
  26348. // Children animations
  26349. if (target.getAnimatables) {
  26350. var animatables = target.getAnimatables();
  26351. for (var index = 0; index < animatables.length; index++) {
  26352. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26353. }
  26354. }
  26355. animatable.reset();
  26356. return animatable;
  26357. };
  26358. /**
  26359. * Begin a new animation on a given node
  26360. * @param target defines the target where the animation will take place
  26361. * @param animations defines the list of animations to start
  26362. * @param from defines the initial value
  26363. * @param to defines the final value
  26364. * @param loop defines if you want animation to loop (off by default)
  26365. * @param speedRatio defines the speed ratio to apply to all animations
  26366. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26367. * @returns the list of created animatables
  26368. */
  26369. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26370. if (speedRatio === undefined) {
  26371. speedRatio = 1.0;
  26372. }
  26373. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26374. return animatable;
  26375. };
  26376. /**
  26377. * Begin a new animation on a given node and its hierarchy
  26378. * @param target defines the root node where the animation will take place
  26379. * @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.
  26380. * @param animations defines the list of animations to start
  26381. * @param from defines the initial value
  26382. * @param to defines the final value
  26383. * @param loop defines if you want animation to loop (off by default)
  26384. * @param speedRatio defines the speed ratio to apply to all animations
  26385. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26386. * @returns the list of animatables created for all nodes
  26387. */
  26388. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26389. var children = target.getDescendants(directDescendantsOnly);
  26390. var result = [];
  26391. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26392. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26393. var child = children_1[_i];
  26394. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26395. }
  26396. return result;
  26397. };
  26398. /**
  26399. * Gets the animatable associated with a specific target
  26400. * @param target defines the target of the animatable
  26401. * @returns the required animatable if found
  26402. */
  26403. Scene.prototype.getAnimatableByTarget = function (target) {
  26404. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26405. if (this._activeAnimatables[index].target === target) {
  26406. return this._activeAnimatables[index];
  26407. }
  26408. }
  26409. return null;
  26410. };
  26411. /**
  26412. * Gets all animatables associated with a given target
  26413. * @param target defines the target to look animatables for
  26414. * @returns an array of Animatables
  26415. */
  26416. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26417. var result = [];
  26418. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26419. if (this._activeAnimatables[index].target === target) {
  26420. result.push(this._activeAnimatables[index]);
  26421. }
  26422. }
  26423. return result;
  26424. };
  26425. Object.defineProperty(Scene.prototype, "animatables", {
  26426. /**
  26427. * Gets all animatable attached to the scene
  26428. */
  26429. get: function () {
  26430. return this._activeAnimatables;
  26431. },
  26432. enumerable: true,
  26433. configurable: true
  26434. });
  26435. /**
  26436. * Will stop the animation of the given target
  26437. * @param target - the target
  26438. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26439. */
  26440. Scene.prototype.stopAnimation = function (target, animationName) {
  26441. var animatables = this.getAllAnimatablesByTarget(target);
  26442. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26443. var animatable = animatables_1[_i];
  26444. animatable.stop(animationName);
  26445. }
  26446. };
  26447. /**
  26448. * Stops and removes all animations that have been applied to the scene
  26449. */
  26450. Scene.prototype.stopAllAnimations = function () {
  26451. if (this._activeAnimatables) {
  26452. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26453. this._activeAnimatables[i].stop();
  26454. }
  26455. this._activeAnimatables = [];
  26456. }
  26457. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26458. var group = _a[_i];
  26459. group.stop();
  26460. }
  26461. };
  26462. Scene.prototype._animate = function () {
  26463. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26464. return;
  26465. }
  26466. // Getting time
  26467. var now = BABYLON.Tools.Now;
  26468. if (!this._animationTimeLast) {
  26469. if (this._pendingData.length > 0) {
  26470. return;
  26471. }
  26472. this._animationTimeLast = now;
  26473. }
  26474. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26475. this._animationTime += deltaTime;
  26476. this._animationTimeLast = now;
  26477. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26478. this._activeAnimatables[index]._animate(this._animationTime);
  26479. }
  26480. // Late animation bindings
  26481. this._processLateAnimationBindings();
  26482. };
  26483. /** @hidden */
  26484. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26485. var target = runtimeAnimation.target;
  26486. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26487. if (!target._lateAnimationHolders) {
  26488. target._lateAnimationHolders = {};
  26489. }
  26490. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26491. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26492. totalWeight: 0,
  26493. animations: [],
  26494. originalValue: originalValue
  26495. };
  26496. }
  26497. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26498. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26499. };
  26500. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26501. var normalizer = 1.0;
  26502. var finalPosition = BABYLON.Tmp.Vector3[0];
  26503. var finalScaling = BABYLON.Tmp.Vector3[1];
  26504. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26505. var startIndex = 0;
  26506. var originalAnimation = holder.animations[0];
  26507. var originalValue = holder.originalValue;
  26508. var scale = 1;
  26509. if (holder.totalWeight < 1.0) {
  26510. // We need to mix the original value in
  26511. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26512. scale = 1.0 - holder.totalWeight;
  26513. }
  26514. else {
  26515. startIndex = 1;
  26516. // We need to normalize the weights
  26517. normalizer = holder.totalWeight;
  26518. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26519. scale = originalAnimation.weight / normalizer;
  26520. if (scale == 1) {
  26521. return originalAnimation.currentValue;
  26522. }
  26523. }
  26524. finalScaling.scaleInPlace(scale);
  26525. finalPosition.scaleInPlace(scale);
  26526. finalQuaternion.scaleInPlace(scale);
  26527. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26528. var runtimeAnimation = holder.animations[animIndex];
  26529. var scale = runtimeAnimation.weight / normalizer;
  26530. var currentPosition = BABYLON.Tmp.Vector3[2];
  26531. var currentScaling = BABYLON.Tmp.Vector3[3];
  26532. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26533. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26534. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26535. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26536. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26537. }
  26538. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26539. return originalAnimation._workValue;
  26540. };
  26541. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26542. var originalAnimation = holder.animations[0];
  26543. var originalValue = holder.originalValue;
  26544. if (holder.animations.length === 1) {
  26545. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26546. }
  26547. var normalizer = 1.0;
  26548. var quaternions;
  26549. var weights;
  26550. if (holder.totalWeight < 1.0) {
  26551. var scale = 1.0 - holder.totalWeight;
  26552. quaternions = [];
  26553. weights = [];
  26554. quaternions.push(originalValue);
  26555. weights.push(scale);
  26556. }
  26557. else {
  26558. if (holder.animations.length === 2) { // Slerp as soon as we can
  26559. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26560. }
  26561. quaternions = [];
  26562. weights = [];
  26563. normalizer = holder.totalWeight;
  26564. }
  26565. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26566. var runtimeAnimation = holder.animations[animIndex];
  26567. quaternions.push(runtimeAnimation.currentValue);
  26568. weights.push(runtimeAnimation.weight / normalizer);
  26569. }
  26570. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26571. var cumulativeAmount = 0;
  26572. var cumulativeQuaternion = null;
  26573. for (var index = 0; index < quaternions.length;) {
  26574. if (!cumulativeQuaternion) {
  26575. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26576. cumulativeAmount = weights[index] + weights[index + 1];
  26577. index += 2;
  26578. continue;
  26579. }
  26580. cumulativeAmount += weights[index];
  26581. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26582. index++;
  26583. }
  26584. return cumulativeQuaternion;
  26585. };
  26586. Scene.prototype._processLateAnimationBindings = function () {
  26587. if (!this._registeredForLateAnimationBindings.length) {
  26588. return;
  26589. }
  26590. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26591. var target = this._registeredForLateAnimationBindings.data[index];
  26592. for (var path in target._lateAnimationHolders) {
  26593. var holder = target._lateAnimationHolders[path];
  26594. var originalAnimation = holder.animations[0];
  26595. var originalValue = holder.originalValue;
  26596. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26597. var finalValue = void 0;
  26598. if (matrixDecomposeMode) {
  26599. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26600. }
  26601. else {
  26602. var quaternionMode = originalValue.w !== undefined;
  26603. if (quaternionMode) {
  26604. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26605. }
  26606. else {
  26607. var startIndex = 0;
  26608. var normalizer = 1.0;
  26609. if (holder.totalWeight < 1.0) {
  26610. // We need to mix the original value in
  26611. if (originalValue.scale) {
  26612. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26613. }
  26614. else {
  26615. finalValue = originalValue * (1.0 - holder.totalWeight);
  26616. }
  26617. }
  26618. else {
  26619. // We need to normalize the weights
  26620. normalizer = holder.totalWeight;
  26621. var scale_1 = originalAnimation.weight / normalizer;
  26622. if (scale_1 !== 1) {
  26623. if (originalAnimation.currentValue.scale) {
  26624. finalValue = originalAnimation.currentValue.scale(scale_1);
  26625. }
  26626. else {
  26627. finalValue = originalAnimation.currentValue * scale_1;
  26628. }
  26629. }
  26630. else {
  26631. finalValue = originalAnimation.currentValue;
  26632. }
  26633. startIndex = 1;
  26634. }
  26635. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26636. var runtimeAnimation = holder.animations[animIndex];
  26637. var scale = runtimeAnimation.weight / normalizer;
  26638. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26639. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26640. }
  26641. else {
  26642. finalValue += runtimeAnimation.currentValue * scale;
  26643. }
  26644. }
  26645. }
  26646. }
  26647. target[path] = finalValue;
  26648. }
  26649. target._lateAnimationHolders = {};
  26650. }
  26651. this._registeredForLateAnimationBindings.reset();
  26652. };
  26653. // Matrix
  26654. /** @hidden */
  26655. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26656. this._useAlternateCameraConfiguration = active;
  26657. };
  26658. /**
  26659. * Gets the current view matrix
  26660. * @returns a Matrix
  26661. */
  26662. Scene.prototype.getViewMatrix = function () {
  26663. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26664. };
  26665. /**
  26666. * Gets the current projection matrix
  26667. * @returns a Matrix
  26668. */
  26669. Scene.prototype.getProjectionMatrix = function () {
  26670. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26671. };
  26672. /**
  26673. * Gets the current transform matrix
  26674. * @returns a Matrix made of View * Projection
  26675. */
  26676. Scene.prototype.getTransformMatrix = function () {
  26677. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26678. };
  26679. /**
  26680. * Sets the current transform matrix
  26681. * @param view defines the View matrix to use
  26682. * @param projection defines the Projection matrix to use
  26683. */
  26684. Scene.prototype.setTransformMatrix = function (view, projection) {
  26685. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26686. return;
  26687. }
  26688. this._viewUpdateFlag = view.updateFlag;
  26689. this._projectionUpdateFlag = projection.updateFlag;
  26690. this._viewMatrix = view;
  26691. this._projectionMatrix = projection;
  26692. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26693. // Update frustum
  26694. if (!this._frustumPlanes) {
  26695. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26696. }
  26697. else {
  26698. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26699. }
  26700. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26701. var otherCamera = this.activeCamera._alternateCamera;
  26702. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26703. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26704. }
  26705. if (this._sceneUbo.useUbo) {
  26706. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26707. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26708. this._sceneUbo.update();
  26709. }
  26710. };
  26711. /** @hidden */
  26712. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26713. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26714. return;
  26715. }
  26716. this._alternateViewUpdateFlag = view.updateFlag;
  26717. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26718. this._alternateViewMatrix = view;
  26719. this._alternateProjectionMatrix = projection;
  26720. if (!this._alternateTransformMatrix) {
  26721. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26722. }
  26723. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26724. if (!this._alternateSceneUbo) {
  26725. this._createAlternateUbo();
  26726. }
  26727. if (this._alternateSceneUbo.useUbo) {
  26728. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26729. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26730. this._alternateSceneUbo.update();
  26731. }
  26732. };
  26733. /**
  26734. * Gets the uniform buffer used to store scene data
  26735. * @returns a UniformBuffer
  26736. */
  26737. Scene.prototype.getSceneUniformBuffer = function () {
  26738. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26739. };
  26740. /**
  26741. * Gets an unique (relatively to the current scene) Id
  26742. * @returns an unique number for the scene
  26743. */
  26744. Scene.prototype.getUniqueId = function () {
  26745. var result = Scene._uniqueIdCounter;
  26746. Scene._uniqueIdCounter++;
  26747. return result;
  26748. };
  26749. /**
  26750. * Add a mesh to the list of scene's meshes
  26751. * @param newMesh defines the mesh to add
  26752. * @param recursive if all child meshes should also be added to the scene
  26753. */
  26754. Scene.prototype.addMesh = function (newMesh, recursive) {
  26755. var _this = this;
  26756. if (recursive === void 0) { recursive = false; }
  26757. this.meshes.push(newMesh);
  26758. //notify the collision coordinator
  26759. if (this.collisionCoordinator) {
  26760. this.collisionCoordinator.onMeshAdded(newMesh);
  26761. }
  26762. newMesh._resyncLightSources();
  26763. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26764. if (recursive) {
  26765. newMesh.getChildMeshes().forEach(function (m) {
  26766. _this.addMesh(m);
  26767. });
  26768. }
  26769. };
  26770. /**
  26771. * Remove a mesh for the list of scene's meshes
  26772. * @param toRemove defines the mesh to remove
  26773. * @param recursive if all child meshes should also be removed from the scene
  26774. * @returns the index where the mesh was in the mesh list
  26775. */
  26776. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26777. var _this = this;
  26778. if (recursive === void 0) { recursive = false; }
  26779. var index = this.meshes.indexOf(toRemove);
  26780. if (index !== -1) {
  26781. // Remove from the scene if mesh found
  26782. this.meshes.splice(index, 1);
  26783. }
  26784. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26785. if (recursive) {
  26786. toRemove.getChildMeshes().forEach(function (m) {
  26787. _this.removeMesh(m);
  26788. });
  26789. }
  26790. return index;
  26791. };
  26792. /**
  26793. * Add a transform node to the list of scene's transform nodes
  26794. * @param newTransformNode defines the transform node to add
  26795. */
  26796. Scene.prototype.addTransformNode = function (newTransformNode) {
  26797. this.transformNodes.push(newTransformNode);
  26798. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26799. };
  26800. /**
  26801. * Remove a transform node for the list of scene's transform nodes
  26802. * @param toRemove defines the transform node to remove
  26803. * @returns the index where the transform node was in the transform node list
  26804. */
  26805. Scene.prototype.removeTransformNode = function (toRemove) {
  26806. var index = this.transformNodes.indexOf(toRemove);
  26807. if (index !== -1) {
  26808. // Remove from the scene if found
  26809. this.transformNodes.splice(index, 1);
  26810. }
  26811. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26812. return index;
  26813. };
  26814. /**
  26815. * Remove a skeleton for the list of scene's skeletons
  26816. * @param toRemove defines the skeleton to remove
  26817. * @returns the index where the skeleton was in the skeleton list
  26818. */
  26819. Scene.prototype.removeSkeleton = function (toRemove) {
  26820. var index = this.skeletons.indexOf(toRemove);
  26821. if (index !== -1) {
  26822. // Remove from the scene if found
  26823. this.skeletons.splice(index, 1);
  26824. }
  26825. return index;
  26826. };
  26827. /**
  26828. * Remove a morph target for the list of scene's morph targets
  26829. * @param toRemove defines the morph target to remove
  26830. * @returns the index where the morph target was in the morph target list
  26831. */
  26832. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26833. var index = this.morphTargetManagers.indexOf(toRemove);
  26834. if (index !== -1) {
  26835. // Remove from the scene if found
  26836. this.morphTargetManagers.splice(index, 1);
  26837. }
  26838. return index;
  26839. };
  26840. /**
  26841. * Remove a light for the list of scene's lights
  26842. * @param toRemove defines the light to remove
  26843. * @returns the index where the light was in the light list
  26844. */
  26845. Scene.prototype.removeLight = function (toRemove) {
  26846. var index = this.lights.indexOf(toRemove);
  26847. if (index !== -1) {
  26848. // Remove from meshes
  26849. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26850. var mesh = _a[_i];
  26851. mesh._removeLightSource(toRemove);
  26852. }
  26853. // Remove from the scene if mesh found
  26854. this.lights.splice(index, 1);
  26855. this.sortLightsByPriority();
  26856. }
  26857. this.onLightRemovedObservable.notifyObservers(toRemove);
  26858. return index;
  26859. };
  26860. /**
  26861. * Remove a camera for the list of scene's cameras
  26862. * @param toRemove defines the camera to remove
  26863. * @returns the index where the camera was in the camera list
  26864. */
  26865. Scene.prototype.removeCamera = function (toRemove) {
  26866. var index = this.cameras.indexOf(toRemove);
  26867. if (index !== -1) {
  26868. // Remove from the scene if mesh found
  26869. this.cameras.splice(index, 1);
  26870. }
  26871. // Remove from activeCameras
  26872. var index2 = this.activeCameras.indexOf(toRemove);
  26873. if (index2 !== -1) {
  26874. // Remove from the scene if mesh found
  26875. this.activeCameras.splice(index2, 1);
  26876. }
  26877. // Reset the activeCamera
  26878. if (this.activeCamera === toRemove) {
  26879. if (this.cameras.length > 0) {
  26880. this.activeCamera = this.cameras[0];
  26881. }
  26882. else {
  26883. this.activeCamera = null;
  26884. }
  26885. }
  26886. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26887. return index;
  26888. };
  26889. /**
  26890. * Remove a particle system for the list of scene's particle systems
  26891. * @param toRemove defines the particle system to remove
  26892. * @returns the index where the particle system was in the particle system list
  26893. */
  26894. Scene.prototype.removeParticleSystem = function (toRemove) {
  26895. var index = this.particleSystems.indexOf(toRemove);
  26896. if (index !== -1) {
  26897. this.particleSystems.splice(index, 1);
  26898. }
  26899. return index;
  26900. };
  26901. /**
  26902. * Remove a animation for the list of scene's animations
  26903. * @param toRemove defines the animation to remove
  26904. * @returns the index where the animation was in the animation list
  26905. */
  26906. Scene.prototype.removeAnimation = function (toRemove) {
  26907. var index = this.animations.indexOf(toRemove);
  26908. if (index !== -1) {
  26909. this.animations.splice(index, 1);
  26910. }
  26911. return index;
  26912. };
  26913. /**
  26914. * Removes the given animation group from this scene.
  26915. * @param toRemove The animation group to remove
  26916. * @returns The index of the removed animation group
  26917. */
  26918. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26919. var index = this.animationGroups.indexOf(toRemove);
  26920. if (index !== -1) {
  26921. this.animationGroups.splice(index, 1);
  26922. }
  26923. return index;
  26924. };
  26925. /**
  26926. * Removes the given multi-material from this scene.
  26927. * @param toRemove The multi-material to remove
  26928. * @returns The index of the removed multi-material
  26929. */
  26930. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26931. var index = this.multiMaterials.indexOf(toRemove);
  26932. if (index !== -1) {
  26933. this.multiMaterials.splice(index, 1);
  26934. }
  26935. return index;
  26936. };
  26937. /**
  26938. * Removes the given material from this scene.
  26939. * @param toRemove The material to remove
  26940. * @returns The index of the removed material
  26941. */
  26942. Scene.prototype.removeMaterial = function (toRemove) {
  26943. var index = this.materials.indexOf(toRemove);
  26944. if (index !== -1) {
  26945. this.materials.splice(index, 1);
  26946. }
  26947. return index;
  26948. };
  26949. /**
  26950. * Removes the given action manager from this scene.
  26951. * @param toRemove The action manager to remove
  26952. * @returns The index of the removed action manager
  26953. */
  26954. Scene.prototype.removeActionManager = function (toRemove) {
  26955. var index = this.actionManagers.indexOf(toRemove);
  26956. if (index !== -1) {
  26957. this.actionManagers.splice(index, 1);
  26958. }
  26959. return index;
  26960. };
  26961. /**
  26962. * Removes the given texture from this scene.
  26963. * @param toRemove The texture to remove
  26964. * @returns The index of the removed texture
  26965. */
  26966. Scene.prototype.removeTexture = function (toRemove) {
  26967. var index = this.textures.indexOf(toRemove);
  26968. if (index !== -1) {
  26969. this.textures.splice(index, 1);
  26970. }
  26971. return index;
  26972. };
  26973. /**
  26974. * Adds the given light to this scene
  26975. * @param newLight The light to add
  26976. */
  26977. Scene.prototype.addLight = function (newLight) {
  26978. this.lights.push(newLight);
  26979. this.sortLightsByPriority();
  26980. // Add light to all meshes (To support if the light is removed and then readded)
  26981. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26982. var mesh = _a[_i];
  26983. if (mesh._lightSources.indexOf(newLight) === -1) {
  26984. mesh._lightSources.push(newLight);
  26985. mesh._resyncLightSources();
  26986. }
  26987. }
  26988. this.onNewLightAddedObservable.notifyObservers(newLight);
  26989. };
  26990. /**
  26991. * Sorts the list list based on light priorities
  26992. */
  26993. Scene.prototype.sortLightsByPriority = function () {
  26994. if (this.requireLightSorting) {
  26995. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26996. }
  26997. };
  26998. /**
  26999. * Adds the given camera to this scene
  27000. * @param newCamera The camera to add
  27001. */
  27002. Scene.prototype.addCamera = function (newCamera) {
  27003. this.cameras.push(newCamera);
  27004. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27005. };
  27006. /**
  27007. * Adds the given skeleton to this scene
  27008. * @param newSkeleton The skeleton to add
  27009. */
  27010. Scene.prototype.addSkeleton = function (newSkeleton) {
  27011. this.skeletons.push(newSkeleton);
  27012. };
  27013. /**
  27014. * Adds the given particle system to this scene
  27015. * @param newParticleSystem The particle system to add
  27016. */
  27017. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27018. this.particleSystems.push(newParticleSystem);
  27019. };
  27020. /**
  27021. * Adds the given animation to this scene
  27022. * @param newAnimation The animation to add
  27023. */
  27024. Scene.prototype.addAnimation = function (newAnimation) {
  27025. this.animations.push(newAnimation);
  27026. };
  27027. /**
  27028. * Adds the given animation group to this scene.
  27029. * @param newAnimationGroup The animation group to add
  27030. */
  27031. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27032. this.animationGroups.push(newAnimationGroup);
  27033. };
  27034. /**
  27035. * Adds the given multi-material to this scene
  27036. * @param newMultiMaterial The multi-material to add
  27037. */
  27038. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27039. this.multiMaterials.push(newMultiMaterial);
  27040. };
  27041. /**
  27042. * Adds the given material to this scene
  27043. * @param newMaterial The material to add
  27044. */
  27045. Scene.prototype.addMaterial = function (newMaterial) {
  27046. this.materials.push(newMaterial);
  27047. };
  27048. /**
  27049. * Adds the given morph target to this scene
  27050. * @param newMorphTargetManager The morph target to add
  27051. */
  27052. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27053. this.morphTargetManagers.push(newMorphTargetManager);
  27054. };
  27055. /**
  27056. * Adds the given geometry to this scene
  27057. * @param newGeometry The geometry to add
  27058. */
  27059. Scene.prototype.addGeometry = function (newGeometry) {
  27060. this.geometries.push(newGeometry);
  27061. };
  27062. /**
  27063. * Adds the given action manager to this scene
  27064. * @param newActionManager The action manager to add
  27065. */
  27066. Scene.prototype.addActionManager = function (newActionManager) {
  27067. this.actionManagers.push(newActionManager);
  27068. };
  27069. /**
  27070. * Adds the given texture to this scene.
  27071. * @param newTexture The texture to add
  27072. */
  27073. Scene.prototype.addTexture = function (newTexture) {
  27074. this.textures.push(newTexture);
  27075. };
  27076. /**
  27077. * Switch active camera
  27078. * @param newCamera defines the new active camera
  27079. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27080. */
  27081. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27082. if (attachControl === void 0) { attachControl = true; }
  27083. var canvas = this._engine.getRenderingCanvas();
  27084. if (!canvas) {
  27085. return;
  27086. }
  27087. if (this.activeCamera) {
  27088. this.activeCamera.detachControl(canvas);
  27089. }
  27090. this.activeCamera = newCamera;
  27091. if (attachControl) {
  27092. newCamera.attachControl(canvas);
  27093. }
  27094. };
  27095. /**
  27096. * sets the active camera of the scene using its ID
  27097. * @param id defines the camera's ID
  27098. * @return the new active camera or null if none found.
  27099. */
  27100. Scene.prototype.setActiveCameraByID = function (id) {
  27101. var camera = this.getCameraByID(id);
  27102. if (camera) {
  27103. this.activeCamera = camera;
  27104. return camera;
  27105. }
  27106. return null;
  27107. };
  27108. /**
  27109. * sets the active camera of the scene using its name
  27110. * @param name defines the camera's name
  27111. * @returns the new active camera or null if none found.
  27112. */
  27113. Scene.prototype.setActiveCameraByName = function (name) {
  27114. var camera = this.getCameraByName(name);
  27115. if (camera) {
  27116. this.activeCamera = camera;
  27117. return camera;
  27118. }
  27119. return null;
  27120. };
  27121. /**
  27122. * get an animation group using its name
  27123. * @param name defines the material's name
  27124. * @return the animation group or null if none found.
  27125. */
  27126. Scene.prototype.getAnimationGroupByName = function (name) {
  27127. for (var index = 0; index < this.animationGroups.length; index++) {
  27128. if (this.animationGroups[index].name === name) {
  27129. return this.animationGroups[index];
  27130. }
  27131. }
  27132. return null;
  27133. };
  27134. /**
  27135. * get a material using its id
  27136. * @param id defines the material's ID
  27137. * @return the material or null if none found.
  27138. */
  27139. Scene.prototype.getMaterialByID = function (id) {
  27140. for (var index = 0; index < this.materials.length; index++) {
  27141. if (this.materials[index].id === id) {
  27142. return this.materials[index];
  27143. }
  27144. }
  27145. return null;
  27146. };
  27147. /**
  27148. * Gets a material using its name
  27149. * @param name defines the material's name
  27150. * @return the material or null if none found.
  27151. */
  27152. Scene.prototype.getMaterialByName = function (name) {
  27153. for (var index = 0; index < this.materials.length; index++) {
  27154. if (this.materials[index].name === name) {
  27155. return this.materials[index];
  27156. }
  27157. }
  27158. return null;
  27159. };
  27160. /**
  27161. * Gets a camera using its id
  27162. * @param id defines the id to look for
  27163. * @returns the camera or null if not found
  27164. */
  27165. Scene.prototype.getCameraByID = function (id) {
  27166. for (var index = 0; index < this.cameras.length; index++) {
  27167. if (this.cameras[index].id === id) {
  27168. return this.cameras[index];
  27169. }
  27170. }
  27171. return null;
  27172. };
  27173. /**
  27174. * Gets a camera using its unique id
  27175. * @param uniqueId defines the unique id to look for
  27176. * @returns the camera or null if not found
  27177. */
  27178. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27179. for (var index = 0; index < this.cameras.length; index++) {
  27180. if (this.cameras[index].uniqueId === uniqueId) {
  27181. return this.cameras[index];
  27182. }
  27183. }
  27184. return null;
  27185. };
  27186. /**
  27187. * Gets a camera using its name
  27188. * @param name defines the camera's name
  27189. * @return the camera or null if none found.
  27190. */
  27191. Scene.prototype.getCameraByName = function (name) {
  27192. for (var index = 0; index < this.cameras.length; index++) {
  27193. if (this.cameras[index].name === name) {
  27194. return this.cameras[index];
  27195. }
  27196. }
  27197. return null;
  27198. };
  27199. /**
  27200. * Gets a bone using its id
  27201. * @param id defines the bone's id
  27202. * @return the bone or null if not found
  27203. */
  27204. Scene.prototype.getBoneByID = function (id) {
  27205. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27206. var skeleton = this.skeletons[skeletonIndex];
  27207. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27208. if (skeleton.bones[boneIndex].id === id) {
  27209. return skeleton.bones[boneIndex];
  27210. }
  27211. }
  27212. }
  27213. return null;
  27214. };
  27215. /**
  27216. * Gets a bone using its id
  27217. * @param name defines the bone's name
  27218. * @return the bone or null if not found
  27219. */
  27220. Scene.prototype.getBoneByName = function (name) {
  27221. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27222. var skeleton = this.skeletons[skeletonIndex];
  27223. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27224. if (skeleton.bones[boneIndex].name === name) {
  27225. return skeleton.bones[boneIndex];
  27226. }
  27227. }
  27228. }
  27229. return null;
  27230. };
  27231. /**
  27232. * Gets a light node using its name
  27233. * @param name defines the the light's name
  27234. * @return the light or null if none found.
  27235. */
  27236. Scene.prototype.getLightByName = function (name) {
  27237. for (var index = 0; index < this.lights.length; index++) {
  27238. if (this.lights[index].name === name) {
  27239. return this.lights[index];
  27240. }
  27241. }
  27242. return null;
  27243. };
  27244. /**
  27245. * Gets a light node using its id
  27246. * @param id defines the light's id
  27247. * @return the light or null if none found.
  27248. */
  27249. Scene.prototype.getLightByID = function (id) {
  27250. for (var index = 0; index < this.lights.length; index++) {
  27251. if (this.lights[index].id === id) {
  27252. return this.lights[index];
  27253. }
  27254. }
  27255. return null;
  27256. };
  27257. /**
  27258. * Gets a light node using its scene-generated unique ID
  27259. * @param uniqueId defines the light's unique id
  27260. * @return the light or null if none found.
  27261. */
  27262. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27263. for (var index = 0; index < this.lights.length; index++) {
  27264. if (this.lights[index].uniqueId === uniqueId) {
  27265. return this.lights[index];
  27266. }
  27267. }
  27268. return null;
  27269. };
  27270. /**
  27271. * Gets a particle system by id
  27272. * @param id defines the particle system id
  27273. * @return the corresponding system or null if none found
  27274. */
  27275. Scene.prototype.getParticleSystemByID = function (id) {
  27276. for (var index = 0; index < this.particleSystems.length; index++) {
  27277. if (this.particleSystems[index].id === id) {
  27278. return this.particleSystems[index];
  27279. }
  27280. }
  27281. return null;
  27282. };
  27283. /**
  27284. * Gets a geometry using its ID
  27285. * @param id defines the geometry's id
  27286. * @return the geometry or null if none found.
  27287. */
  27288. Scene.prototype.getGeometryByID = function (id) {
  27289. for (var index = 0; index < this.geometries.length; index++) {
  27290. if (this.geometries[index].id === id) {
  27291. return this.geometries[index];
  27292. }
  27293. }
  27294. return null;
  27295. };
  27296. /**
  27297. * Add a new geometry to this scene
  27298. * @param geometry defines the geometry to be added to the scene.
  27299. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27300. * @return a boolean defining if the geometry was added or not
  27301. */
  27302. Scene.prototype.pushGeometry = function (geometry, force) {
  27303. if (!force && this.getGeometryByID(geometry.id)) {
  27304. return false;
  27305. }
  27306. this.geometries.push(geometry);
  27307. //notify the collision coordinator
  27308. if (this.collisionCoordinator) {
  27309. this.collisionCoordinator.onGeometryAdded(geometry);
  27310. }
  27311. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27312. return true;
  27313. };
  27314. /**
  27315. * Removes an existing geometry
  27316. * @param geometry defines the geometry to be removed from the scene
  27317. * @return a boolean defining if the geometry was removed or not
  27318. */
  27319. Scene.prototype.removeGeometry = function (geometry) {
  27320. var index = this.geometries.indexOf(geometry);
  27321. if (index > -1) {
  27322. this.geometries.splice(index, 1);
  27323. //notify the collision coordinator
  27324. if (this.collisionCoordinator) {
  27325. this.collisionCoordinator.onGeometryDeleted(geometry);
  27326. }
  27327. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27328. return true;
  27329. }
  27330. return false;
  27331. };
  27332. /**
  27333. * Gets the list of geometries attached to the scene
  27334. * @returns an array of Geometry
  27335. */
  27336. Scene.prototype.getGeometries = function () {
  27337. return this.geometries;
  27338. };
  27339. /**
  27340. * Gets the first added mesh found of a given ID
  27341. * @param id defines the id to search for
  27342. * @return the mesh found or null if not found at all
  27343. */
  27344. Scene.prototype.getMeshByID = function (id) {
  27345. for (var index = 0; index < this.meshes.length; index++) {
  27346. if (this.meshes[index].id === id) {
  27347. return this.meshes[index];
  27348. }
  27349. }
  27350. return null;
  27351. };
  27352. /**
  27353. * Gets a list of meshes using their id
  27354. * @param id defines the id to search for
  27355. * @returns a list of meshes
  27356. */
  27357. Scene.prototype.getMeshesByID = function (id) {
  27358. return this.meshes.filter(function (m) {
  27359. return m.id === id;
  27360. });
  27361. };
  27362. /**
  27363. * Gets the first added transform node found of a given ID
  27364. * @param id defines the id to search for
  27365. * @return the found transform node or null if not found at all.
  27366. */
  27367. Scene.prototype.getTransformNodeByID = function (id) {
  27368. for (var index = 0; index < this.transformNodes.length; index++) {
  27369. if (this.transformNodes[index].id === id) {
  27370. return this.transformNodes[index];
  27371. }
  27372. }
  27373. return null;
  27374. };
  27375. /**
  27376. * Gets a list of transform nodes using their id
  27377. * @param id defines the id to search for
  27378. * @returns a list of transform nodes
  27379. */
  27380. Scene.prototype.getTransformNodesByID = function (id) {
  27381. return this.transformNodes.filter(function (m) {
  27382. return m.id === id;
  27383. });
  27384. };
  27385. /**
  27386. * Gets a mesh with its auto-generated unique id
  27387. * @param uniqueId defines the unique id to search for
  27388. * @return the found mesh or null if not found at all.
  27389. */
  27390. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27391. for (var index = 0; index < this.meshes.length; index++) {
  27392. if (this.meshes[index].uniqueId === uniqueId) {
  27393. return this.meshes[index];
  27394. }
  27395. }
  27396. return null;
  27397. };
  27398. /**
  27399. * Gets a the last added mesh using a given id
  27400. * @param id defines the id to search for
  27401. * @return the found mesh or null if not found at all.
  27402. */
  27403. Scene.prototype.getLastMeshByID = function (id) {
  27404. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27405. if (this.meshes[index].id === id) {
  27406. return this.meshes[index];
  27407. }
  27408. }
  27409. return null;
  27410. };
  27411. /**
  27412. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27413. * @param id defines the id to search for
  27414. * @return the found node or null if not found at all
  27415. */
  27416. Scene.prototype.getLastEntryByID = function (id) {
  27417. var index;
  27418. for (index = this.meshes.length - 1; index >= 0; index--) {
  27419. if (this.meshes[index].id === id) {
  27420. return this.meshes[index];
  27421. }
  27422. }
  27423. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27424. if (this.transformNodes[index].id === id) {
  27425. return this.transformNodes[index];
  27426. }
  27427. }
  27428. for (index = this.cameras.length - 1; index >= 0; index--) {
  27429. if (this.cameras[index].id === id) {
  27430. return this.cameras[index];
  27431. }
  27432. }
  27433. for (index = this.lights.length - 1; index >= 0; index--) {
  27434. if (this.lights[index].id === id) {
  27435. return this.lights[index];
  27436. }
  27437. }
  27438. return null;
  27439. };
  27440. /**
  27441. * Gets a node (Mesh, Camera, Light) using a given id
  27442. * @param id defines the id to search for
  27443. * @return the found node or null if not found at all
  27444. */
  27445. Scene.prototype.getNodeByID = function (id) {
  27446. var mesh = this.getMeshByID(id);
  27447. if (mesh) {
  27448. return mesh;
  27449. }
  27450. var light = this.getLightByID(id);
  27451. if (light) {
  27452. return light;
  27453. }
  27454. var camera = this.getCameraByID(id);
  27455. if (camera) {
  27456. return camera;
  27457. }
  27458. var bone = this.getBoneByID(id);
  27459. return bone;
  27460. };
  27461. /**
  27462. * Gets a node (Mesh, Camera, Light) using a given name
  27463. * @param name defines the name to search for
  27464. * @return the found node or null if not found at all.
  27465. */
  27466. Scene.prototype.getNodeByName = function (name) {
  27467. var mesh = this.getMeshByName(name);
  27468. if (mesh) {
  27469. return mesh;
  27470. }
  27471. var light = this.getLightByName(name);
  27472. if (light) {
  27473. return light;
  27474. }
  27475. var camera = this.getCameraByName(name);
  27476. if (camera) {
  27477. return camera;
  27478. }
  27479. var bone = this.getBoneByName(name);
  27480. return bone;
  27481. };
  27482. /**
  27483. * Gets a mesh using a given name
  27484. * @param name defines the name to search for
  27485. * @return the found mesh or null if not found at all.
  27486. */
  27487. Scene.prototype.getMeshByName = function (name) {
  27488. for (var index = 0; index < this.meshes.length; index++) {
  27489. if (this.meshes[index].name === name) {
  27490. return this.meshes[index];
  27491. }
  27492. }
  27493. return null;
  27494. };
  27495. /**
  27496. * Gets a transform node using a given name
  27497. * @param name defines the name to search for
  27498. * @return the found transform node or null if not found at all.
  27499. */
  27500. Scene.prototype.getTransformNodeByName = function (name) {
  27501. for (var index = 0; index < this.transformNodes.length; index++) {
  27502. if (this.transformNodes[index].name === name) {
  27503. return this.transformNodes[index];
  27504. }
  27505. }
  27506. return null;
  27507. };
  27508. /**
  27509. * Gets a sound using a given name
  27510. * @param name defines the name to search for
  27511. * @return the found sound or null if not found at all.
  27512. */
  27513. Scene.prototype.getSoundByName = function (name) {
  27514. var index;
  27515. if (BABYLON.AudioEngine) {
  27516. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27517. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27518. return this.mainSoundTrack.soundCollection[index];
  27519. }
  27520. }
  27521. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27522. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27523. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27524. return this.soundTracks[sdIndex].soundCollection[index];
  27525. }
  27526. }
  27527. }
  27528. }
  27529. return null;
  27530. };
  27531. /**
  27532. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27533. * @param id defines the id to search for
  27534. * @return the found skeleton or null if not found at all.
  27535. */
  27536. Scene.prototype.getLastSkeletonByID = function (id) {
  27537. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27538. if (this.skeletons[index].id === id) {
  27539. return this.skeletons[index];
  27540. }
  27541. }
  27542. return null;
  27543. };
  27544. /**
  27545. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27546. * @param id defines the id to search for
  27547. * @return the found skeleton or null if not found at all.
  27548. */
  27549. Scene.prototype.getSkeletonById = function (id) {
  27550. for (var index = 0; index < this.skeletons.length; index++) {
  27551. if (this.skeletons[index].id === id) {
  27552. return this.skeletons[index];
  27553. }
  27554. }
  27555. return null;
  27556. };
  27557. /**
  27558. * Gets a skeleton using a given name
  27559. * @param name defines the name to search for
  27560. * @return the found skeleton or null if not found at all.
  27561. */
  27562. Scene.prototype.getSkeletonByName = function (name) {
  27563. for (var index = 0; index < this.skeletons.length; index++) {
  27564. if (this.skeletons[index].name === name) {
  27565. return this.skeletons[index];
  27566. }
  27567. }
  27568. return null;
  27569. };
  27570. /**
  27571. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27572. * @param id defines the id to search for
  27573. * @return the found morph target manager or null if not found at all.
  27574. */
  27575. Scene.prototype.getMorphTargetManagerById = function (id) {
  27576. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27577. if (this.morphTargetManagers[index].uniqueId === id) {
  27578. return this.morphTargetManagers[index];
  27579. }
  27580. }
  27581. return null;
  27582. };
  27583. /**
  27584. * Gets a boolean indicating if the given mesh is active
  27585. * @param mesh defines the mesh to look for
  27586. * @returns true if the mesh is in the active list
  27587. */
  27588. Scene.prototype.isActiveMesh = function (mesh) {
  27589. return (this._activeMeshes.indexOf(mesh) !== -1);
  27590. };
  27591. Object.defineProperty(Scene.prototype, "uid", {
  27592. /**
  27593. * Return a unique id as a string which can serve as an identifier for the scene
  27594. */
  27595. get: function () {
  27596. if (!this._uid) {
  27597. this._uid = BABYLON.Tools.RandomId();
  27598. }
  27599. return this._uid;
  27600. },
  27601. enumerable: true,
  27602. configurable: true
  27603. });
  27604. /**
  27605. * Add an externaly attached data from its key.
  27606. * This method call will fail and return false, if such key already exists.
  27607. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27608. * @param key the unique key that identifies the data
  27609. * @param data the data object to associate to the key for this Engine instance
  27610. * @return true if no such key were already present and the data was added successfully, false otherwise
  27611. */
  27612. Scene.prototype.addExternalData = function (key, data) {
  27613. if (!this._externalData) {
  27614. this._externalData = new BABYLON.StringDictionary();
  27615. }
  27616. return this._externalData.add(key, data);
  27617. };
  27618. /**
  27619. * Get an externaly attached data from its key
  27620. * @param key the unique key that identifies the data
  27621. * @return the associated data, if present (can be null), or undefined if not present
  27622. */
  27623. Scene.prototype.getExternalData = function (key) {
  27624. if (!this._externalData) {
  27625. return null;
  27626. }
  27627. return this._externalData.get(key);
  27628. };
  27629. /**
  27630. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27631. * @param key the unique key that identifies the data
  27632. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27633. * @return the associated data, can be null if the factory returned null.
  27634. */
  27635. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27636. if (!this._externalData) {
  27637. this._externalData = new BABYLON.StringDictionary();
  27638. }
  27639. return this._externalData.getOrAddWithFactory(key, factory);
  27640. };
  27641. /**
  27642. * Remove an externaly attached data from the Engine instance
  27643. * @param key the unique key that identifies the data
  27644. * @return true if the data was successfully removed, false if it doesn't exist
  27645. */
  27646. Scene.prototype.removeExternalData = function (key) {
  27647. return this._externalData.remove(key);
  27648. };
  27649. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27650. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27651. if (mesh.showSubMeshesBoundingBox) {
  27652. var boundingInfo = subMesh.getBoundingInfo();
  27653. if (boundingInfo !== null && boundingInfo !== undefined) {
  27654. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27655. }
  27656. }
  27657. var material = subMesh.getMaterial();
  27658. if (material !== null && material !== undefined) {
  27659. // Render targets
  27660. if (material.getRenderTargetTextures !== undefined) {
  27661. if (this._processedMaterials.indexOf(material) === -1) {
  27662. this._processedMaterials.push(material);
  27663. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27664. }
  27665. }
  27666. // Dispatch
  27667. this._activeIndices.addCount(subMesh.indexCount, false);
  27668. this._renderingManager.dispatch(subMesh, mesh, material);
  27669. }
  27670. }
  27671. };
  27672. /**
  27673. * Clear the processed materials smart array preventing retention point in material dispose.
  27674. */
  27675. Scene.prototype.freeProcessedMaterials = function () {
  27676. this._processedMaterials.dispose();
  27677. };
  27678. /**
  27679. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27680. */
  27681. Scene.prototype.freeActiveMeshes = function () {
  27682. this._activeMeshes.dispose();
  27683. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27684. this.activeCamera._activeMeshes.dispose();
  27685. }
  27686. if (this.activeCameras) {
  27687. for (var i = 0; i < this.activeCameras.length; i++) {
  27688. var activeCamera = this.activeCameras[i];
  27689. if (activeCamera && activeCamera._activeMeshes) {
  27690. activeCamera._activeMeshes.dispose();
  27691. }
  27692. }
  27693. }
  27694. };
  27695. /**
  27696. * Clear the info related to rendering groups preventing retention points during dispose.
  27697. */
  27698. Scene.prototype.freeRenderingGroups = function () {
  27699. if (this._renderingManager) {
  27700. this._renderingManager.freeRenderingGroups();
  27701. }
  27702. if (this.textures) {
  27703. for (var i = 0; i < this.textures.length; i++) {
  27704. var texture = this.textures[i];
  27705. if (texture && texture.renderList) {
  27706. texture.freeRenderingGroups();
  27707. }
  27708. }
  27709. }
  27710. };
  27711. /** @hidden */
  27712. Scene.prototype._isInIntermediateRendering = function () {
  27713. return this._intermediateRendering;
  27714. };
  27715. /**
  27716. * Defines the current active mesh candidate provider
  27717. * @param provider defines the provider to use
  27718. */
  27719. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27720. this._activeMeshCandidateProvider = provider;
  27721. };
  27722. /**
  27723. * Gets the current active mesh candidate provider
  27724. * @returns the current active mesh candidate provider
  27725. */
  27726. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27727. return this._activeMeshCandidateProvider;
  27728. };
  27729. /**
  27730. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27731. * @returns the current scene
  27732. */
  27733. Scene.prototype.freezeActiveMeshes = function () {
  27734. if (!this.activeCamera) {
  27735. return this;
  27736. }
  27737. if (!this._frustumPlanes) {
  27738. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27739. }
  27740. this._evaluateActiveMeshes();
  27741. this._activeMeshesFrozen = true;
  27742. return this;
  27743. };
  27744. /**
  27745. * Use this function to restart evaluating active meshes on every frame
  27746. * @returns the current scene
  27747. */
  27748. Scene.prototype.unfreezeActiveMeshes = function () {
  27749. this._activeMeshesFrozen = false;
  27750. return this;
  27751. };
  27752. Scene.prototype._evaluateActiveMeshes = function () {
  27753. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27754. return;
  27755. }
  27756. if (!this.activeCamera) {
  27757. return;
  27758. }
  27759. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27760. this.activeCamera._activeMeshes.reset();
  27761. this._activeMeshes.reset();
  27762. this._renderingManager.reset();
  27763. this._processedMaterials.reset();
  27764. this._activeParticleSystems.reset();
  27765. this._activeSkeletons.reset();
  27766. this._softwareSkinnedMeshes.reset();
  27767. if (this._boundingBoxRenderer) {
  27768. this._boundingBoxRenderer.reset();
  27769. }
  27770. // Meshes
  27771. var meshes;
  27772. var len;
  27773. var checkIsEnabled = true;
  27774. // Determine mesh candidates
  27775. if (this._activeMeshCandidateProvider !== undefined) {
  27776. // Use _activeMeshCandidateProvider
  27777. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27778. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27779. if (meshes !== undefined) {
  27780. len = meshes.length;
  27781. }
  27782. else {
  27783. len = 0;
  27784. }
  27785. }
  27786. else if (this._selectionOctree !== undefined) {
  27787. // Octree
  27788. var selection = this._selectionOctree.select(this._frustumPlanes);
  27789. meshes = selection.data;
  27790. len = selection.length;
  27791. }
  27792. else {
  27793. // Full scene traversal
  27794. len = this.meshes.length;
  27795. meshes = this.meshes;
  27796. }
  27797. // Check each mesh
  27798. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27799. mesh = meshes[meshIndex];
  27800. if (mesh.isBlocked) {
  27801. continue;
  27802. }
  27803. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27804. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27805. continue;
  27806. }
  27807. mesh.computeWorldMatrix();
  27808. // Intersections
  27809. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27810. this._meshesForIntersections.pushNoDuplicate(mesh);
  27811. }
  27812. // Switch to current LOD
  27813. meshLOD = mesh.getLOD(this.activeCamera);
  27814. if (meshLOD === undefined || meshLOD === null) {
  27815. continue;
  27816. }
  27817. mesh._preActivate();
  27818. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27819. this._activeMeshes.push(mesh);
  27820. this.activeCamera._activeMeshes.push(mesh);
  27821. mesh._activate(this._renderId);
  27822. if (meshLOD !== mesh) {
  27823. meshLOD._activate(this._renderId);
  27824. }
  27825. this._activeMesh(mesh, meshLOD);
  27826. }
  27827. }
  27828. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27829. // Particle systems
  27830. if (this.particlesEnabled) {
  27831. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27832. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27833. var particleSystem = this.particleSystems[particleIndex];
  27834. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27835. continue;
  27836. }
  27837. var emitter = particleSystem.emitter;
  27838. if (!emitter.position || emitter.isEnabled()) {
  27839. this._activeParticleSystems.push(particleSystem);
  27840. particleSystem.animate();
  27841. this._renderingManager.dispatchParticles(particleSystem);
  27842. }
  27843. }
  27844. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27845. }
  27846. };
  27847. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27848. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27849. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27850. mesh.skeleton.prepare();
  27851. }
  27852. if (!mesh.computeBonesUsingShaders) {
  27853. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27854. }
  27855. }
  27856. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27857. var boundingInfo = sourceMesh.getBoundingInfo();
  27858. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27859. }
  27860. if (mesh !== undefined && mesh !== null
  27861. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27862. // Submeshes Octrees
  27863. var len;
  27864. var subMeshes;
  27865. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27866. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27867. len = intersections.length;
  27868. subMeshes = intersections.data;
  27869. }
  27870. else {
  27871. subMeshes = mesh.subMeshes;
  27872. len = subMeshes.length;
  27873. }
  27874. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27875. subMesh = subMeshes[subIndex];
  27876. this._evaluateSubMesh(subMesh, mesh);
  27877. }
  27878. }
  27879. };
  27880. /**
  27881. * Update the transform matrix to update from the current active camera
  27882. * @param force defines a boolean used to force the update even if cache is up to date
  27883. */
  27884. Scene.prototype.updateTransformMatrix = function (force) {
  27885. if (!this.activeCamera) {
  27886. return;
  27887. }
  27888. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27889. };
  27890. /**
  27891. * 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)
  27892. * @param alternateCamera defines the camera to use
  27893. */
  27894. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27895. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27896. };
  27897. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27898. if (camera && camera._skipRendering) {
  27899. return;
  27900. }
  27901. var engine = this._engine;
  27902. this.activeCamera = camera;
  27903. if (!this.activeCamera)
  27904. throw new Error("Active camera not set");
  27905. // Viewport
  27906. engine.setViewport(this.activeCamera.viewport);
  27907. // Camera
  27908. this.resetCachedMaterial();
  27909. this._renderId++;
  27910. this.updateTransformMatrix();
  27911. if (camera._alternateCamera) {
  27912. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27913. this._alternateRendering = true;
  27914. }
  27915. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27916. // Meshes
  27917. this._evaluateActiveMeshes();
  27918. // Software skinning
  27919. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27920. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27921. mesh.applySkeleton(mesh.skeleton);
  27922. }
  27923. // Render targets
  27924. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27925. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27926. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27927. }
  27928. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27929. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27930. }
  27931. if (this.renderTargetsEnabled) {
  27932. this._intermediateRendering = true;
  27933. if (this._renderTargets.length > 0) {
  27934. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27935. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27936. var renderTarget = this._renderTargets.data[renderIndex];
  27937. if (renderTarget._shouldRender()) {
  27938. this._renderId++;
  27939. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27940. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27941. }
  27942. }
  27943. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27944. this._renderId++;
  27945. }
  27946. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27947. var step = _a[_i];
  27948. step.action(this.activeCamera);
  27949. }
  27950. this._intermediateRendering = false;
  27951. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27952. }
  27953. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27954. // Prepare Frame
  27955. if (this.postProcessManager) {
  27956. this.postProcessManager._prepareFrame();
  27957. }
  27958. // Before Camera Draw
  27959. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27960. var step = _c[_b];
  27961. step.action(this.activeCamera);
  27962. }
  27963. // Render
  27964. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27965. this._renderingManager.render(null, null, true, true);
  27966. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27967. // After Camera Draw
  27968. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27969. var step = _e[_d];
  27970. step.action(this.activeCamera);
  27971. }
  27972. // Bounding boxes
  27973. if (this._boundingBoxRenderer) {
  27974. this._boundingBoxRenderer.render();
  27975. }
  27976. // Finalize frame
  27977. if (this.postProcessManager) {
  27978. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27979. }
  27980. // Reset some special arrays
  27981. this._renderTargets.reset();
  27982. this._alternateRendering = false;
  27983. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27984. };
  27985. Scene.prototype._processSubCameras = function (camera) {
  27986. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27987. this._renderForCamera(camera);
  27988. return;
  27989. }
  27990. // rig cameras
  27991. for (var index = 0; index < camera._rigCameras.length; index++) {
  27992. this._renderForCamera(camera._rigCameras[index], camera);
  27993. }
  27994. this.activeCamera = camera;
  27995. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27996. };
  27997. Scene.prototype._checkIntersections = function () {
  27998. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27999. var sourceMesh = this._meshesForIntersections.data[index];
  28000. if (!sourceMesh.actionManager) {
  28001. continue;
  28002. }
  28003. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28004. var action = sourceMesh.actionManager.actions[actionIndex];
  28005. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28006. var parameters = action.getTriggerParameter();
  28007. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28008. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28009. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28010. if (areIntersecting && currentIntersectionInProgress === -1) {
  28011. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28012. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28013. sourceMesh._intersectionsInProgress.push(otherMesh);
  28014. }
  28015. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28016. sourceMesh._intersectionsInProgress.push(otherMesh);
  28017. }
  28018. }
  28019. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28020. //They intersected, and now they don't.
  28021. //is this trigger an exit trigger? execute an event.
  28022. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28023. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28024. }
  28025. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28026. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28027. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28028. return otherMesh === parameterMesh;
  28029. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28030. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28031. }
  28032. }
  28033. }
  28034. }
  28035. }
  28036. };
  28037. /**
  28038. * Render the scene
  28039. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28040. */
  28041. Scene.prototype.render = function (updateCameras) {
  28042. if (updateCameras === void 0) { updateCameras = true; }
  28043. if (this.isDisposed) {
  28044. return;
  28045. }
  28046. // Register components that have been associated lately to the scene.
  28047. this._registerTransientComponents();
  28048. this._activeParticles.fetchNewFrame();
  28049. this._totalVertices.fetchNewFrame();
  28050. this._activeIndices.fetchNewFrame();
  28051. this._activeBones.fetchNewFrame();
  28052. this._meshesForIntersections.reset();
  28053. this.resetCachedMaterial();
  28054. this.onBeforeAnimationsObservable.notifyObservers(this);
  28055. // Actions
  28056. if (this.actionManager) {
  28057. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28058. }
  28059. //Simplification Queue
  28060. if (this.simplificationQueue && !this.simplificationQueue.running) {
  28061. this.simplificationQueue.executeNext();
  28062. }
  28063. if (this._engine.isDeterministicLockStep()) {
  28064. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28065. var defaultFPS = (60.0 / 1000.0);
  28066. var defaultFrameTime = 1000 / 60; // frame time in MS
  28067. if (this._physicsEngine) {
  28068. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  28069. }
  28070. var stepsTaken = 0;
  28071. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28072. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28073. internalSteps = Math.min(internalSteps, maxSubSteps);
  28074. do {
  28075. this.onBeforeStepObservable.notifyObservers(this);
  28076. // Animations
  28077. this._animationRatio = defaultFrameTime * defaultFPS;
  28078. this._animate();
  28079. this.onAfterAnimationsObservable.notifyObservers(this);
  28080. // Physics
  28081. if (this._physicsEngine) {
  28082. this.onBeforePhysicsObservable.notifyObservers(this);
  28083. this._physicsEngine._step(defaultFrameTime / 1000);
  28084. this.onAfterPhysicsObservable.notifyObservers(this);
  28085. }
  28086. this.onAfterStepObservable.notifyObservers(this);
  28087. this._currentStepId++;
  28088. stepsTaken++;
  28089. deltaTime -= defaultFrameTime;
  28090. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28091. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28092. }
  28093. else {
  28094. // Animations
  28095. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28096. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28097. this._animate();
  28098. this.onAfterAnimationsObservable.notifyObservers(this);
  28099. // Physics
  28100. if (this._physicsEngine) {
  28101. this.onBeforePhysicsObservable.notifyObservers(this);
  28102. this._physicsEngine._step(deltaTime / 1000.0);
  28103. this.onAfterPhysicsObservable.notifyObservers(this);
  28104. }
  28105. }
  28106. // update gamepad manager
  28107. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  28108. this._gamepadManager._checkGamepadsStatus();
  28109. }
  28110. // Update Cameras
  28111. if (updateCameras) {
  28112. if (this.activeCameras.length > 0) {
  28113. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28114. var camera = this.activeCameras[cameraIndex];
  28115. camera.update();
  28116. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28117. // rig cameras
  28118. for (var index = 0; index < camera._rigCameras.length; index++) {
  28119. camera._rigCameras[index].update();
  28120. }
  28121. }
  28122. }
  28123. }
  28124. else if (this.activeCamera) {
  28125. this.activeCamera.update();
  28126. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28127. // rig cameras
  28128. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28129. this.activeCamera._rigCameras[index].update();
  28130. }
  28131. }
  28132. }
  28133. }
  28134. // Before render
  28135. this.onBeforeRenderObservable.notifyObservers(this);
  28136. // Customs render targets
  28137. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28138. var engine = this.getEngine();
  28139. var currentActiveCamera = this.activeCamera;
  28140. if (this.renderTargetsEnabled) {
  28141. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28142. this._intermediateRendering = true;
  28143. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28144. var renderTarget = this.customRenderTargets[customIndex];
  28145. if (renderTarget._shouldRender()) {
  28146. this._renderId++;
  28147. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28148. if (!this.activeCamera)
  28149. throw new Error("Active camera not set");
  28150. // Viewport
  28151. engine.setViewport(this.activeCamera.viewport);
  28152. // Camera
  28153. this.updateTransformMatrix();
  28154. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28155. }
  28156. }
  28157. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28158. this._intermediateRendering = false;
  28159. this._renderId++;
  28160. }
  28161. // Restore back buffer
  28162. if (this.customRenderTargets.length > 0) {
  28163. engine.restoreDefaultFramebuffer();
  28164. }
  28165. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28166. this.activeCamera = currentActiveCamera;
  28167. // Procedural textures
  28168. if (this.proceduralTexturesEnabled) {
  28169. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28170. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  28171. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  28172. if (proceduralTexture._shouldRender()) {
  28173. proceduralTexture.render();
  28174. }
  28175. }
  28176. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28177. }
  28178. // Clear
  28179. if (this.autoClearDepthAndStencil || this.autoClear) {
  28180. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28181. }
  28182. // Shadows
  28183. if (this.shadowsEnabled) {
  28184. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28185. var light = this.lights[lightIndex];
  28186. var shadowGenerator = light.getShadowGenerator();
  28187. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28188. var shadowMap = (shadowGenerator.getShadowMap());
  28189. if (this.textures.indexOf(shadowMap) !== -1) {
  28190. this._renderTargets.push(shadowMap);
  28191. }
  28192. }
  28193. }
  28194. }
  28195. // Depth renderer
  28196. for (var key in this._depthRenderer) {
  28197. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28198. }
  28199. // Geometry renderer
  28200. if (this._geometryBufferRenderer) {
  28201. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28202. }
  28203. // RenderPipeline
  28204. if (this._postProcessRenderPipelineManager) {
  28205. this._postProcessRenderPipelineManager.update();
  28206. }
  28207. // Multi-cameras?
  28208. if (this.activeCameras.length > 0) {
  28209. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28210. if (cameraIndex > 0) {
  28211. this._engine.clear(null, false, true, true);
  28212. }
  28213. this._processSubCameras(this.activeCameras[cameraIndex]);
  28214. }
  28215. }
  28216. else {
  28217. if (!this.activeCamera) {
  28218. throw new Error("No camera defined");
  28219. }
  28220. this._processSubCameras(this.activeCamera);
  28221. }
  28222. // Intersection checks
  28223. this._checkIntersections();
  28224. // Update the audio listener attached to the camera
  28225. if (BABYLON.AudioEngine) {
  28226. this._updateAudioParameters();
  28227. }
  28228. // After render
  28229. if (this.afterRender) {
  28230. this.afterRender();
  28231. }
  28232. this.onAfterRenderObservable.notifyObservers(this);
  28233. // Cleaning
  28234. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28235. var data = this._toBeDisposed.data[index];
  28236. if (data) {
  28237. data.dispose();
  28238. }
  28239. this._toBeDisposed[index] = null;
  28240. }
  28241. this._toBeDisposed.reset();
  28242. if (this.dumpNextRenderTargets) {
  28243. this.dumpNextRenderTargets = false;
  28244. }
  28245. this._activeBones.addCount(0, true);
  28246. this._activeIndices.addCount(0, true);
  28247. this._activeParticles.addCount(0, true);
  28248. };
  28249. Scene.prototype._updateAudioParameters = function () {
  28250. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28251. return;
  28252. }
  28253. var listeningCamera;
  28254. var audioEngine = BABYLON.Engine.audioEngine;
  28255. if (this.activeCameras.length > 0) {
  28256. listeningCamera = this.activeCameras[0];
  28257. }
  28258. else {
  28259. listeningCamera = this.activeCamera;
  28260. }
  28261. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28262. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28263. // for VR cameras
  28264. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28265. listeningCamera = listeningCamera.rigCameras[0];
  28266. }
  28267. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28268. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28269. cameraDirection.normalize();
  28270. // To avoid some errors on GearVR
  28271. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28272. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28273. }
  28274. var i;
  28275. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28276. var sound = this.mainSoundTrack.soundCollection[i];
  28277. if (sound.useCustomAttenuation) {
  28278. sound.updateDistanceFromListener();
  28279. }
  28280. }
  28281. for (i = 0; i < this.soundTracks.length; i++) {
  28282. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28283. sound = this.soundTracks[i].soundCollection[j];
  28284. if (sound.useCustomAttenuation) {
  28285. sound.updateDistanceFromListener();
  28286. }
  28287. }
  28288. }
  28289. }
  28290. };
  28291. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28292. // Audio
  28293. /**
  28294. * Gets or sets if audio support is enabled
  28295. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28296. */
  28297. get: function () {
  28298. return this._audioEnabled;
  28299. },
  28300. set: function (value) {
  28301. this._audioEnabled = value;
  28302. if (BABYLON.AudioEngine) {
  28303. if (this._audioEnabled) {
  28304. this._enableAudio();
  28305. }
  28306. else {
  28307. this._disableAudio();
  28308. }
  28309. }
  28310. },
  28311. enumerable: true,
  28312. configurable: true
  28313. });
  28314. Scene.prototype._disableAudio = function () {
  28315. var i;
  28316. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28317. this.mainSoundTrack.soundCollection[i].pause();
  28318. }
  28319. for (i = 0; i < this.soundTracks.length; i++) {
  28320. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28321. this.soundTracks[i].soundCollection[j].pause();
  28322. }
  28323. }
  28324. };
  28325. Scene.prototype._enableAudio = function () {
  28326. var i;
  28327. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28328. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28329. this.mainSoundTrack.soundCollection[i].play();
  28330. }
  28331. }
  28332. for (i = 0; i < this.soundTracks.length; i++) {
  28333. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28334. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28335. this.soundTracks[i].soundCollection[j].play();
  28336. }
  28337. }
  28338. }
  28339. };
  28340. Object.defineProperty(Scene.prototype, "headphone", {
  28341. /**
  28342. * Gets or sets if audio will be output to headphones
  28343. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28344. */
  28345. get: function () {
  28346. return this._headphone;
  28347. },
  28348. set: function (value) {
  28349. this._headphone = value;
  28350. if (BABYLON.AudioEngine) {
  28351. if (this._headphone) {
  28352. this._switchAudioModeForHeadphones();
  28353. }
  28354. else {
  28355. this._switchAudioModeForNormalSpeakers();
  28356. }
  28357. }
  28358. },
  28359. enumerable: true,
  28360. configurable: true
  28361. });
  28362. Scene.prototype._switchAudioModeForHeadphones = function () {
  28363. this.mainSoundTrack.switchPanningModelToHRTF();
  28364. for (var i = 0; i < this.soundTracks.length; i++) {
  28365. this.soundTracks[i].switchPanningModelToHRTF();
  28366. }
  28367. };
  28368. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28369. this.mainSoundTrack.switchPanningModelToEqualPower();
  28370. for (var i = 0; i < this.soundTracks.length; i++) {
  28371. this.soundTracks[i].switchPanningModelToEqualPower();
  28372. }
  28373. };
  28374. /**
  28375. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28376. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28377. * @returns the created depth renderer
  28378. */
  28379. Scene.prototype.enableDepthRenderer = function (camera) {
  28380. camera = camera || this.activeCamera;
  28381. if (!camera) {
  28382. throw "No camera available to enable depth renderer";
  28383. }
  28384. if (!this._depthRenderer[camera.id]) {
  28385. var textureType = 0;
  28386. if (this._engine.getCaps().textureHalfFloatRender) {
  28387. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28388. }
  28389. else if (this._engine.getCaps().textureFloatRender) {
  28390. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28391. }
  28392. else {
  28393. throw "Depth renderer does not support int texture type";
  28394. }
  28395. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28396. }
  28397. return this._depthRenderer[camera.id];
  28398. };
  28399. /**
  28400. * Disables a depth renderer for a given camera
  28401. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28402. */
  28403. Scene.prototype.disableDepthRenderer = function (camera) {
  28404. camera = camera || this.activeCamera;
  28405. if (!camera || !this._depthRenderer[camera.id]) {
  28406. return;
  28407. }
  28408. this._depthRenderer[camera.id].dispose();
  28409. delete this._depthRenderer[camera.id];
  28410. };
  28411. /**
  28412. * Enables a GeometryBufferRender and associates it with the scene
  28413. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28414. * @returns the GeometryBufferRenderer
  28415. */
  28416. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28417. if (ratio === void 0) { ratio = 1; }
  28418. if (this._geometryBufferRenderer) {
  28419. return this._geometryBufferRenderer;
  28420. }
  28421. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28422. if (!this._geometryBufferRenderer.isSupported) {
  28423. this._geometryBufferRenderer = null;
  28424. }
  28425. return this._geometryBufferRenderer;
  28426. };
  28427. /**
  28428. * Disables the GeometryBufferRender associated with the scene
  28429. */
  28430. Scene.prototype.disableGeometryBufferRenderer = function () {
  28431. if (!this._geometryBufferRenderer) {
  28432. return;
  28433. }
  28434. this._geometryBufferRenderer.dispose();
  28435. this._geometryBufferRenderer = null;
  28436. };
  28437. /**
  28438. * Freeze all materials
  28439. * A frozen material will not be updatable but should be faster to render
  28440. */
  28441. Scene.prototype.freezeMaterials = function () {
  28442. for (var i = 0; i < this.materials.length; i++) {
  28443. this.materials[i].freeze();
  28444. }
  28445. };
  28446. /**
  28447. * Unfreeze all materials
  28448. * A frozen material will not be updatable but should be faster to render
  28449. */
  28450. Scene.prototype.unfreezeMaterials = function () {
  28451. for (var i = 0; i < this.materials.length; i++) {
  28452. this.materials[i].unfreeze();
  28453. }
  28454. };
  28455. /**
  28456. * Releases all held ressources
  28457. */
  28458. Scene.prototype.dispose = function () {
  28459. this.beforeRender = null;
  28460. this.afterRender = null;
  28461. this.skeletons = [];
  28462. this.morphTargetManagers = [];
  28463. this._transientComponents = [];
  28464. this._isReadyForMeshStage.clear();
  28465. this._cameraDrawRenderTargetStage.clear();
  28466. this._beforeCameraDrawStage.clear();
  28467. this._afterCameraDrawStage.clear();
  28468. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28469. var component = _a[_i];
  28470. component.dispose();
  28471. }
  28472. this.importedMeshesFiles = new Array();
  28473. this.stopAllAnimations();
  28474. this.resetCachedMaterial();
  28475. for (var key in this._depthRenderer) {
  28476. this._depthRenderer[key].dispose();
  28477. }
  28478. if (this._gamepadManager) {
  28479. this._gamepadManager.dispose();
  28480. this._gamepadManager = null;
  28481. }
  28482. // Smart arrays
  28483. if (this.activeCamera) {
  28484. this.activeCamera._activeMeshes.dispose();
  28485. this.activeCamera = null;
  28486. }
  28487. this._activeMeshes.dispose();
  28488. this._renderingManager.dispose();
  28489. this._processedMaterials.dispose();
  28490. this._activeParticleSystems.dispose();
  28491. this._activeSkeletons.dispose();
  28492. this._softwareSkinnedMeshes.dispose();
  28493. this._renderTargets.dispose();
  28494. this._registeredForLateAnimationBindings.dispose();
  28495. if (this._boundingBoxRenderer) {
  28496. this._boundingBoxRenderer.dispose();
  28497. }
  28498. this._meshesForIntersections.dispose();
  28499. this._toBeDisposed.dispose();
  28500. // Abort active requests
  28501. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28502. var request = _c[_b];
  28503. request.abort();
  28504. }
  28505. // Debug layer
  28506. if (this._debugLayer) {
  28507. this._debugLayer.hide();
  28508. }
  28509. // Events
  28510. this.onDisposeObservable.notifyObservers(this);
  28511. this.onDisposeObservable.clear();
  28512. this.onBeforeRenderObservable.clear();
  28513. this.onAfterRenderObservable.clear();
  28514. this.onBeforeRenderTargetsRenderObservable.clear();
  28515. this.onAfterRenderTargetsRenderObservable.clear();
  28516. this.onAfterStepObservable.clear();
  28517. this.onBeforeStepObservable.clear();
  28518. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28519. this.onAfterActiveMeshesEvaluationObservable.clear();
  28520. this.onBeforeParticlesRenderingObservable.clear();
  28521. this.onAfterParticlesRenderingObservable.clear();
  28522. this.onBeforeSpritesRenderingObservable.clear();
  28523. this.onAfterSpritesRenderingObservable.clear();
  28524. this.onBeforeDrawPhaseObservable.clear();
  28525. this.onAfterDrawPhaseObservable.clear();
  28526. this.onBeforePhysicsObservable.clear();
  28527. this.onAfterPhysicsObservable.clear();
  28528. this.onBeforeAnimationsObservable.clear();
  28529. this.onAfterAnimationsObservable.clear();
  28530. this.onDataLoadedObservable.clear();
  28531. this.detachControl();
  28532. // Release sounds & sounds tracks
  28533. if (BABYLON.AudioEngine) {
  28534. this.disposeSounds();
  28535. }
  28536. // VR Helper
  28537. if (this.VRHelper) {
  28538. this.VRHelper.dispose();
  28539. }
  28540. // Detach cameras
  28541. var canvas = this._engine.getRenderingCanvas();
  28542. if (canvas) {
  28543. var index;
  28544. for (index = 0; index < this.cameras.length; index++) {
  28545. this.cameras[index].detachControl(canvas);
  28546. }
  28547. }
  28548. // Release animation groups
  28549. while (this.animationGroups.length) {
  28550. this.animationGroups[0].dispose();
  28551. }
  28552. // Release lights
  28553. while (this.lights.length) {
  28554. this.lights[0].dispose();
  28555. }
  28556. // Release meshes
  28557. while (this.meshes.length) {
  28558. this.meshes[0].dispose(true);
  28559. }
  28560. while (this.transformNodes.length) {
  28561. this.removeTransformNode(this.transformNodes[0]);
  28562. }
  28563. // Release cameras
  28564. while (this.cameras.length) {
  28565. this.cameras[0].dispose();
  28566. }
  28567. // Release materials
  28568. if (this.defaultMaterial) {
  28569. this.defaultMaterial.dispose();
  28570. }
  28571. while (this.multiMaterials.length) {
  28572. this.multiMaterials[0].dispose();
  28573. }
  28574. while (this.materials.length) {
  28575. this.materials[0].dispose();
  28576. }
  28577. // Release particles
  28578. while (this.particleSystems.length) {
  28579. this.particleSystems[0].dispose();
  28580. }
  28581. // Release sprites
  28582. while (this.spriteManagers.length) {
  28583. this.spriteManagers[0].dispose();
  28584. }
  28585. // Release postProcesses
  28586. while (this.postProcesses.length) {
  28587. this.postProcesses[0].dispose();
  28588. }
  28589. // Release textures
  28590. while (this.textures.length) {
  28591. this.textures[0].dispose();
  28592. }
  28593. // Release UBO
  28594. this._sceneUbo.dispose();
  28595. if (this._alternateSceneUbo) {
  28596. this._alternateSceneUbo.dispose();
  28597. }
  28598. // Post-processes
  28599. this.postProcessManager.dispose();
  28600. if (this._postProcessRenderPipelineManager) {
  28601. this._postProcessRenderPipelineManager.dispose();
  28602. }
  28603. // Physics
  28604. if (this._physicsEngine) {
  28605. this.disablePhysicsEngine();
  28606. }
  28607. // Remove from engine
  28608. index = this._engine.scenes.indexOf(this);
  28609. if (index > -1) {
  28610. this._engine.scenes.splice(index, 1);
  28611. }
  28612. this._engine.wipeCaches(true);
  28613. this._isDisposed = true;
  28614. };
  28615. Object.defineProperty(Scene.prototype, "isDisposed", {
  28616. /**
  28617. * Gets if the scene is already disposed
  28618. */
  28619. get: function () {
  28620. return this._isDisposed;
  28621. },
  28622. enumerable: true,
  28623. configurable: true
  28624. });
  28625. /**
  28626. * Releases sounds & soundtracks
  28627. */
  28628. Scene.prototype.disposeSounds = function () {
  28629. if (!this._mainSoundTrack) {
  28630. return;
  28631. }
  28632. this.mainSoundTrack.dispose();
  28633. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28634. this.soundTracks[scIndex].dispose();
  28635. }
  28636. };
  28637. /**
  28638. * Call this function to reduce memory footprint of the scene.
  28639. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28640. */
  28641. Scene.prototype.clearCachedVertexData = function () {
  28642. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28643. var mesh = this.meshes[meshIndex];
  28644. var geometry = mesh.geometry;
  28645. if (geometry) {
  28646. geometry._indices = [];
  28647. for (var vbName in geometry._vertexBuffers) {
  28648. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28649. continue;
  28650. }
  28651. geometry._vertexBuffers[vbName]._buffer._data = null;
  28652. }
  28653. }
  28654. }
  28655. };
  28656. /**
  28657. * This function will remove the local cached buffer data from texture.
  28658. * It will save memory but will prevent the texture from being rebuilt
  28659. */
  28660. Scene.prototype.cleanCachedTextureBuffer = function () {
  28661. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28662. var baseTexture = _a[_i];
  28663. var buffer = baseTexture._buffer;
  28664. if (buffer) {
  28665. baseTexture._buffer = null;
  28666. }
  28667. }
  28668. };
  28669. // Octrees
  28670. /**
  28671. * Get the world extend vectors with an optional filter
  28672. *
  28673. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28674. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28675. */
  28676. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28677. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28678. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28679. filterPredicate = filterPredicate || (function () { return true; });
  28680. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28681. mesh.computeWorldMatrix(true);
  28682. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28683. return;
  28684. }
  28685. var boundingInfo = mesh.getBoundingInfo();
  28686. var minBox = boundingInfo.boundingBox.minimumWorld;
  28687. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28688. BABYLON.Tools.CheckExtends(minBox, min, max);
  28689. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28690. });
  28691. return {
  28692. min: min,
  28693. max: max
  28694. };
  28695. };
  28696. /**
  28697. * Creates or updates the octree used to boost selection (picking)
  28698. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28699. * @param maxCapacity defines the maximum capacity per leaf
  28700. * @param maxDepth defines the maximum depth of the octree
  28701. * @returns an octree of AbstractMesh
  28702. */
  28703. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28704. if (maxCapacity === void 0) { maxCapacity = 64; }
  28705. if (maxDepth === void 0) { maxDepth = 2; }
  28706. if (!this._selectionOctree) {
  28707. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28708. }
  28709. var worldExtends = this.getWorldExtends();
  28710. // Update octree
  28711. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28712. return this._selectionOctree;
  28713. };
  28714. // Picking
  28715. /**
  28716. * Creates a ray that can be used to pick in the scene
  28717. * @param x defines the x coordinate of the origin (on-screen)
  28718. * @param y defines the y coordinate of the origin (on-screen)
  28719. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28720. * @param camera defines the camera to use for the picking
  28721. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28722. * @returns a Ray
  28723. */
  28724. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28725. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28726. var result = BABYLON.Ray.Zero();
  28727. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28728. return result;
  28729. };
  28730. /**
  28731. * Creates a ray that can be used to pick in the scene
  28732. * @param x defines the x coordinate of the origin (on-screen)
  28733. * @param y defines the y coordinate of the origin (on-screen)
  28734. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28735. * @param result defines the ray where to store the picking ray
  28736. * @param camera defines the camera to use for the picking
  28737. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28738. * @returns the current scene
  28739. */
  28740. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28741. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28742. var engine = this._engine;
  28743. if (!camera) {
  28744. if (!this.activeCamera)
  28745. throw new Error("Active camera not set");
  28746. camera = this.activeCamera;
  28747. }
  28748. var cameraViewport = camera.viewport;
  28749. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28750. // Moving coordinates to local viewport world
  28751. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28752. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28753. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28754. return this;
  28755. };
  28756. /**
  28757. * Creates a ray that can be used to pick in the scene
  28758. * @param x defines the x coordinate of the origin (on-screen)
  28759. * @param y defines the y coordinate of the origin (on-screen)
  28760. * @param camera defines the camera to use for the picking
  28761. * @returns a Ray
  28762. */
  28763. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28764. var result = BABYLON.Ray.Zero();
  28765. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28766. return result;
  28767. };
  28768. /**
  28769. * Creates a ray that can be used to pick in the scene
  28770. * @param x defines the x coordinate of the origin (on-screen)
  28771. * @param y defines the y coordinate of the origin (on-screen)
  28772. * @param result defines the ray where to store the picking ray
  28773. * @param camera defines the camera to use for the picking
  28774. * @returns the current scene
  28775. */
  28776. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28777. if (!BABYLON.PickingInfo) {
  28778. return this;
  28779. }
  28780. var engine = this._engine;
  28781. if (!camera) {
  28782. if (!this.activeCamera)
  28783. throw new Error("Active camera not set");
  28784. camera = this.activeCamera;
  28785. }
  28786. var cameraViewport = camera.viewport;
  28787. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28788. var identity = BABYLON.Matrix.Identity();
  28789. // Moving coordinates to local viewport world
  28790. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28791. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28792. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28793. return this;
  28794. };
  28795. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28796. if (!BABYLON.PickingInfo) {
  28797. return null;
  28798. }
  28799. var pickingInfo = null;
  28800. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28801. var mesh = this.meshes[meshIndex];
  28802. if (predicate) {
  28803. if (!predicate(mesh)) {
  28804. continue;
  28805. }
  28806. }
  28807. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28808. continue;
  28809. }
  28810. var world = mesh.getWorldMatrix();
  28811. var ray = rayFunction(world);
  28812. var result = mesh.intersects(ray, fastCheck);
  28813. if (!result || !result.hit)
  28814. continue;
  28815. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28816. continue;
  28817. pickingInfo = result;
  28818. if (fastCheck) {
  28819. break;
  28820. }
  28821. }
  28822. return pickingInfo || new BABYLON.PickingInfo();
  28823. };
  28824. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28825. if (!BABYLON.PickingInfo) {
  28826. return null;
  28827. }
  28828. var pickingInfos = new Array();
  28829. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28830. var mesh = this.meshes[meshIndex];
  28831. if (predicate) {
  28832. if (!predicate(mesh)) {
  28833. continue;
  28834. }
  28835. }
  28836. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28837. continue;
  28838. }
  28839. var world = mesh.getWorldMatrix();
  28840. var ray = rayFunction(world);
  28841. var result = mesh.intersects(ray, false);
  28842. if (!result || !result.hit)
  28843. continue;
  28844. pickingInfos.push(result);
  28845. }
  28846. return pickingInfos;
  28847. };
  28848. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28849. if (!BABYLON.PickingInfo) {
  28850. return null;
  28851. }
  28852. var pickingInfo = null;
  28853. if (!camera) {
  28854. if (!this.activeCamera) {
  28855. return null;
  28856. }
  28857. camera = this.activeCamera;
  28858. }
  28859. if (this.spriteManagers.length > 0) {
  28860. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28861. var spriteManager = this.spriteManagers[spriteIndex];
  28862. if (!spriteManager.isPickable) {
  28863. continue;
  28864. }
  28865. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28866. if (!result || !result.hit)
  28867. continue;
  28868. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28869. continue;
  28870. pickingInfo = result;
  28871. if (fastCheck) {
  28872. break;
  28873. }
  28874. }
  28875. }
  28876. return pickingInfo || new BABYLON.PickingInfo();
  28877. };
  28878. /** Launch a ray to try to pick a mesh in the scene
  28879. * @param x position on screen
  28880. * @param y position on screen
  28881. * @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
  28882. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28883. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28884. * @returns a PickingInfo
  28885. */
  28886. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28887. var _this = this;
  28888. if (!BABYLON.PickingInfo) {
  28889. return null;
  28890. }
  28891. var result = this._internalPick(function (world) {
  28892. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28893. return _this._tempPickingRay;
  28894. }, predicate, fastCheck);
  28895. if (result) {
  28896. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28897. }
  28898. return result;
  28899. };
  28900. /** Launch a ray to try to pick a sprite in the scene
  28901. * @param x position on screen
  28902. * @param y position on screen
  28903. * @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
  28904. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28905. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28906. * @returns a PickingInfo
  28907. */
  28908. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28909. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28910. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28911. };
  28912. /** Use the given ray to pick a mesh in the scene
  28913. * @param ray The ray to use to pick meshes
  28914. * @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
  28915. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28916. * @returns a PickingInfo
  28917. */
  28918. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28919. var _this = this;
  28920. var result = this._internalPick(function (world) {
  28921. if (!_this._pickWithRayInverseMatrix) {
  28922. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28923. }
  28924. world.invertToRef(_this._pickWithRayInverseMatrix);
  28925. if (!_this._cachedRayForTransform) {
  28926. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28927. }
  28928. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28929. return _this._cachedRayForTransform;
  28930. }, predicate, fastCheck);
  28931. if (result) {
  28932. result.ray = ray;
  28933. }
  28934. return result;
  28935. };
  28936. /**
  28937. * Launch a ray to try to pick a mesh in the scene
  28938. * @param x X position on screen
  28939. * @param y Y position on screen
  28940. * @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
  28941. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28942. * @returns an array of PickingInfo
  28943. */
  28944. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28945. var _this = this;
  28946. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28947. };
  28948. /**
  28949. * Launch a ray to try to pick a mesh in the scene
  28950. * @param ray Ray to use
  28951. * @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
  28952. * @returns an array of PickingInfo
  28953. */
  28954. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28955. var _this = this;
  28956. return this._internalMultiPick(function (world) {
  28957. if (!_this._pickWithRayInverseMatrix) {
  28958. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28959. }
  28960. world.invertToRef(_this._pickWithRayInverseMatrix);
  28961. if (!_this._cachedRayForTransform) {
  28962. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28963. }
  28964. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28965. return _this._cachedRayForTransform;
  28966. }, predicate);
  28967. };
  28968. /**
  28969. * Force the value of meshUnderPointer
  28970. * @param mesh defines the mesh to use
  28971. */
  28972. Scene.prototype.setPointerOverMesh = function (mesh) {
  28973. if (this._pointerOverMesh === mesh) {
  28974. return;
  28975. }
  28976. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28977. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28978. }
  28979. this._pointerOverMesh = mesh;
  28980. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28981. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28982. }
  28983. };
  28984. /**
  28985. * Gets the mesh under the pointer
  28986. * @returns a Mesh or null if no mesh is under the pointer
  28987. */
  28988. Scene.prototype.getPointerOverMesh = function () {
  28989. return this._pointerOverMesh;
  28990. };
  28991. /**
  28992. * Force the sprite under the pointer
  28993. * @param sprite defines the sprite to use
  28994. */
  28995. Scene.prototype.setPointerOverSprite = function (sprite) {
  28996. if (this._pointerOverSprite === sprite) {
  28997. return;
  28998. }
  28999. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  29000. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  29001. }
  29002. this._pointerOverSprite = sprite;
  29003. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  29004. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  29005. }
  29006. };
  29007. /**
  29008. * Gets the sprite under the pointer
  29009. * @returns a Sprite or null if no sprite is under the pointer
  29010. */
  29011. Scene.prototype.getPointerOverSprite = function () {
  29012. return this._pointerOverSprite;
  29013. };
  29014. // Physics
  29015. /**
  29016. * Gets the current physics engine
  29017. * @returns a PhysicsEngine or null if none attached
  29018. */
  29019. Scene.prototype.getPhysicsEngine = function () {
  29020. return this._physicsEngine;
  29021. };
  29022. /**
  29023. * Enables physics to the current scene
  29024. * @param gravity defines the scene's gravity for the physics engine
  29025. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  29026. * @return a boolean indicating if the physics engine was initialized
  29027. */
  29028. Scene.prototype.enablePhysics = function (gravity, plugin) {
  29029. if (gravity === void 0) { gravity = null; }
  29030. if (this._physicsEngine) {
  29031. return true;
  29032. }
  29033. try {
  29034. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  29035. return true;
  29036. }
  29037. catch (e) {
  29038. BABYLON.Tools.Error(e.message);
  29039. return false;
  29040. }
  29041. };
  29042. /**
  29043. * Disables and disposes the physics engine associated with the scene
  29044. */
  29045. Scene.prototype.disablePhysicsEngine = function () {
  29046. if (!this._physicsEngine) {
  29047. return;
  29048. }
  29049. this._physicsEngine.dispose();
  29050. this._physicsEngine = null;
  29051. };
  29052. /**
  29053. * Gets a boolean indicating if there is an active physics engine
  29054. * @returns a boolean indicating if there is an active physics engine
  29055. */
  29056. Scene.prototype.isPhysicsEnabled = function () {
  29057. return this._physicsEngine !== undefined;
  29058. };
  29059. /**
  29060. * Deletes a physics compound impostor
  29061. * @param compound defines the compound to delete
  29062. */
  29063. Scene.prototype.deleteCompoundImpostor = function (compound) {
  29064. var mesh = compound.parts[0].mesh;
  29065. if (mesh.physicsImpostor) {
  29066. mesh.physicsImpostor.dispose( /*true*/);
  29067. mesh.physicsImpostor = null;
  29068. }
  29069. };
  29070. // Misc.
  29071. /** @hidden */
  29072. Scene.prototype._rebuildGeometries = function () {
  29073. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29074. var geometry = _a[_i];
  29075. geometry._rebuild();
  29076. }
  29077. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29078. var mesh = _c[_b];
  29079. mesh._rebuild();
  29080. }
  29081. if (this.postProcessManager) {
  29082. this.postProcessManager._rebuild();
  29083. }
  29084. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29085. var component = _e[_d];
  29086. component.rebuild();
  29087. }
  29088. if (this._boundingBoxRenderer) {
  29089. this._boundingBoxRenderer._rebuild();
  29090. }
  29091. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29092. var system = _g[_f];
  29093. system.rebuild();
  29094. }
  29095. if (this._postProcessRenderPipelineManager) {
  29096. this._postProcessRenderPipelineManager._rebuild();
  29097. }
  29098. };
  29099. /** @hidden */
  29100. Scene.prototype._rebuildTextures = function () {
  29101. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29102. var texture = _a[_i];
  29103. texture._rebuild();
  29104. }
  29105. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29106. };
  29107. /**
  29108. * Creates a default light for the scene.
  29109. * @param replace Whether to replace the existing lights in the scene.
  29110. */
  29111. Scene.prototype.createDefaultLight = function (replace) {
  29112. if (replace === void 0) { replace = false; }
  29113. // Dispose existing light in replace mode.
  29114. if (replace) {
  29115. if (this.lights) {
  29116. for (var i = 0; i < this.lights.length; i++) {
  29117. this.lights[i].dispose();
  29118. }
  29119. }
  29120. }
  29121. // Light
  29122. if (this.lights.length === 0) {
  29123. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  29124. }
  29125. };
  29126. /**
  29127. * Creates a default camera for the scene.
  29128. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  29129. * @param replace Whether to replace the existing active camera in the scene.
  29130. * @param attachCameraControls Whether to attach camera controls to the canvas.
  29131. */
  29132. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  29133. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29134. if (replace === void 0) { replace = false; }
  29135. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29136. // Dispose existing camera in replace mode.
  29137. if (replace) {
  29138. if (this.activeCamera) {
  29139. this.activeCamera.dispose();
  29140. this.activeCamera = null;
  29141. }
  29142. }
  29143. // Camera
  29144. if (!this.activeCamera) {
  29145. var worldExtends = this.getWorldExtends();
  29146. var worldSize = worldExtends.max.subtract(worldExtends.min);
  29147. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  29148. var camera;
  29149. var radius = worldSize.length() * 1.5;
  29150. // empty scene scenario!
  29151. if (!isFinite(radius)) {
  29152. radius = 1;
  29153. worldCenter.copyFromFloats(0, 0, 0);
  29154. }
  29155. if (createArcRotateCamera) {
  29156. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  29157. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  29158. arcRotateCamera.wheelPrecision = 100 / radius;
  29159. camera = arcRotateCamera;
  29160. }
  29161. else {
  29162. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  29163. freeCamera.setTarget(worldCenter);
  29164. camera = freeCamera;
  29165. }
  29166. camera.minZ = radius * 0.01;
  29167. camera.maxZ = radius * 1000;
  29168. camera.speed = radius * 0.2;
  29169. this.activeCamera = camera;
  29170. var canvas = this.getEngine().getRenderingCanvas();
  29171. if (attachCameraControls && canvas) {
  29172. camera.attachControl(canvas);
  29173. }
  29174. }
  29175. };
  29176. /**
  29177. * Creates a default camera and a default light
  29178. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29179. * @param replace defines if the camera and/or light will replace the existing ones
  29180. * @param attachCameraControls defines if attachControl will be called on the new camera
  29181. */
  29182. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29183. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29184. if (replace === void 0) { replace = false; }
  29185. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29186. this.createDefaultLight(replace);
  29187. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29188. };
  29189. /**
  29190. * Creates a new sky box
  29191. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29192. * @param environmentTexture defines the texture to use as environment texture
  29193. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29194. * @param scale defines the overall scale of the skybox
  29195. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29196. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29197. * @returns a new mesh holding the sky box
  29198. */
  29199. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29200. if (pbr === void 0) { pbr = false; }
  29201. if (scale === void 0) { scale = 1000; }
  29202. if (blur === void 0) { blur = 0; }
  29203. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29204. if (!environmentTexture) {
  29205. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29206. return null;
  29207. }
  29208. if (setGlobalEnvTexture) {
  29209. if (environmentTexture) {
  29210. this.environmentTexture = environmentTexture;
  29211. }
  29212. }
  29213. // Skybox
  29214. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29215. if (pbr) {
  29216. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29217. hdrSkyboxMaterial.backFaceCulling = false;
  29218. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29219. if (hdrSkyboxMaterial.reflectionTexture) {
  29220. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29221. }
  29222. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29223. hdrSkyboxMaterial.disableLighting = true;
  29224. hdrSkyboxMaterial.twoSidedLighting = true;
  29225. hdrSkybox.infiniteDistance = true;
  29226. hdrSkybox.material = hdrSkyboxMaterial;
  29227. }
  29228. else {
  29229. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29230. skyboxMaterial.backFaceCulling = false;
  29231. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29232. if (skyboxMaterial.reflectionTexture) {
  29233. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29234. }
  29235. skyboxMaterial.disableLighting = true;
  29236. hdrSkybox.infiniteDistance = true;
  29237. hdrSkybox.material = skyboxMaterial;
  29238. }
  29239. return hdrSkybox;
  29240. };
  29241. /**
  29242. * Creates a new environment
  29243. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29244. * @param options defines the options you can use to configure the environment
  29245. * @returns the new EnvironmentHelper
  29246. */
  29247. Scene.prototype.createDefaultEnvironment = function (options) {
  29248. if (BABYLON.EnvironmentHelper) {
  29249. return new BABYLON.EnvironmentHelper(options, this);
  29250. }
  29251. return null;
  29252. };
  29253. /**
  29254. * Creates a new VREXperienceHelper
  29255. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29256. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29257. * @returns a new VREXperienceHelper
  29258. */
  29259. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29260. if (webVROptions === void 0) { webVROptions = {}; }
  29261. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29262. };
  29263. // Tags
  29264. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29265. if (tagsQuery === undefined) {
  29266. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29267. return list;
  29268. }
  29269. var listByTags = [];
  29270. forEach = forEach || (function (item) { return; });
  29271. for (var i in list) {
  29272. var item = list[i];
  29273. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29274. listByTags.push(item);
  29275. forEach(item);
  29276. }
  29277. }
  29278. return listByTags;
  29279. };
  29280. /**
  29281. * Get a list of meshes by tags
  29282. * @param tagsQuery defines the tags query to use
  29283. * @param forEach defines a predicate used to filter results
  29284. * @returns an array of Mesh
  29285. */
  29286. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29287. return this._getByTags(this.meshes, tagsQuery, forEach);
  29288. };
  29289. /**
  29290. * Get a list of cameras by tags
  29291. * @param tagsQuery defines the tags query to use
  29292. * @param forEach defines a predicate used to filter results
  29293. * @returns an array of Camera
  29294. */
  29295. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29296. return this._getByTags(this.cameras, tagsQuery, forEach);
  29297. };
  29298. /**
  29299. * Get a list of lights by tags
  29300. * @param tagsQuery defines the tags query to use
  29301. * @param forEach defines a predicate used to filter results
  29302. * @returns an array of Light
  29303. */
  29304. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29305. return this._getByTags(this.lights, tagsQuery, forEach);
  29306. };
  29307. /**
  29308. * Get a list of materials by tags
  29309. * @param tagsQuery defines the tags query to use
  29310. * @param forEach defines a predicate used to filter results
  29311. * @returns an array of Material
  29312. */
  29313. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29314. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29315. };
  29316. /**
  29317. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29318. * This allowed control for front to back rendering or reversly depending of the special needs.
  29319. *
  29320. * @param renderingGroupId The rendering group id corresponding to its index
  29321. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29322. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29323. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29324. */
  29325. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29326. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29327. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29328. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29329. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29330. };
  29331. /**
  29332. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29333. *
  29334. * @param renderingGroupId The rendering group id corresponding to its index
  29335. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29336. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29337. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29338. */
  29339. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29340. if (depth === void 0) { depth = true; }
  29341. if (stencil === void 0) { stencil = true; }
  29342. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29343. };
  29344. /**
  29345. * Will flag all materials as dirty to trigger new shader compilation
  29346. * @param flag defines the flag used to specify which material part must be marked as dirty
  29347. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29348. */
  29349. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29350. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29351. var material = _a[_i];
  29352. if (predicate && !predicate(material)) {
  29353. continue;
  29354. }
  29355. material.markAsDirty(flag);
  29356. }
  29357. };
  29358. /** @hidden */
  29359. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29360. var _this = this;
  29361. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29362. this._activeRequests.push(request);
  29363. request.onCompleteObservable.add(function (request) {
  29364. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29365. });
  29366. return request;
  29367. };
  29368. /** @hidden */
  29369. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29370. var _this = this;
  29371. return new Promise(function (resolve, reject) {
  29372. _this._loadFile(url, function (data) {
  29373. resolve(data);
  29374. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29375. reject(exception);
  29376. });
  29377. });
  29378. };
  29379. // Statics
  29380. Scene._FOGMODE_NONE = 0;
  29381. Scene._FOGMODE_EXP = 1;
  29382. Scene._FOGMODE_EXP2 = 2;
  29383. Scene._FOGMODE_LINEAR = 3;
  29384. Scene._uniqueIdCounter = 0;
  29385. /**
  29386. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29387. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29388. */
  29389. Scene.MinDeltaTime = 1.0;
  29390. /**
  29391. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29392. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29393. */
  29394. Scene.MaxDeltaTime = 1000.0;
  29395. /** The distance in pixel that you have to move to prevent some events */
  29396. Scene.DragMovementThreshold = 10; // in pixels
  29397. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29398. Scene.LongPressDelay = 500; // in milliseconds
  29399. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29400. Scene.DoubleClickDelay = 300; // in milliseconds
  29401. /** If you need to check double click without raising a single click at first click, enable this flag */
  29402. Scene.ExclusiveDoubleClickMode = false;
  29403. return Scene;
  29404. }(BABYLON.AbstractScene));
  29405. BABYLON.Scene = Scene;
  29406. })(BABYLON || (BABYLON = {}));
  29407. //# sourceMappingURL=babylon.scene.js.map
  29408. var BABYLON;
  29409. (function (BABYLON) {
  29410. /**
  29411. * Set of assets to keep when moving a scene into an asset container.
  29412. */
  29413. var KeepAssets = /** @class */ (function (_super) {
  29414. __extends(KeepAssets, _super);
  29415. function KeepAssets() {
  29416. return _super !== null && _super.apply(this, arguments) || this;
  29417. }
  29418. return KeepAssets;
  29419. }(BABYLON.AbstractScene));
  29420. BABYLON.KeepAssets = KeepAssets;
  29421. /**
  29422. * Container with a set of assets that can be added or removed from a scene.
  29423. */
  29424. var AssetContainer = /** @class */ (function (_super) {
  29425. __extends(AssetContainer, _super);
  29426. /**
  29427. * Instantiates an AssetContainer.
  29428. * @param scene The scene the AssetContainer belongs to.
  29429. */
  29430. function AssetContainer(scene) {
  29431. var _this = _super.call(this) || this;
  29432. _this.scene = scene;
  29433. return _this;
  29434. }
  29435. /**
  29436. * Adds all the assets from the container to the scene.
  29437. */
  29438. AssetContainer.prototype.addAllToScene = function () {
  29439. var _this = this;
  29440. this.cameras.forEach(function (o) {
  29441. _this.scene.addCamera(o);
  29442. });
  29443. this.lights.forEach(function (o) {
  29444. _this.scene.addLight(o);
  29445. });
  29446. this.meshes.forEach(function (o) {
  29447. _this.scene.addMesh(o);
  29448. });
  29449. this.skeletons.forEach(function (o) {
  29450. _this.scene.addSkeleton(o);
  29451. });
  29452. this.particleSystems.forEach(function (o) {
  29453. _this.scene.addParticleSystem(o);
  29454. });
  29455. this.animations.forEach(function (o) {
  29456. _this.scene.addAnimation(o);
  29457. });
  29458. this.animationGroups.forEach(function (o) {
  29459. _this.scene.addAnimationGroup(o);
  29460. });
  29461. this.multiMaterials.forEach(function (o) {
  29462. _this.scene.addMultiMaterial(o);
  29463. });
  29464. this.materials.forEach(function (o) {
  29465. _this.scene.addMaterial(o);
  29466. });
  29467. this.morphTargetManagers.forEach(function (o) {
  29468. _this.scene.addMorphTargetManager(o);
  29469. });
  29470. this.geometries.forEach(function (o) {
  29471. _this.scene.addGeometry(o);
  29472. });
  29473. this.transformNodes.forEach(function (o) {
  29474. _this.scene.addTransformNode(o);
  29475. });
  29476. this.actionManagers.forEach(function (o) {
  29477. _this.scene.addActionManager(o);
  29478. });
  29479. this.sounds.forEach(function (o) {
  29480. o.play();
  29481. o.autoplay = true;
  29482. _this.scene.mainSoundTrack.AddSound(o);
  29483. });
  29484. this.textures.forEach(function (o) {
  29485. _this.scene.addTexture(o);
  29486. });
  29487. for (var _i = 0, _a = this.scene._components; _i < _a.length; _i++) {
  29488. var component = _a[_i];
  29489. component.addFromContainer(this.scene);
  29490. }
  29491. };
  29492. /**
  29493. * Removes all the assets in the container from the scene
  29494. */
  29495. AssetContainer.prototype.removeAllFromScene = function () {
  29496. var _this = this;
  29497. this.cameras.forEach(function (o) {
  29498. _this.scene.removeCamera(o);
  29499. });
  29500. this.lights.forEach(function (o) {
  29501. _this.scene.removeLight(o);
  29502. });
  29503. this.meshes.forEach(function (o) {
  29504. _this.scene.removeMesh(o);
  29505. });
  29506. this.skeletons.forEach(function (o) {
  29507. _this.scene.removeSkeleton(o);
  29508. });
  29509. this.particleSystems.forEach(function (o) {
  29510. _this.scene.removeParticleSystem(o);
  29511. });
  29512. this.animations.forEach(function (o) {
  29513. _this.scene.removeAnimation(o);
  29514. });
  29515. this.animationGroups.forEach(function (o) {
  29516. _this.scene.removeAnimationGroup(o);
  29517. });
  29518. this.multiMaterials.forEach(function (o) {
  29519. _this.scene.removeMultiMaterial(o);
  29520. });
  29521. this.materials.forEach(function (o) {
  29522. _this.scene.removeMaterial(o);
  29523. });
  29524. this.morphTargetManagers.forEach(function (o) {
  29525. _this.scene.removeMorphTargetManager(o);
  29526. });
  29527. this.geometries.forEach(function (o) {
  29528. _this.scene.removeGeometry(o);
  29529. });
  29530. this.transformNodes.forEach(function (o) {
  29531. _this.scene.removeTransformNode(o);
  29532. });
  29533. this.actionManagers.forEach(function (o) {
  29534. _this.scene.removeActionManager(o);
  29535. });
  29536. this.sounds.forEach(function (o) {
  29537. o.stop();
  29538. o.autoplay = false;
  29539. _this.scene.mainSoundTrack.RemoveSound(o);
  29540. });
  29541. this.textures.forEach(function (o) {
  29542. _this.scene.removeTexture(o);
  29543. });
  29544. for (var _i = 0, _a = this.scene._components; _i < _a.length; _i++) {
  29545. var component = _a[_i];
  29546. component.removeFromContainer(this.scene);
  29547. }
  29548. };
  29549. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29550. if (!sourceAssets) {
  29551. return;
  29552. }
  29553. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29554. var asset = sourceAssets_1[_i];
  29555. var move = true;
  29556. if (keepAssets) {
  29557. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29558. var keepAsset = keepAssets_1[_a];
  29559. if (asset === keepAsset) {
  29560. move = false;
  29561. break;
  29562. }
  29563. }
  29564. }
  29565. if (move) {
  29566. targetAssets.push(asset);
  29567. }
  29568. }
  29569. };
  29570. /**
  29571. * Removes all the assets contained in the scene and adds them to the container.
  29572. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29573. */
  29574. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29575. if (keepAssets === undefined) {
  29576. keepAssets = new KeepAssets();
  29577. }
  29578. for (var key in this) {
  29579. if (this.hasOwnProperty(key)) {
  29580. this[key] = this[key] || [];
  29581. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29582. }
  29583. }
  29584. this.removeAllFromScene();
  29585. };
  29586. /**
  29587. * 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.
  29588. * @returns the root mesh
  29589. */
  29590. AssetContainer.prototype.createRootMesh = function () {
  29591. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29592. this.meshes.forEach(function (m) {
  29593. if (!m.parent) {
  29594. rootMesh.addChild(m);
  29595. }
  29596. });
  29597. this.meshes.unshift(rootMesh);
  29598. return rootMesh;
  29599. };
  29600. return AssetContainer;
  29601. }(BABYLON.AbstractScene));
  29602. BABYLON.AssetContainer = AssetContainer;
  29603. })(BABYLON || (BABYLON = {}));
  29604. //# sourceMappingURL=babylon.assetContainer.js.map
  29605. var BABYLON;
  29606. (function (BABYLON) {
  29607. var Buffer = /** @class */ (function () {
  29608. /**
  29609. * Constructor
  29610. * @param engine the engine
  29611. * @param data the data to use for this buffer
  29612. * @param updatable whether the data is updatable
  29613. * @param stride the stride (optional)
  29614. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29615. * @param instanced whether the buffer is instanced (optional)
  29616. * @param useBytes set to true if the stride in in bytes (optional)
  29617. */
  29618. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29619. if (stride === void 0) { stride = 0; }
  29620. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29621. if (instanced === void 0) { instanced = false; }
  29622. if (useBytes === void 0) { useBytes = false; }
  29623. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29624. this._engine = engine.getScene().getEngine();
  29625. }
  29626. else {
  29627. this._engine = engine;
  29628. }
  29629. this._updatable = updatable;
  29630. this._instanced = instanced;
  29631. this._data = data;
  29632. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29633. if (!postponeInternalCreation) { // by default
  29634. this.create();
  29635. }
  29636. }
  29637. /**
  29638. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29639. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29640. * @param offset defines offset in the buffer (0 by default)
  29641. * @param size defines the size in floats of attributes (position is 3 for instance)
  29642. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29643. * @param instanced defines if the vertex buffer contains indexed data
  29644. * @param useBytes defines if the offset and stride are in bytes
  29645. * @returns the new vertex buffer
  29646. */
  29647. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29648. if (useBytes === void 0) { useBytes = false; }
  29649. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29650. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29651. // a lot of these parameters are ignored as they are overriden by the buffer
  29652. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29653. };
  29654. // Properties
  29655. Buffer.prototype.isUpdatable = function () {
  29656. return this._updatable;
  29657. };
  29658. Buffer.prototype.getData = function () {
  29659. return this._data;
  29660. };
  29661. Buffer.prototype.getBuffer = function () {
  29662. return this._buffer;
  29663. };
  29664. /**
  29665. * Gets the stride in float32 units (i.e. byte stride / 4).
  29666. * May not be an integer if the byte stride is not divisible by 4.
  29667. * DEPRECATED. Use byteStride instead.
  29668. * @returns the stride in float32 units
  29669. */
  29670. Buffer.prototype.getStrideSize = function () {
  29671. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29672. };
  29673. // Methods
  29674. Buffer.prototype.create = function (data) {
  29675. if (data === void 0) { data = null; }
  29676. if (!data && this._buffer) {
  29677. return; // nothing to do
  29678. }
  29679. data = data || this._data;
  29680. if (!data) {
  29681. return;
  29682. }
  29683. if (!this._buffer) { // create buffer
  29684. if (this._updatable) {
  29685. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29686. this._data = data;
  29687. }
  29688. else {
  29689. this._buffer = this._engine.createVertexBuffer(data);
  29690. }
  29691. }
  29692. else if (this._updatable) { // update buffer
  29693. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29694. this._data = data;
  29695. }
  29696. };
  29697. Buffer.prototype._rebuild = function () {
  29698. this._buffer = null;
  29699. this.create(this._data);
  29700. };
  29701. Buffer.prototype.update = function (data) {
  29702. this.create(data);
  29703. };
  29704. /**
  29705. * Updates the data directly.
  29706. * @param data the new data
  29707. * @param offset the new offset
  29708. * @param vertexCount the vertex count (optional)
  29709. * @param useBytes set to true if the offset is in bytes
  29710. */
  29711. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29712. if (useBytes === void 0) { useBytes = false; }
  29713. if (!this._buffer) {
  29714. return;
  29715. }
  29716. if (this._updatable) { // update buffer
  29717. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29718. this._data = null;
  29719. }
  29720. };
  29721. Buffer.prototype.dispose = function () {
  29722. if (!this._buffer) {
  29723. return;
  29724. }
  29725. if (this._engine._releaseBuffer(this._buffer)) {
  29726. this._buffer = null;
  29727. }
  29728. };
  29729. return Buffer;
  29730. }());
  29731. BABYLON.Buffer = Buffer;
  29732. })(BABYLON || (BABYLON = {}));
  29733. //# sourceMappingURL=babylon.buffer.js.map
  29734. var BABYLON;
  29735. (function (BABYLON) {
  29736. var VertexBuffer = /** @class */ (function () {
  29737. /**
  29738. * Constructor
  29739. * @param engine the engine
  29740. * @param data the data to use for this vertex buffer
  29741. * @param kind the vertex buffer kind
  29742. * @param updatable whether the data is updatable
  29743. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29744. * @param stride the stride (optional)
  29745. * @param instanced whether the buffer is instanced (optional)
  29746. * @param offset the offset of the data (optional)
  29747. * @param size the number of components (optional)
  29748. * @param type the type of the component (optional)
  29749. * @param normalized whether the data contains normalized data (optional)
  29750. * @param useBytes set to true if stride and offset are in bytes (optional)
  29751. */
  29752. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29753. if (normalized === void 0) { normalized = false; }
  29754. if (useBytes === void 0) { useBytes = false; }
  29755. if (data instanceof BABYLON.Buffer) {
  29756. this._buffer = data;
  29757. this._ownsBuffer = false;
  29758. }
  29759. else {
  29760. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29761. this._ownsBuffer = true;
  29762. }
  29763. this._kind = kind;
  29764. if (type == undefined) {
  29765. var data_1 = this.getData();
  29766. this.type = VertexBuffer.FLOAT;
  29767. if (data_1 instanceof Int8Array)
  29768. this.type = VertexBuffer.BYTE;
  29769. else if (data_1 instanceof Uint8Array)
  29770. this.type = VertexBuffer.UNSIGNED_BYTE;
  29771. else if (data_1 instanceof Int16Array)
  29772. this.type = VertexBuffer.SHORT;
  29773. else if (data_1 instanceof Uint16Array)
  29774. this.type = VertexBuffer.UNSIGNED_SHORT;
  29775. else if (data_1 instanceof Int32Array)
  29776. this.type = VertexBuffer.INT;
  29777. else if (data_1 instanceof Uint32Array)
  29778. this.type = VertexBuffer.UNSIGNED_INT;
  29779. }
  29780. else {
  29781. this.type = type;
  29782. }
  29783. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29784. if (useBytes) {
  29785. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29786. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29787. this.byteOffset = offset || 0;
  29788. }
  29789. else {
  29790. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29791. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29792. this.byteOffset = (offset || 0) * typeByteLength;
  29793. }
  29794. this.normalized = normalized;
  29795. this._instanced = instanced !== undefined ? instanced : false;
  29796. this._instanceDivisor = instanced ? 1 : 0;
  29797. }
  29798. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29799. /**
  29800. * Gets or sets the instance divisor when in instanced mode
  29801. */
  29802. get: function () {
  29803. return this._instanceDivisor;
  29804. },
  29805. set: function (value) {
  29806. this._instanceDivisor = value;
  29807. if (value == 0) {
  29808. this._instanced = false;
  29809. }
  29810. else {
  29811. this._instanced = true;
  29812. }
  29813. },
  29814. enumerable: true,
  29815. configurable: true
  29816. });
  29817. VertexBuffer.prototype._rebuild = function () {
  29818. if (!this._buffer) {
  29819. return;
  29820. }
  29821. this._buffer._rebuild();
  29822. };
  29823. /**
  29824. * Returns the kind of the VertexBuffer (string).
  29825. */
  29826. VertexBuffer.prototype.getKind = function () {
  29827. return this._kind;
  29828. };
  29829. // Properties
  29830. /**
  29831. * Boolean : is the VertexBuffer updatable ?
  29832. */
  29833. VertexBuffer.prototype.isUpdatable = function () {
  29834. return this._buffer.isUpdatable();
  29835. };
  29836. /**
  29837. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29838. */
  29839. VertexBuffer.prototype.getData = function () {
  29840. return this._buffer.getData();
  29841. };
  29842. /**
  29843. * Returns the WebGLBuffer associated to the VertexBuffer.
  29844. */
  29845. VertexBuffer.prototype.getBuffer = function () {
  29846. return this._buffer.getBuffer();
  29847. };
  29848. /**
  29849. * Returns the stride as a multiple of the type byte length.
  29850. * DEPRECATED. Use byteStride instead.
  29851. */
  29852. VertexBuffer.prototype.getStrideSize = function () {
  29853. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29854. };
  29855. /**
  29856. * Returns the offset as a multiple of the type byte length.
  29857. * DEPRECATED. Use byteOffset instead.
  29858. */
  29859. VertexBuffer.prototype.getOffset = function () {
  29860. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29861. };
  29862. /**
  29863. * Returns the number of components per vertex attribute (integer).
  29864. */
  29865. VertexBuffer.prototype.getSize = function () {
  29866. return this._size;
  29867. };
  29868. /**
  29869. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29870. */
  29871. VertexBuffer.prototype.getIsInstanced = function () {
  29872. return this._instanced;
  29873. };
  29874. /**
  29875. * Returns the instancing divisor, zero for non-instanced (integer).
  29876. */
  29877. VertexBuffer.prototype.getInstanceDivisor = function () {
  29878. return this._instanceDivisor;
  29879. };
  29880. // Methods
  29881. /**
  29882. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29883. * Returns the created WebGLBuffer.
  29884. */
  29885. VertexBuffer.prototype.create = function (data) {
  29886. return this._buffer.create(data);
  29887. };
  29888. /**
  29889. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29890. * This function will create a new buffer if the current one is not updatable
  29891. * Returns the updated WebGLBuffer.
  29892. */
  29893. VertexBuffer.prototype.update = function (data) {
  29894. return this._buffer.update(data);
  29895. };
  29896. /**
  29897. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29898. * Returns the directly updated WebGLBuffer.
  29899. * @param data the new data
  29900. * @param offset the new offset
  29901. * @param useBytes set to true if the offset is in bytes
  29902. */
  29903. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29904. if (useBytes === void 0) { useBytes = false; }
  29905. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29906. };
  29907. /**
  29908. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29909. */
  29910. VertexBuffer.prototype.dispose = function () {
  29911. if (this._ownsBuffer) {
  29912. this._buffer.dispose();
  29913. }
  29914. };
  29915. /**
  29916. * Enumerates each value of this vertex buffer as numbers.
  29917. * @param count the number of values to enumerate
  29918. * @param callback the callback function called for each value
  29919. */
  29920. VertexBuffer.prototype.forEach = function (count, callback) {
  29921. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29922. };
  29923. Object.defineProperty(VertexBuffer, "PositionKind", {
  29924. get: function () {
  29925. return VertexBuffer._PositionKind;
  29926. },
  29927. enumerable: true,
  29928. configurable: true
  29929. });
  29930. Object.defineProperty(VertexBuffer, "NormalKind", {
  29931. get: function () {
  29932. return VertexBuffer._NormalKind;
  29933. },
  29934. enumerable: true,
  29935. configurable: true
  29936. });
  29937. Object.defineProperty(VertexBuffer, "TangentKind", {
  29938. get: function () {
  29939. return VertexBuffer._TangentKind;
  29940. },
  29941. enumerable: true,
  29942. configurable: true
  29943. });
  29944. Object.defineProperty(VertexBuffer, "UVKind", {
  29945. get: function () {
  29946. return VertexBuffer._UVKind;
  29947. },
  29948. enumerable: true,
  29949. configurable: true
  29950. });
  29951. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29952. get: function () {
  29953. return VertexBuffer._UV2Kind;
  29954. },
  29955. enumerable: true,
  29956. configurable: true
  29957. });
  29958. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29959. get: function () {
  29960. return VertexBuffer._UV3Kind;
  29961. },
  29962. enumerable: true,
  29963. configurable: true
  29964. });
  29965. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29966. get: function () {
  29967. return VertexBuffer._UV4Kind;
  29968. },
  29969. enumerable: true,
  29970. configurable: true
  29971. });
  29972. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29973. get: function () {
  29974. return VertexBuffer._UV5Kind;
  29975. },
  29976. enumerable: true,
  29977. configurable: true
  29978. });
  29979. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29980. get: function () {
  29981. return VertexBuffer._UV6Kind;
  29982. },
  29983. enumerable: true,
  29984. configurable: true
  29985. });
  29986. Object.defineProperty(VertexBuffer, "ColorKind", {
  29987. get: function () {
  29988. return VertexBuffer._ColorKind;
  29989. },
  29990. enumerable: true,
  29991. configurable: true
  29992. });
  29993. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29994. get: function () {
  29995. return VertexBuffer._MatricesIndicesKind;
  29996. },
  29997. enumerable: true,
  29998. configurable: true
  29999. });
  30000. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  30001. get: function () {
  30002. return VertexBuffer._MatricesWeightsKind;
  30003. },
  30004. enumerable: true,
  30005. configurable: true
  30006. });
  30007. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  30008. get: function () {
  30009. return VertexBuffer._MatricesIndicesExtraKind;
  30010. },
  30011. enumerable: true,
  30012. configurable: true
  30013. });
  30014. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  30015. get: function () {
  30016. return VertexBuffer._MatricesWeightsExtraKind;
  30017. },
  30018. enumerable: true,
  30019. configurable: true
  30020. });
  30021. /**
  30022. * Deduces the stride given a kind.
  30023. * @param kind The kind string to deduce
  30024. * @returns The deduced stride
  30025. */
  30026. VertexBuffer.DeduceStride = function (kind) {
  30027. switch (kind) {
  30028. case VertexBuffer.UVKind:
  30029. case VertexBuffer.UV2Kind:
  30030. case VertexBuffer.UV3Kind:
  30031. case VertexBuffer.UV4Kind:
  30032. case VertexBuffer.UV5Kind:
  30033. case VertexBuffer.UV6Kind:
  30034. return 2;
  30035. case VertexBuffer.NormalKind:
  30036. case VertexBuffer.PositionKind:
  30037. return 3;
  30038. case VertexBuffer.ColorKind:
  30039. case VertexBuffer.MatricesIndicesKind:
  30040. case VertexBuffer.MatricesIndicesExtraKind:
  30041. case VertexBuffer.MatricesWeightsKind:
  30042. case VertexBuffer.MatricesWeightsExtraKind:
  30043. case VertexBuffer.TangentKind:
  30044. return 4;
  30045. default:
  30046. throw new Error("Invalid kind '" + kind + "'");
  30047. }
  30048. };
  30049. /**
  30050. * Gets the byte length of the given type.
  30051. * @param type the type
  30052. * @returns the number of bytes
  30053. */
  30054. VertexBuffer.GetTypeByteLength = function (type) {
  30055. switch (type) {
  30056. case VertexBuffer.BYTE:
  30057. case VertexBuffer.UNSIGNED_BYTE:
  30058. return 1;
  30059. case VertexBuffer.SHORT:
  30060. case VertexBuffer.UNSIGNED_SHORT:
  30061. return 2;
  30062. case VertexBuffer.INT:
  30063. case VertexBuffer.FLOAT:
  30064. return 4;
  30065. default:
  30066. throw new Error("Invalid type '" + type + "'");
  30067. }
  30068. };
  30069. /**
  30070. * Enumerates each value of the given parameters as numbers.
  30071. * @param data the data to enumerate
  30072. * @param byteOffset the byte offset of the data
  30073. * @param byteStride the byte stride of the data
  30074. * @param componentCount the number of components per element
  30075. * @param componentType the type of the component
  30076. * @param count the total number of components
  30077. * @param normalized whether the data is normalized
  30078. * @param callback the callback function called for each value
  30079. */
  30080. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30081. if (data instanceof Array) {
  30082. var offset = byteOffset / 4;
  30083. var stride = byteStride / 4;
  30084. for (var index = 0; index < count; index += componentCount) {
  30085. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30086. callback(data[offset + componentIndex], index + componentIndex);
  30087. }
  30088. offset += stride;
  30089. }
  30090. }
  30091. else {
  30092. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30093. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30094. for (var index = 0; index < count; index += componentCount) {
  30095. var componentByteOffset = byteOffset;
  30096. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30097. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30098. callback(value, index + componentIndex);
  30099. componentByteOffset += componentByteLength;
  30100. }
  30101. byteOffset += byteStride;
  30102. }
  30103. }
  30104. };
  30105. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30106. switch (type) {
  30107. case VertexBuffer.BYTE: {
  30108. var value = dataView.getInt8(byteOffset);
  30109. if (normalized) {
  30110. value = Math.max(value / 127, -1);
  30111. }
  30112. return value;
  30113. }
  30114. case VertexBuffer.UNSIGNED_BYTE: {
  30115. var value = dataView.getUint8(byteOffset);
  30116. if (normalized) {
  30117. value = value / 255;
  30118. }
  30119. return value;
  30120. }
  30121. case VertexBuffer.SHORT: {
  30122. var value = dataView.getInt16(byteOffset, true);
  30123. if (normalized) {
  30124. value = Math.max(value / 16383, -1);
  30125. }
  30126. return value;
  30127. }
  30128. case VertexBuffer.UNSIGNED_SHORT: {
  30129. var value = dataView.getUint16(byteOffset, true);
  30130. if (normalized) {
  30131. value = value / 65535;
  30132. }
  30133. return value;
  30134. }
  30135. case VertexBuffer.FLOAT: {
  30136. return dataView.getFloat32(byteOffset, true);
  30137. }
  30138. default: {
  30139. throw new Error("Invalid component type " + type);
  30140. }
  30141. }
  30142. };
  30143. /**
  30144. * The byte type.
  30145. */
  30146. VertexBuffer.BYTE = 5120;
  30147. /**
  30148. * The unsigned byte type.
  30149. */
  30150. VertexBuffer.UNSIGNED_BYTE = 5121;
  30151. /**
  30152. * The short type.
  30153. */
  30154. VertexBuffer.SHORT = 5122;
  30155. /**
  30156. * The unsigned short type.
  30157. */
  30158. VertexBuffer.UNSIGNED_SHORT = 5123;
  30159. /**
  30160. * The integer type.
  30161. */
  30162. VertexBuffer.INT = 5124;
  30163. /**
  30164. * The unsigned integer type.
  30165. */
  30166. VertexBuffer.UNSIGNED_INT = 5125;
  30167. /**
  30168. * The float type.
  30169. */
  30170. VertexBuffer.FLOAT = 5126;
  30171. // Enums
  30172. VertexBuffer._PositionKind = "position";
  30173. VertexBuffer._NormalKind = "normal";
  30174. VertexBuffer._TangentKind = "tangent";
  30175. VertexBuffer._UVKind = "uv";
  30176. VertexBuffer._UV2Kind = "uv2";
  30177. VertexBuffer._UV3Kind = "uv3";
  30178. VertexBuffer._UV4Kind = "uv4";
  30179. VertexBuffer._UV5Kind = "uv5";
  30180. VertexBuffer._UV6Kind = "uv6";
  30181. VertexBuffer._ColorKind = "color";
  30182. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30183. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30184. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30185. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30186. return VertexBuffer;
  30187. }());
  30188. BABYLON.VertexBuffer = VertexBuffer;
  30189. })(BABYLON || (BABYLON = {}));
  30190. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30191. var BABYLON;
  30192. (function (BABYLON) {
  30193. /**
  30194. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30195. */
  30196. var DummyInternalTextureTracker = /** @class */ (function () {
  30197. function DummyInternalTextureTracker() {
  30198. /**
  30199. * Gets or set the previous tracker in the list
  30200. */
  30201. this.previous = null;
  30202. /**
  30203. * Gets or set the next tracker in the list
  30204. */
  30205. this.next = null;
  30206. }
  30207. return DummyInternalTextureTracker;
  30208. }());
  30209. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30210. })(BABYLON || (BABYLON = {}));
  30211. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30212. var BABYLON;
  30213. (function (BABYLON) {
  30214. /**
  30215. * Class used to store data associated with WebGL texture data for the engine
  30216. * This class should not be used directly
  30217. */
  30218. var InternalTexture = /** @class */ (function () {
  30219. /**
  30220. * Creates a new InternalTexture
  30221. * @param engine defines the engine to use
  30222. * @param dataSource defines the type of data that will be used
  30223. */
  30224. function InternalTexture(engine, dataSource) {
  30225. /**
  30226. * Observable called when the texture is loaded
  30227. */
  30228. this.onLoadedObservable = new BABYLON.Observable();
  30229. /**
  30230. * Gets or set the previous tracker in the list
  30231. */
  30232. this.previous = null;
  30233. /**
  30234. * Gets or set the next tracker in the list
  30235. */
  30236. this.next = null;
  30237. // Private
  30238. /** @hidden */
  30239. this._initialSlot = -1;
  30240. /** @hidden */
  30241. this._designatedSlot = -1;
  30242. /** @hidden */
  30243. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30244. /** @hidden */
  30245. this._comparisonFunction = 0;
  30246. /** @hidden */
  30247. this._lodGenerationScale = 0;
  30248. /** @hidden */
  30249. this._lodGenerationOffset = 0;
  30250. /** @hidden */
  30251. this._isRGBD = false;
  30252. /** @hidden */
  30253. this._references = 1;
  30254. this._engine = engine;
  30255. this._dataSource = dataSource;
  30256. this._webGLTexture = engine._createTexture();
  30257. }
  30258. /**
  30259. * Gets the Engine the texture belongs to.
  30260. * @returns The babylon engine
  30261. */
  30262. InternalTexture.prototype.getEngine = function () {
  30263. return this._engine;
  30264. };
  30265. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30266. /**
  30267. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30268. */
  30269. get: function () {
  30270. return this._dataSource;
  30271. },
  30272. enumerable: true,
  30273. configurable: true
  30274. });
  30275. /**
  30276. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30277. */
  30278. InternalTexture.prototype.incrementReferences = function () {
  30279. this._references++;
  30280. };
  30281. /**
  30282. * Change the size of the texture (not the size of the content)
  30283. * @param width defines the new width
  30284. * @param height defines the new height
  30285. * @param depth defines the new depth (1 by default)
  30286. */
  30287. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30288. if (depth === void 0) { depth = 1; }
  30289. this.width = width;
  30290. this.height = height;
  30291. this.depth = depth;
  30292. this.baseWidth = width;
  30293. this.baseHeight = height;
  30294. this.baseDepth = depth;
  30295. this._size = width * height * depth;
  30296. };
  30297. /** @hidden */
  30298. InternalTexture.prototype._rebuild = function () {
  30299. var _this = this;
  30300. var proxy;
  30301. this.isReady = false;
  30302. this._cachedCoordinatesMode = null;
  30303. this._cachedWrapU = null;
  30304. this._cachedWrapV = null;
  30305. this._cachedAnisotropicFilteringLevel = null;
  30306. switch (this._dataSource) {
  30307. case InternalTexture.DATASOURCE_TEMP:
  30308. return;
  30309. case InternalTexture.DATASOURCE_URL:
  30310. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30311. _this.isReady = true;
  30312. }, null, this._buffer, undefined, this.format);
  30313. proxy._swapAndDie(this);
  30314. return;
  30315. case InternalTexture.DATASOURCE_RAW:
  30316. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30317. proxy._swapAndDie(this);
  30318. this.isReady = true;
  30319. return;
  30320. case InternalTexture.DATASOURCE_RAW3D:
  30321. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30322. proxy._swapAndDie(this);
  30323. this.isReady = true;
  30324. return;
  30325. case InternalTexture.DATASOURCE_DYNAMIC:
  30326. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30327. proxy._swapAndDie(this);
  30328. // The engine will make sure to update content so no need to flag it as isReady = true
  30329. return;
  30330. case InternalTexture.DATASOURCE_RENDERTARGET:
  30331. var options = new BABYLON.RenderTargetCreationOptions();
  30332. options.generateDepthBuffer = this._generateDepthBuffer;
  30333. options.generateMipMaps = this.generateMipMaps;
  30334. options.generateStencilBuffer = this._generateStencilBuffer;
  30335. options.samplingMode = this.samplingMode;
  30336. options.type = this.type;
  30337. if (this.isCube) {
  30338. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30339. }
  30340. else {
  30341. var size = {
  30342. width: this.width,
  30343. height: this.height
  30344. };
  30345. proxy = this._engine.createRenderTargetTexture(size, options);
  30346. }
  30347. proxy._swapAndDie(this);
  30348. this.isReady = true;
  30349. return;
  30350. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30351. var depthTextureOptions = {
  30352. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30353. comparisonFunction: this._comparisonFunction,
  30354. generateStencil: this._generateStencilBuffer,
  30355. isCube: this.isCube
  30356. };
  30357. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30358. proxy._swapAndDie(this);
  30359. this.isReady = true;
  30360. return;
  30361. case InternalTexture.DATASOURCE_CUBE:
  30362. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30363. _this.isReady = true;
  30364. }, null, this.format, this._extension);
  30365. proxy._swapAndDie(this);
  30366. return;
  30367. case InternalTexture.DATASOURCE_CUBERAW:
  30368. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30369. proxy._swapAndDie(this);
  30370. this.isReady = true;
  30371. return;
  30372. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30373. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30374. if (proxy) {
  30375. proxy._swapAndDie(_this);
  30376. }
  30377. _this.isReady = true;
  30378. }, null, this.format, this._extension);
  30379. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30380. return;
  30381. }
  30382. };
  30383. InternalTexture.prototype._swapAndDie = function (target) {
  30384. target._webGLTexture = this._webGLTexture;
  30385. if (this._framebuffer) {
  30386. target._framebuffer = this._framebuffer;
  30387. }
  30388. if (this._depthStencilBuffer) {
  30389. target._depthStencilBuffer = this._depthStencilBuffer;
  30390. }
  30391. if (this._lodTextureHigh) {
  30392. if (target._lodTextureHigh) {
  30393. target._lodTextureHigh.dispose();
  30394. }
  30395. target._lodTextureHigh = this._lodTextureHigh;
  30396. }
  30397. if (this._lodTextureMid) {
  30398. if (target._lodTextureMid) {
  30399. target._lodTextureMid.dispose();
  30400. }
  30401. target._lodTextureMid = this._lodTextureMid;
  30402. }
  30403. if (this._lodTextureLow) {
  30404. if (target._lodTextureLow) {
  30405. target._lodTextureLow.dispose();
  30406. }
  30407. target._lodTextureLow = this._lodTextureLow;
  30408. }
  30409. var cache = this._engine.getLoadedTexturesCache();
  30410. var index = cache.indexOf(this);
  30411. if (index !== -1) {
  30412. cache.splice(index, 1);
  30413. }
  30414. };
  30415. /**
  30416. * Dispose the current allocated resources
  30417. */
  30418. InternalTexture.prototype.dispose = function () {
  30419. if (!this._webGLTexture) {
  30420. return;
  30421. }
  30422. this._references--;
  30423. if (this._references === 0) {
  30424. this._engine._releaseTexture(this);
  30425. this._webGLTexture = null;
  30426. this.previous = null;
  30427. this.next = null;
  30428. }
  30429. };
  30430. /**
  30431. * The source of the texture data is unknown
  30432. */
  30433. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30434. /**
  30435. * Texture data comes from an URL
  30436. */
  30437. InternalTexture.DATASOURCE_URL = 1;
  30438. /**
  30439. * Texture data is only used for temporary storage
  30440. */
  30441. InternalTexture.DATASOURCE_TEMP = 2;
  30442. /**
  30443. * Texture data comes from raw data (ArrayBuffer)
  30444. */
  30445. InternalTexture.DATASOURCE_RAW = 3;
  30446. /**
  30447. * Texture content is dynamic (video or dynamic texture)
  30448. */
  30449. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30450. /**
  30451. * Texture content is generated by rendering to it
  30452. */
  30453. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30454. /**
  30455. * Texture content is part of a multi render target process
  30456. */
  30457. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30458. /**
  30459. * Texture data comes from a cube data file
  30460. */
  30461. InternalTexture.DATASOURCE_CUBE = 7;
  30462. /**
  30463. * Texture data comes from a raw cube data
  30464. */
  30465. InternalTexture.DATASOURCE_CUBERAW = 8;
  30466. /**
  30467. * Texture data come from a prefiltered cube data file
  30468. */
  30469. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30470. /**
  30471. * Texture content is raw 3D data
  30472. */
  30473. InternalTexture.DATASOURCE_RAW3D = 10;
  30474. /**
  30475. * Texture content is a depth texture
  30476. */
  30477. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30478. return InternalTexture;
  30479. }());
  30480. BABYLON.InternalTexture = InternalTexture;
  30481. })(BABYLON || (BABYLON = {}));
  30482. //# sourceMappingURL=babylon.internalTexture.js.map
  30483. var BABYLON;
  30484. (function (BABYLON) {
  30485. var BaseTexture = /** @class */ (function () {
  30486. function BaseTexture(scene) {
  30487. this._hasAlpha = false;
  30488. this.getAlphaFromRGB = false;
  30489. this.level = 1;
  30490. this.coordinatesIndex = 0;
  30491. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30492. /**
  30493. * | Value | Type | Description |
  30494. * | ----- | ------------------ | ----------- |
  30495. * | 0 | CLAMP_ADDRESSMODE | |
  30496. * | 1 | WRAP_ADDRESSMODE | |
  30497. * | 2 | MIRROR_ADDRESSMODE | |
  30498. */
  30499. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30500. /**
  30501. * | Value | Type | Description |
  30502. * | ----- | ------------------ | ----------- |
  30503. * | 0 | CLAMP_ADDRESSMODE | |
  30504. * | 1 | WRAP_ADDRESSMODE | |
  30505. * | 2 | MIRROR_ADDRESSMODE | |
  30506. */
  30507. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30508. /**
  30509. * | Value | Type | Description |
  30510. * | ----- | ------------------ | ----------- |
  30511. * | 0 | CLAMP_ADDRESSMODE | |
  30512. * | 1 | WRAP_ADDRESSMODE | |
  30513. * | 2 | MIRROR_ADDRESSMODE | |
  30514. */
  30515. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30516. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30517. this.isCube = false;
  30518. this.is3D = false;
  30519. this.gammaSpace = true;
  30520. this.invertZ = false;
  30521. this.lodLevelInAlpha = false;
  30522. this.isRenderTarget = false;
  30523. this.animations = new Array();
  30524. /**
  30525. * An event triggered when the texture is disposed.
  30526. */
  30527. this.onDisposeObservable = new BABYLON.Observable();
  30528. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30529. this._cachedSize = BABYLON.Size.Zero();
  30530. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30531. if (this._scene) {
  30532. this._scene.textures.push(this);
  30533. }
  30534. this._uid = null;
  30535. }
  30536. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30537. get: function () {
  30538. return this._hasAlpha;
  30539. },
  30540. set: function (value) {
  30541. if (this._hasAlpha === value) {
  30542. return;
  30543. }
  30544. this._hasAlpha = value;
  30545. if (this._scene) {
  30546. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30547. }
  30548. },
  30549. enumerable: true,
  30550. configurable: true
  30551. });
  30552. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30553. get: function () {
  30554. return this._coordinatesMode;
  30555. },
  30556. /**
  30557. * How a texture is mapped.
  30558. *
  30559. * | Value | Type | Description |
  30560. * | ----- | ----------------------------------- | ----------- |
  30561. * | 0 | EXPLICIT_MODE | |
  30562. * | 1 | SPHERICAL_MODE | |
  30563. * | 2 | PLANAR_MODE | |
  30564. * | 3 | CUBIC_MODE | |
  30565. * | 4 | PROJECTION_MODE | |
  30566. * | 5 | SKYBOX_MODE | |
  30567. * | 6 | INVCUBIC_MODE | |
  30568. * | 7 | EQUIRECTANGULAR_MODE | |
  30569. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30570. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30571. */
  30572. set: function (value) {
  30573. if (this._coordinatesMode === value) {
  30574. return;
  30575. }
  30576. this._coordinatesMode = value;
  30577. if (this._scene) {
  30578. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30579. }
  30580. },
  30581. enumerable: true,
  30582. configurable: true
  30583. });
  30584. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30585. /**
  30586. * Gets whether or not the texture contains RGBD data.
  30587. */
  30588. get: function () {
  30589. return this._texture != null && this._texture._isRGBD;
  30590. },
  30591. enumerable: true,
  30592. configurable: true
  30593. });
  30594. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30595. get: function () {
  30596. if (this._texture)
  30597. return this._texture._lodGenerationOffset;
  30598. return 0.0;
  30599. },
  30600. set: function (value) {
  30601. if (this._texture)
  30602. this._texture._lodGenerationOffset = value;
  30603. },
  30604. enumerable: true,
  30605. configurable: true
  30606. });
  30607. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30608. get: function () {
  30609. if (this._texture)
  30610. return this._texture._lodGenerationScale;
  30611. return 0.0;
  30612. },
  30613. set: function (value) {
  30614. if (this._texture)
  30615. this._texture._lodGenerationScale = value;
  30616. },
  30617. enumerable: true,
  30618. configurable: true
  30619. });
  30620. Object.defineProperty(BaseTexture.prototype, "uid", {
  30621. get: function () {
  30622. if (!this._uid) {
  30623. this._uid = BABYLON.Tools.RandomId();
  30624. }
  30625. return this._uid;
  30626. },
  30627. enumerable: true,
  30628. configurable: true
  30629. });
  30630. BaseTexture.prototype.toString = function () {
  30631. return this.name;
  30632. };
  30633. BaseTexture.prototype.getClassName = function () {
  30634. return "BaseTexture";
  30635. };
  30636. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30637. set: function (callback) {
  30638. if (this._onDisposeObserver) {
  30639. this.onDisposeObservable.remove(this._onDisposeObserver);
  30640. }
  30641. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30642. },
  30643. enumerable: true,
  30644. configurable: true
  30645. });
  30646. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30647. get: function () {
  30648. return true;
  30649. },
  30650. enumerable: true,
  30651. configurable: true
  30652. });
  30653. BaseTexture.prototype.getScene = function () {
  30654. return this._scene;
  30655. };
  30656. BaseTexture.prototype.getTextureMatrix = function () {
  30657. return BABYLON.Matrix.IdentityReadOnly;
  30658. };
  30659. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30660. return BABYLON.Matrix.IdentityReadOnly;
  30661. };
  30662. BaseTexture.prototype.getInternalTexture = function () {
  30663. return this._texture;
  30664. };
  30665. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30666. return !this.isBlocking || this.isReady();
  30667. };
  30668. BaseTexture.prototype.isReady = function () {
  30669. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30670. this.delayLoad();
  30671. return false;
  30672. }
  30673. if (this._texture) {
  30674. return this._texture.isReady;
  30675. }
  30676. return false;
  30677. };
  30678. BaseTexture.prototype.getSize = function () {
  30679. if (this._texture) {
  30680. if (this._texture.width) {
  30681. this._cachedSize.width = this._texture.width;
  30682. this._cachedSize.height = this._texture.height;
  30683. return this._cachedSize;
  30684. }
  30685. if (this._texture._size) {
  30686. this._cachedSize.width = this._texture._size;
  30687. this._cachedSize.height = this._texture._size;
  30688. return this._cachedSize;
  30689. }
  30690. }
  30691. return this._cachedSize;
  30692. };
  30693. BaseTexture.prototype.getBaseSize = function () {
  30694. if (!this.isReady() || !this._texture)
  30695. return BABYLON.Size.Zero();
  30696. if (this._texture._size) {
  30697. return new BABYLON.Size(this._texture._size, this._texture._size);
  30698. }
  30699. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30700. };
  30701. BaseTexture.prototype.scale = function (ratio) {
  30702. };
  30703. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30704. get: function () {
  30705. return false;
  30706. },
  30707. enumerable: true,
  30708. configurable: true
  30709. });
  30710. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30711. if (!this._scene) {
  30712. return null;
  30713. }
  30714. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30715. for (var index = 0; index < texturesCache.length; index++) {
  30716. var texturesCacheEntry = texturesCache[index];
  30717. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30718. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30719. texturesCacheEntry.incrementReferences();
  30720. return texturesCacheEntry;
  30721. }
  30722. }
  30723. }
  30724. return null;
  30725. };
  30726. BaseTexture.prototype._rebuild = function () {
  30727. };
  30728. BaseTexture.prototype.delayLoad = function () {
  30729. };
  30730. BaseTexture.prototype.clone = function () {
  30731. return null;
  30732. };
  30733. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30734. get: function () {
  30735. if (!this._texture) {
  30736. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30737. }
  30738. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30739. },
  30740. enumerable: true,
  30741. configurable: true
  30742. });
  30743. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30744. get: function () {
  30745. if (!this._texture) {
  30746. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30747. }
  30748. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30749. },
  30750. enumerable: true,
  30751. configurable: true
  30752. });
  30753. /**
  30754. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30755. * This will returns an RGBA array buffer containing either in values (0-255) or
  30756. * float values (0-1) depending of the underlying buffer type.
  30757. * @param faceIndex The face of the texture to read (in case of cube texture)
  30758. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30759. * @returns The Array buffer containing the pixels data.
  30760. */
  30761. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30762. if (faceIndex === void 0) { faceIndex = 0; }
  30763. if (level === void 0) { level = 0; }
  30764. if (!this._texture) {
  30765. return null;
  30766. }
  30767. var size = this.getSize();
  30768. var width = size.width;
  30769. var height = size.height;
  30770. var scene = this.getScene();
  30771. if (!scene) {
  30772. return null;
  30773. }
  30774. var engine = scene.getEngine();
  30775. if (level != 0) {
  30776. width = width / Math.pow(2, level);
  30777. height = height / Math.pow(2, level);
  30778. width = Math.round(width);
  30779. height = Math.round(height);
  30780. }
  30781. if (this._texture.isCube) {
  30782. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30783. }
  30784. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30785. };
  30786. BaseTexture.prototype.releaseInternalTexture = function () {
  30787. if (this._texture) {
  30788. this._texture.dispose();
  30789. this._texture = null;
  30790. }
  30791. };
  30792. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30793. get: function () {
  30794. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30795. return null;
  30796. }
  30797. if (!this._texture._sphericalPolynomial) {
  30798. this._texture._sphericalPolynomial =
  30799. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30800. }
  30801. return this._texture._sphericalPolynomial;
  30802. },
  30803. set: function (value) {
  30804. if (this._texture) {
  30805. this._texture._sphericalPolynomial = value;
  30806. }
  30807. },
  30808. enumerable: true,
  30809. configurable: true
  30810. });
  30811. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30812. get: function () {
  30813. if (this._texture) {
  30814. return this._texture._lodTextureHigh;
  30815. }
  30816. return null;
  30817. },
  30818. enumerable: true,
  30819. configurable: true
  30820. });
  30821. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30822. get: function () {
  30823. if (this._texture) {
  30824. return this._texture._lodTextureMid;
  30825. }
  30826. return null;
  30827. },
  30828. enumerable: true,
  30829. configurable: true
  30830. });
  30831. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30832. get: function () {
  30833. if (this._texture) {
  30834. return this._texture._lodTextureLow;
  30835. }
  30836. return null;
  30837. },
  30838. enumerable: true,
  30839. configurable: true
  30840. });
  30841. BaseTexture.prototype.dispose = function () {
  30842. if (!this._scene) {
  30843. return;
  30844. }
  30845. // Animations
  30846. this._scene.stopAnimation(this);
  30847. // Remove from scene
  30848. this._scene._removePendingData(this);
  30849. var index = this._scene.textures.indexOf(this);
  30850. if (index >= 0) {
  30851. this._scene.textures.splice(index, 1);
  30852. }
  30853. if (this._texture === undefined) {
  30854. return;
  30855. }
  30856. // Release
  30857. this.releaseInternalTexture();
  30858. // Callback
  30859. this.onDisposeObservable.notifyObservers(this);
  30860. this.onDisposeObservable.clear();
  30861. };
  30862. BaseTexture.prototype.serialize = function () {
  30863. if (!this.name) {
  30864. return null;
  30865. }
  30866. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30867. // Animations
  30868. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30869. return serializationObject;
  30870. };
  30871. BaseTexture.WhenAllReady = function (textures, callback) {
  30872. var numRemaining = textures.length;
  30873. if (numRemaining === 0) {
  30874. callback();
  30875. return;
  30876. }
  30877. var _loop_1 = function () {
  30878. texture = textures[i];
  30879. if (texture.isReady()) {
  30880. if (--numRemaining === 0) {
  30881. callback();
  30882. }
  30883. }
  30884. else {
  30885. onLoadObservable = texture.onLoadObservable;
  30886. var onLoadCallback_1 = function () {
  30887. onLoadObservable.removeCallback(onLoadCallback_1);
  30888. if (--numRemaining === 0) {
  30889. callback();
  30890. }
  30891. };
  30892. onLoadObservable.add(onLoadCallback_1);
  30893. }
  30894. };
  30895. var texture, onLoadObservable;
  30896. for (var i = 0; i < textures.length; i++) {
  30897. _loop_1();
  30898. }
  30899. };
  30900. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30901. __decorate([
  30902. BABYLON.serialize()
  30903. ], BaseTexture.prototype, "name", void 0);
  30904. __decorate([
  30905. BABYLON.serialize("hasAlpha")
  30906. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30907. __decorate([
  30908. BABYLON.serialize()
  30909. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30910. __decorate([
  30911. BABYLON.serialize()
  30912. ], BaseTexture.prototype, "level", void 0);
  30913. __decorate([
  30914. BABYLON.serialize()
  30915. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30916. __decorate([
  30917. BABYLON.serialize("coordinatesMode")
  30918. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30919. __decorate([
  30920. BABYLON.serialize()
  30921. ], BaseTexture.prototype, "wrapU", void 0);
  30922. __decorate([
  30923. BABYLON.serialize()
  30924. ], BaseTexture.prototype, "wrapV", void 0);
  30925. __decorate([
  30926. BABYLON.serialize()
  30927. ], BaseTexture.prototype, "wrapR", void 0);
  30928. __decorate([
  30929. BABYLON.serialize()
  30930. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30931. __decorate([
  30932. BABYLON.serialize()
  30933. ], BaseTexture.prototype, "isCube", void 0);
  30934. __decorate([
  30935. BABYLON.serialize()
  30936. ], BaseTexture.prototype, "is3D", void 0);
  30937. __decorate([
  30938. BABYLON.serialize()
  30939. ], BaseTexture.prototype, "gammaSpace", void 0);
  30940. __decorate([
  30941. BABYLON.serialize()
  30942. ], BaseTexture.prototype, "invertZ", void 0);
  30943. __decorate([
  30944. BABYLON.serialize()
  30945. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30946. __decorate([
  30947. BABYLON.serialize()
  30948. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30949. __decorate([
  30950. BABYLON.serialize()
  30951. ], BaseTexture.prototype, "lodGenerationScale", null);
  30952. __decorate([
  30953. BABYLON.serialize()
  30954. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30955. return BaseTexture;
  30956. }());
  30957. BABYLON.BaseTexture = BaseTexture;
  30958. })(BABYLON || (BABYLON = {}));
  30959. //# sourceMappingURL=babylon.baseTexture.js.map
  30960. var BABYLON;
  30961. (function (BABYLON) {
  30962. var Texture = /** @class */ (function (_super) {
  30963. __extends(Texture, _super);
  30964. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30965. if (noMipmap === void 0) { noMipmap = false; }
  30966. if (invertY === void 0) { invertY = true; }
  30967. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30968. if (onLoad === void 0) { onLoad = null; }
  30969. if (onError === void 0) { onError = null; }
  30970. if (buffer === void 0) { buffer = null; }
  30971. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30972. var _this = _super.call(this, scene) || this;
  30973. _this.uOffset = 0;
  30974. _this.vOffset = 0;
  30975. _this.uScale = 1.0;
  30976. _this.vScale = 1.0;
  30977. _this.uAng = 0;
  30978. _this.vAng = 0;
  30979. _this.wAng = 0;
  30980. /**
  30981. * Defines the center of rotation (U)
  30982. */
  30983. _this.uRotationCenter = 0.5;
  30984. /**
  30985. * Defines the center of rotation (V)
  30986. */
  30987. _this.vRotationCenter = 0.5;
  30988. /**
  30989. * Defines the center of rotation (W)
  30990. */
  30991. _this.wRotationCenter = 0.5;
  30992. _this._isBlocking = true;
  30993. _this.name = url || "";
  30994. _this.url = url;
  30995. _this._noMipmap = noMipmap;
  30996. _this._invertY = invertY;
  30997. _this._samplingMode = samplingMode;
  30998. _this._buffer = buffer;
  30999. _this._deleteBuffer = deleteBuffer;
  31000. if (format) {
  31001. _this._format = format;
  31002. }
  31003. scene = _this.getScene();
  31004. if (!scene) {
  31005. return _this;
  31006. }
  31007. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31008. var load = function () {
  31009. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  31010. _this.onLoadObservable.notifyObservers(_this);
  31011. }
  31012. if (onLoad) {
  31013. onLoad();
  31014. }
  31015. if (!_this.isBlocking && scene) {
  31016. scene.resetCachedMaterial();
  31017. }
  31018. };
  31019. if (!_this.url) {
  31020. _this._delayedOnLoad = load;
  31021. _this._delayedOnError = onError;
  31022. return _this;
  31023. }
  31024. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31025. if (!_this._texture) {
  31026. if (!scene.useDelayedTextureLoading) {
  31027. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31028. if (deleteBuffer) {
  31029. delete _this._buffer;
  31030. }
  31031. }
  31032. else {
  31033. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31034. _this._delayedOnLoad = load;
  31035. _this._delayedOnError = onError;
  31036. }
  31037. }
  31038. else {
  31039. if (_this._texture.isReady) {
  31040. BABYLON.Tools.SetImmediate(function () { return load(); });
  31041. }
  31042. else {
  31043. _this._texture.onLoadedObservable.add(load);
  31044. }
  31045. }
  31046. return _this;
  31047. }
  31048. Object.defineProperty(Texture.prototype, "noMipmap", {
  31049. get: function () {
  31050. return this._noMipmap;
  31051. },
  31052. enumerable: true,
  31053. configurable: true
  31054. });
  31055. Object.defineProperty(Texture.prototype, "isBlocking", {
  31056. get: function () {
  31057. return this._isBlocking;
  31058. },
  31059. set: function (value) {
  31060. this._isBlocking = value;
  31061. },
  31062. enumerable: true,
  31063. configurable: true
  31064. });
  31065. Object.defineProperty(Texture.prototype, "samplingMode", {
  31066. get: function () {
  31067. return this._samplingMode;
  31068. },
  31069. enumerable: true,
  31070. configurable: true
  31071. });
  31072. /**
  31073. * Update the url (and optional buffer) of this texture if url was null during construction.
  31074. * @param url the url of the texture
  31075. * @param buffer the buffer of the texture (defaults to null)
  31076. */
  31077. Texture.prototype.updateURL = function (url, buffer) {
  31078. if (buffer === void 0) { buffer = null; }
  31079. if (this.url) {
  31080. throw new Error("URL is already set");
  31081. }
  31082. this.url = url;
  31083. this._buffer = buffer;
  31084. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31085. this.delayLoad();
  31086. };
  31087. Texture.prototype.delayLoad = function () {
  31088. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31089. return;
  31090. }
  31091. var scene = this.getScene();
  31092. if (!scene) {
  31093. return;
  31094. }
  31095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31096. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31097. if (!this._texture) {
  31098. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31099. if (this._deleteBuffer) {
  31100. delete this._buffer;
  31101. }
  31102. }
  31103. else {
  31104. if (this._delayedOnLoad) {
  31105. if (this._texture.isReady) {
  31106. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31107. }
  31108. else {
  31109. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31110. }
  31111. }
  31112. }
  31113. this._delayedOnLoad = null;
  31114. this._delayedOnError = null;
  31115. };
  31116. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31117. if (!this._texture) {
  31118. return;
  31119. }
  31120. var scene = this.getScene();
  31121. if (!scene) {
  31122. return;
  31123. }
  31124. this._samplingMode = samplingMode;
  31125. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31126. };
  31127. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31128. x *= this.uScale;
  31129. y *= this.vScale;
  31130. x -= this.uRotationCenter * this.uScale;
  31131. y -= this.vRotationCenter * this.vScale;
  31132. z -= this.wRotationCenter;
  31133. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31134. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31135. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31136. t.z += this.wRotationCenter;
  31137. };
  31138. Texture.prototype.getTextureMatrix = function () {
  31139. var _this = this;
  31140. if (this.uOffset === this._cachedUOffset &&
  31141. this.vOffset === this._cachedVOffset &&
  31142. this.uScale === this._cachedUScale &&
  31143. this.vScale === this._cachedVScale &&
  31144. this.uAng === this._cachedUAng &&
  31145. this.vAng === this._cachedVAng &&
  31146. this.wAng === this._cachedWAng) {
  31147. return this._cachedTextureMatrix;
  31148. }
  31149. this._cachedUOffset = this.uOffset;
  31150. this._cachedVOffset = this.vOffset;
  31151. this._cachedUScale = this.uScale;
  31152. this._cachedVScale = this.vScale;
  31153. this._cachedUAng = this.uAng;
  31154. this._cachedVAng = this.vAng;
  31155. this._cachedWAng = this.wAng;
  31156. if (!this._cachedTextureMatrix) {
  31157. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31158. this._rowGenerationMatrix = new BABYLON.Matrix();
  31159. this._t0 = BABYLON.Vector3.Zero();
  31160. this._t1 = BABYLON.Vector3.Zero();
  31161. this._t2 = BABYLON.Vector3.Zero();
  31162. }
  31163. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31164. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31165. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31166. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31167. this._t1.subtractInPlace(this._t0);
  31168. this._t2.subtractInPlace(this._t0);
  31169. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31170. this._cachedTextureMatrix.m[0] = this._t1.x;
  31171. this._cachedTextureMatrix.m[1] = this._t1.y;
  31172. this._cachedTextureMatrix.m[2] = this._t1.z;
  31173. this._cachedTextureMatrix.m[4] = this._t2.x;
  31174. this._cachedTextureMatrix.m[5] = this._t2.y;
  31175. this._cachedTextureMatrix.m[6] = this._t2.z;
  31176. this._cachedTextureMatrix.m[8] = this._t0.x;
  31177. this._cachedTextureMatrix.m[9] = this._t0.y;
  31178. this._cachedTextureMatrix.m[10] = this._t0.z;
  31179. var scene = this.getScene();
  31180. if (!scene) {
  31181. return this._cachedTextureMatrix;
  31182. }
  31183. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31184. return mat.hasTexture(_this);
  31185. });
  31186. return this._cachedTextureMatrix;
  31187. };
  31188. Texture.prototype.getReflectionTextureMatrix = function () {
  31189. var _this = this;
  31190. var scene = this.getScene();
  31191. if (!scene) {
  31192. return this._cachedTextureMatrix;
  31193. }
  31194. if (this.uOffset === this._cachedUOffset &&
  31195. this.vOffset === this._cachedVOffset &&
  31196. this.uScale === this._cachedUScale &&
  31197. this.vScale === this._cachedVScale &&
  31198. this.coordinatesMode === this._cachedCoordinatesMode) {
  31199. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31200. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31201. return this._cachedTextureMatrix;
  31202. }
  31203. }
  31204. else {
  31205. return this._cachedTextureMatrix;
  31206. }
  31207. }
  31208. if (!this._cachedTextureMatrix) {
  31209. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31210. }
  31211. if (!this._projectionModeMatrix) {
  31212. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31213. }
  31214. this._cachedUOffset = this.uOffset;
  31215. this._cachedVOffset = this.vOffset;
  31216. this._cachedUScale = this.uScale;
  31217. this._cachedVScale = this.vScale;
  31218. this._cachedCoordinatesMode = this.coordinatesMode;
  31219. switch (this.coordinatesMode) {
  31220. case Texture.PLANAR_MODE:
  31221. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31222. this._cachedTextureMatrix[0] = this.uScale;
  31223. this._cachedTextureMatrix[5] = this.vScale;
  31224. this._cachedTextureMatrix[12] = this.uOffset;
  31225. this._cachedTextureMatrix[13] = this.vOffset;
  31226. break;
  31227. case Texture.PROJECTION_MODE:
  31228. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31229. this._projectionModeMatrix.m[0] = 0.5;
  31230. this._projectionModeMatrix.m[5] = -0.5;
  31231. this._projectionModeMatrix.m[10] = 0.0;
  31232. this._projectionModeMatrix.m[12] = 0.5;
  31233. this._projectionModeMatrix.m[13] = 0.5;
  31234. this._projectionModeMatrix.m[14] = 1.0;
  31235. this._projectionModeMatrix.m[15] = 1.0;
  31236. var projectionMatrix = scene.getProjectionMatrix();
  31237. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31238. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31239. break;
  31240. default:
  31241. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31242. break;
  31243. }
  31244. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31245. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31246. });
  31247. return this._cachedTextureMatrix;
  31248. };
  31249. Texture.prototype.clone = function () {
  31250. var _this = this;
  31251. return BABYLON.SerializationHelper.Clone(function () {
  31252. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31253. }, this);
  31254. };
  31255. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31256. get: function () {
  31257. if (!this._onLoadObservable) {
  31258. this._onLoadObservable = new BABYLON.Observable();
  31259. }
  31260. return this._onLoadObservable;
  31261. },
  31262. enumerable: true,
  31263. configurable: true
  31264. });
  31265. Texture.prototype.serialize = function () {
  31266. var serializationObject = _super.prototype.serialize.call(this);
  31267. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31268. serializationObject.base64String = this._buffer;
  31269. serializationObject.name = serializationObject.name.replace("data:", "");
  31270. }
  31271. serializationObject.invertY = this._invertY;
  31272. serializationObject.samplingMode = this.samplingMode;
  31273. return serializationObject;
  31274. };
  31275. Texture.prototype.getClassName = function () {
  31276. return "Texture";
  31277. };
  31278. Texture.prototype.dispose = function () {
  31279. _super.prototype.dispose.call(this);
  31280. if (this._onLoadObservable) {
  31281. this._onLoadObservable.clear();
  31282. this._onLoadObservable = null;
  31283. }
  31284. this._delayedOnLoad = null;
  31285. this._delayedOnError = null;
  31286. };
  31287. // Statics
  31288. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31289. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31290. if (onLoad === void 0) { onLoad = null; }
  31291. if (onError === void 0) { onError = null; }
  31292. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31293. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31294. };
  31295. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31296. if (parsedTexture.customType) {
  31297. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31298. // Update Sampling Mode
  31299. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31300. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31301. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31302. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31303. }
  31304. }
  31305. return parsedCustomTexture;
  31306. }
  31307. if (parsedTexture.isCube) {
  31308. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31309. }
  31310. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31311. return null;
  31312. }
  31313. var texture = BABYLON.SerializationHelper.Parse(function () {
  31314. var generateMipMaps = true;
  31315. if (parsedTexture.noMipmap) {
  31316. generateMipMaps = false;
  31317. }
  31318. if (parsedTexture.mirrorPlane) {
  31319. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31320. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31321. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31322. return mirrorTexture;
  31323. }
  31324. else if (parsedTexture.isRenderTarget) {
  31325. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31326. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31327. return renderTargetTexture;
  31328. }
  31329. else {
  31330. var texture;
  31331. if (parsedTexture.base64String) {
  31332. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31333. }
  31334. else {
  31335. var url = rootUrl + parsedTexture.name;
  31336. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31337. url = parsedTexture.url;
  31338. }
  31339. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31340. }
  31341. return texture;
  31342. }
  31343. }, parsedTexture, scene);
  31344. // Update Sampling Mode
  31345. if (parsedTexture.samplingMode) {
  31346. var sampling = parsedTexture.samplingMode;
  31347. if (texture._samplingMode !== sampling) {
  31348. texture.updateSamplingMode(sampling);
  31349. }
  31350. }
  31351. // Animations
  31352. if (parsedTexture.animations) {
  31353. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31354. var parsedAnimation = parsedTexture.animations[animationIndex];
  31355. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31356. }
  31357. }
  31358. return texture;
  31359. };
  31360. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31361. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31362. if (noMipmap === void 0) { noMipmap = false; }
  31363. if (invertY === void 0) { invertY = true; }
  31364. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31365. if (onLoad === void 0) { onLoad = null; }
  31366. if (onError === void 0) { onError = null; }
  31367. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31368. if (name.substr(0, 5) !== "data:") {
  31369. name = "data:" + name;
  31370. }
  31371. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31372. };
  31373. // Constants
  31374. Texture.NEAREST_SAMPLINGMODE = 1;
  31375. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31376. Texture.BILINEAR_SAMPLINGMODE = 2;
  31377. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31378. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31379. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31380. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31381. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31382. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31383. Texture.NEAREST_LINEAR = 7;
  31384. Texture.NEAREST_NEAREST = 8;
  31385. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31386. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31387. Texture.LINEAR_LINEAR = 11;
  31388. Texture.LINEAR_NEAREST = 12;
  31389. Texture.EXPLICIT_MODE = 0;
  31390. Texture.SPHERICAL_MODE = 1;
  31391. Texture.PLANAR_MODE = 2;
  31392. Texture.CUBIC_MODE = 3;
  31393. Texture.PROJECTION_MODE = 4;
  31394. Texture.SKYBOX_MODE = 5;
  31395. Texture.INVCUBIC_MODE = 6;
  31396. Texture.EQUIRECTANGULAR_MODE = 7;
  31397. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31398. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31399. Texture.CLAMP_ADDRESSMODE = 0;
  31400. Texture.WRAP_ADDRESSMODE = 1;
  31401. Texture.MIRROR_ADDRESSMODE = 2;
  31402. /**
  31403. * 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
  31404. */
  31405. Texture.UseSerializedUrlIfAny = false;
  31406. __decorate([
  31407. BABYLON.serialize()
  31408. ], Texture.prototype, "url", void 0);
  31409. __decorate([
  31410. BABYLON.serialize()
  31411. ], Texture.prototype, "uOffset", void 0);
  31412. __decorate([
  31413. BABYLON.serialize()
  31414. ], Texture.prototype, "vOffset", void 0);
  31415. __decorate([
  31416. BABYLON.serialize()
  31417. ], Texture.prototype, "uScale", void 0);
  31418. __decorate([
  31419. BABYLON.serialize()
  31420. ], Texture.prototype, "vScale", void 0);
  31421. __decorate([
  31422. BABYLON.serialize()
  31423. ], Texture.prototype, "uAng", void 0);
  31424. __decorate([
  31425. BABYLON.serialize()
  31426. ], Texture.prototype, "vAng", void 0);
  31427. __decorate([
  31428. BABYLON.serialize()
  31429. ], Texture.prototype, "wAng", void 0);
  31430. __decorate([
  31431. BABYLON.serialize()
  31432. ], Texture.prototype, "uRotationCenter", void 0);
  31433. __decorate([
  31434. BABYLON.serialize()
  31435. ], Texture.prototype, "vRotationCenter", void 0);
  31436. __decorate([
  31437. BABYLON.serialize()
  31438. ], Texture.prototype, "wRotationCenter", void 0);
  31439. __decorate([
  31440. BABYLON.serialize()
  31441. ], Texture.prototype, "isBlocking", null);
  31442. return Texture;
  31443. }(BABYLON.BaseTexture));
  31444. BABYLON.Texture = Texture;
  31445. })(BABYLON || (BABYLON = {}));
  31446. //# sourceMappingURL=babylon.texture.js.map
  31447. var BABYLON;
  31448. (function (BABYLON) {
  31449. /**
  31450. * @hidden
  31451. **/
  31452. var _InstancesBatch = /** @class */ (function () {
  31453. function _InstancesBatch() {
  31454. this.mustReturn = false;
  31455. this.visibleInstances = new Array();
  31456. this.renderSelf = new Array();
  31457. }
  31458. return _InstancesBatch;
  31459. }());
  31460. BABYLON._InstancesBatch = _InstancesBatch;
  31461. var Mesh = /** @class */ (function (_super) {
  31462. __extends(Mesh, _super);
  31463. /**
  31464. * @constructor
  31465. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31466. * @param {Scene} scene The scene to add this mesh to.
  31467. * @param {Node} parent The parent of this mesh, if it has one
  31468. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31469. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31470. * When false, achieved by calling a clone(), also passing False.
  31471. * This will make creation of children, recursive.
  31472. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31473. */
  31474. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31475. if (scene === void 0) { scene = null; }
  31476. if (parent === void 0) { parent = null; }
  31477. if (source === void 0) { source = null; }
  31478. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31479. var _this = _super.call(this, name, scene) || this;
  31480. // Events
  31481. /**
  31482. * An event triggered before rendering the mesh
  31483. */
  31484. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31485. /**
  31486. * An event triggered after rendering the mesh
  31487. */
  31488. _this.onAfterRenderObservable = new BABYLON.Observable();
  31489. /**
  31490. * An event triggered before drawing the mesh
  31491. */
  31492. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31493. // Members
  31494. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31495. _this.instances = new Array();
  31496. _this._LODLevels = new Array();
  31497. _this._visibleInstances = {};
  31498. _this._renderIdForInstances = new Array();
  31499. _this._batchCache = new _InstancesBatch();
  31500. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31501. // Use by builder only to know what orientation were the mesh build in.
  31502. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31503. _this.overrideMaterialSideOrientation = null;
  31504. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31505. // Will be used to save a source mesh reference, If any
  31506. _this._source = null;
  31507. scene = _this.getScene();
  31508. if (source) {
  31509. // Geometry
  31510. if (source._geometry) {
  31511. source._geometry.applyToMesh(_this);
  31512. }
  31513. // Deep copy
  31514. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31515. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31516. // Source mesh
  31517. _this._source = source;
  31518. // Metadata
  31519. if (source.metadata && source.metadata.clone) {
  31520. _this.metadata = source.metadata.clone();
  31521. }
  31522. else {
  31523. _this.metadata = source.metadata;
  31524. }
  31525. // Tags
  31526. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31527. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31528. }
  31529. // Parent
  31530. _this.parent = source.parent;
  31531. // Pivot
  31532. _this.setPivotMatrix(source.getPivotMatrix());
  31533. _this.id = name + "." + source.id;
  31534. // Material
  31535. _this.material = source.material;
  31536. var index;
  31537. if (!doNotCloneChildren) {
  31538. // Children
  31539. var directDescendants = source.getDescendants(true);
  31540. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31541. var child = directDescendants[index_1];
  31542. if (child.clone) {
  31543. child.clone(name + "." + child.name, _this);
  31544. }
  31545. }
  31546. }
  31547. // Physics clone
  31548. var physicsEngine = _this.getScene().getPhysicsEngine();
  31549. if (clonePhysicsImpostor && physicsEngine) {
  31550. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31551. if (impostor) {
  31552. _this.physicsImpostor = impostor.clone(_this);
  31553. }
  31554. }
  31555. // Particles
  31556. for (index = 0; index < scene.particleSystems.length; index++) {
  31557. var system = scene.particleSystems[index];
  31558. if (system.emitter === source) {
  31559. system.clone(system.name, _this);
  31560. }
  31561. }
  31562. _this.refreshBoundingInfo();
  31563. _this.computeWorldMatrix(true);
  31564. }
  31565. // Parent
  31566. if (parent !== null) {
  31567. _this.parent = parent;
  31568. }
  31569. return _this;
  31570. }
  31571. Object.defineProperty(Mesh, "FRONTSIDE", {
  31572. /**
  31573. * Mesh side orientation : usually the external or front surface
  31574. */
  31575. get: function () {
  31576. return Mesh._FRONTSIDE;
  31577. },
  31578. enumerable: true,
  31579. configurable: true
  31580. });
  31581. Object.defineProperty(Mesh, "BACKSIDE", {
  31582. /**
  31583. * Mesh side orientation : usually the internal or back surface
  31584. */
  31585. get: function () {
  31586. return Mesh._BACKSIDE;
  31587. },
  31588. enumerable: true,
  31589. configurable: true
  31590. });
  31591. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31592. /**
  31593. * Mesh side orientation : both internal and external or front and back surfaces
  31594. */
  31595. get: function () {
  31596. return Mesh._DOUBLESIDE;
  31597. },
  31598. enumerable: true,
  31599. configurable: true
  31600. });
  31601. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31602. /**
  31603. * Mesh side orientation : by default, `FRONTSIDE`
  31604. */
  31605. get: function () {
  31606. return Mesh._DEFAULTSIDE;
  31607. },
  31608. enumerable: true,
  31609. configurable: true
  31610. });
  31611. Object.defineProperty(Mesh, "NO_CAP", {
  31612. /**
  31613. * Mesh cap setting : no cap
  31614. */
  31615. get: function () {
  31616. return Mesh._NO_CAP;
  31617. },
  31618. enumerable: true,
  31619. configurable: true
  31620. });
  31621. Object.defineProperty(Mesh, "CAP_START", {
  31622. /**
  31623. * Mesh cap setting : one cap at the beginning of the mesh
  31624. */
  31625. get: function () {
  31626. return Mesh._CAP_START;
  31627. },
  31628. enumerable: true,
  31629. configurable: true
  31630. });
  31631. Object.defineProperty(Mesh, "CAP_END", {
  31632. /**
  31633. * Mesh cap setting : one cap at the end of the mesh
  31634. */
  31635. get: function () {
  31636. return Mesh._CAP_END;
  31637. },
  31638. enumerable: true,
  31639. configurable: true
  31640. });
  31641. Object.defineProperty(Mesh, "CAP_ALL", {
  31642. /**
  31643. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31644. */
  31645. get: function () {
  31646. return Mesh._CAP_ALL;
  31647. },
  31648. enumerable: true,
  31649. configurable: true
  31650. });
  31651. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31652. set: function (callback) {
  31653. if (this._onBeforeDrawObserver) {
  31654. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31655. }
  31656. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31657. },
  31658. enumerable: true,
  31659. configurable: true
  31660. });
  31661. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31662. get: function () {
  31663. return this._morphTargetManager;
  31664. },
  31665. set: function (value) {
  31666. if (this._morphTargetManager === value) {
  31667. return;
  31668. }
  31669. this._morphTargetManager = value;
  31670. this._syncGeometryWithMorphTargetManager();
  31671. },
  31672. enumerable: true,
  31673. configurable: true
  31674. });
  31675. Object.defineProperty(Mesh.prototype, "source", {
  31676. get: function () {
  31677. return this._source;
  31678. },
  31679. enumerable: true,
  31680. configurable: true
  31681. });
  31682. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31683. get: function () {
  31684. return this._unIndexed;
  31685. },
  31686. set: function (value) {
  31687. if (this._unIndexed !== value) {
  31688. this._unIndexed = value;
  31689. this._markSubMeshesAsAttributesDirty();
  31690. }
  31691. },
  31692. enumerable: true,
  31693. configurable: true
  31694. });
  31695. // Methods
  31696. /**
  31697. * Returns the string "Mesh".
  31698. */
  31699. Mesh.prototype.getClassName = function () {
  31700. return "Mesh";
  31701. };
  31702. /**
  31703. * Returns a string.
  31704. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31705. */
  31706. Mesh.prototype.toString = function (fullDetails) {
  31707. var ret = _super.prototype.toString.call(this, fullDetails);
  31708. ret += ", n vertices: " + this.getTotalVertices();
  31709. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31710. if (this.animations) {
  31711. for (var i = 0; i < this.animations.length; i++) {
  31712. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31713. }
  31714. }
  31715. if (fullDetails) {
  31716. if (this._geometry) {
  31717. var ib = this.getIndices();
  31718. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31719. if (vb && ib) {
  31720. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31721. }
  31722. }
  31723. else {
  31724. ret += ", flat shading: UNKNOWN";
  31725. }
  31726. }
  31727. return ret;
  31728. };
  31729. Mesh.prototype._unBindEffect = function () {
  31730. _super.prototype._unBindEffect.call(this);
  31731. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31732. var instance = _a[_i];
  31733. instance._unBindEffect();
  31734. }
  31735. };
  31736. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31737. /**
  31738. * True if the mesh has some Levels Of Details (LOD).
  31739. * Returns a boolean.
  31740. */
  31741. get: function () {
  31742. return this._LODLevels.length > 0;
  31743. },
  31744. enumerable: true,
  31745. configurable: true
  31746. });
  31747. /**
  31748. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31749. * @returns an array of {BABYLON.MeshLODLevel}
  31750. */
  31751. Mesh.prototype.getLODLevels = function () {
  31752. return this._LODLevels;
  31753. };
  31754. Mesh.prototype._sortLODLevels = function () {
  31755. this._LODLevels.sort(function (a, b) {
  31756. if (a.distance < b.distance) {
  31757. return 1;
  31758. }
  31759. if (a.distance > b.distance) {
  31760. return -1;
  31761. }
  31762. return 0;
  31763. });
  31764. };
  31765. /**
  31766. * Add a mesh as LOD level triggered at the given distance.
  31767. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31768. * @param distance The distance from the center of the object to show this level
  31769. * @param mesh The mesh to be added as LOD level (can be null)
  31770. * @return This mesh (for chaining)
  31771. */
  31772. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31773. if (mesh && mesh._masterMesh) {
  31774. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31775. return this;
  31776. }
  31777. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31778. this._LODLevels.push(level);
  31779. if (mesh) {
  31780. mesh._masterMesh = this;
  31781. }
  31782. this._sortLODLevels();
  31783. return this;
  31784. };
  31785. /**
  31786. * Returns the LOD level mesh at the passed distance or null if not found.
  31787. * It is related to the method `addLODLevel(distance, mesh)`.
  31788. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31789. * Returns an object Mesh or `null`.
  31790. */
  31791. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31792. for (var index = 0; index < this._LODLevels.length; index++) {
  31793. var level = this._LODLevels[index];
  31794. if (level.distance === distance) {
  31795. return level.mesh;
  31796. }
  31797. }
  31798. return null;
  31799. };
  31800. /**
  31801. * Remove a mesh from the LOD array
  31802. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31803. * @param {Mesh} mesh The mesh to be removed.
  31804. * @return {Mesh} This mesh (for chaining)
  31805. */
  31806. Mesh.prototype.removeLODLevel = function (mesh) {
  31807. for (var index = 0; index < this._LODLevels.length; index++) {
  31808. if (this._LODLevels[index].mesh === mesh) {
  31809. this._LODLevels.splice(index, 1);
  31810. if (mesh) {
  31811. mesh._masterMesh = null;
  31812. }
  31813. }
  31814. }
  31815. this._sortLODLevels();
  31816. return this;
  31817. };
  31818. /**
  31819. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31820. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31821. */
  31822. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31823. if (!this._LODLevels || this._LODLevels.length === 0) {
  31824. return this;
  31825. }
  31826. var bSphere;
  31827. if (boundingSphere) {
  31828. bSphere = boundingSphere;
  31829. }
  31830. else {
  31831. var boundingInfo = this.getBoundingInfo();
  31832. bSphere = boundingInfo.boundingSphere;
  31833. }
  31834. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31835. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31836. if (this.onLODLevelSelection) {
  31837. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31838. }
  31839. return this;
  31840. }
  31841. for (var index = 0; index < this._LODLevels.length; index++) {
  31842. var level = this._LODLevels[index];
  31843. if (level.distance < distanceToCamera) {
  31844. if (level.mesh) {
  31845. level.mesh._preActivate();
  31846. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31847. }
  31848. if (this.onLODLevelSelection) {
  31849. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31850. }
  31851. return level.mesh;
  31852. }
  31853. }
  31854. if (this.onLODLevelSelection) {
  31855. this.onLODLevelSelection(distanceToCamera, this, this);
  31856. }
  31857. return this;
  31858. };
  31859. Object.defineProperty(Mesh.prototype, "geometry", {
  31860. /**
  31861. * Returns the mesh internal Geometry object.
  31862. */
  31863. get: function () {
  31864. return this._geometry;
  31865. },
  31866. enumerable: true,
  31867. configurable: true
  31868. });
  31869. /**
  31870. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31871. */
  31872. Mesh.prototype.getTotalVertices = function () {
  31873. if (this._geometry === null || this._geometry === undefined) {
  31874. return 0;
  31875. }
  31876. return this._geometry.getTotalVertices();
  31877. };
  31878. /**
  31879. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31880. * 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.
  31881. * You can force the copy with forceCopy === true
  31882. * Returns null if the mesh has no geometry or no vertex buffer.
  31883. * Possible `kind` values :
  31884. * - BABYLON.VertexBuffer.PositionKind
  31885. * - BABYLON.VertexBuffer.UVKind
  31886. * - BABYLON.VertexBuffer.UV2Kind
  31887. * - BABYLON.VertexBuffer.UV3Kind
  31888. * - BABYLON.VertexBuffer.UV4Kind
  31889. * - BABYLON.VertexBuffer.UV5Kind
  31890. * - BABYLON.VertexBuffer.UV6Kind
  31891. * - BABYLON.VertexBuffer.ColorKind
  31892. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31893. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31894. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31895. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31896. */
  31897. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31898. if (!this._geometry) {
  31899. return null;
  31900. }
  31901. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31902. };
  31903. /**
  31904. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31905. * Returns `null` if the mesh has no geometry.
  31906. * Possible `kind` values :
  31907. * - BABYLON.VertexBuffer.PositionKind
  31908. * - BABYLON.VertexBuffer.UVKind
  31909. * - BABYLON.VertexBuffer.UV2Kind
  31910. * - BABYLON.VertexBuffer.UV3Kind
  31911. * - BABYLON.VertexBuffer.UV4Kind
  31912. * - BABYLON.VertexBuffer.UV5Kind
  31913. * - BABYLON.VertexBuffer.UV6Kind
  31914. * - BABYLON.VertexBuffer.ColorKind
  31915. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31916. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31917. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31918. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31919. */
  31920. Mesh.prototype.getVertexBuffer = function (kind) {
  31921. if (!this._geometry) {
  31922. return null;
  31923. }
  31924. return this._geometry.getVertexBuffer(kind);
  31925. };
  31926. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31927. if (!this._geometry) {
  31928. if (this._delayInfo) {
  31929. return this._delayInfo.indexOf(kind) !== -1;
  31930. }
  31931. return false;
  31932. }
  31933. return this._geometry.isVerticesDataPresent(kind);
  31934. };
  31935. /**
  31936. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31937. * Possible `kind` values :
  31938. * - BABYLON.VertexBuffer.PositionKind
  31939. * - BABYLON.VertexBuffer.UVKind
  31940. * - BABYLON.VertexBuffer.UV2Kind
  31941. * - BABYLON.VertexBuffer.UV3Kind
  31942. * - BABYLON.VertexBuffer.UV4Kind
  31943. * - BABYLON.VertexBuffer.UV5Kind
  31944. * - BABYLON.VertexBuffer.UV6Kind
  31945. * - BABYLON.VertexBuffer.ColorKind
  31946. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31947. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31948. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31949. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31950. */
  31951. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31952. if (!this._geometry) {
  31953. if (this._delayInfo) {
  31954. return this._delayInfo.indexOf(kind) !== -1;
  31955. }
  31956. return false;
  31957. }
  31958. return this._geometry.isVertexBufferUpdatable(kind);
  31959. };
  31960. /**
  31961. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31962. * Possible `kind` values :
  31963. * - BABYLON.VertexBuffer.PositionKind
  31964. * - BABYLON.VertexBuffer.UVKind
  31965. * - BABYLON.VertexBuffer.UV2Kind
  31966. * - BABYLON.VertexBuffer.UV3Kind
  31967. * - BABYLON.VertexBuffer.UV4Kind
  31968. * - BABYLON.VertexBuffer.UV5Kind
  31969. * - BABYLON.VertexBuffer.UV6Kind
  31970. * - BABYLON.VertexBuffer.ColorKind
  31971. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31972. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31973. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31974. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31975. */
  31976. Mesh.prototype.getVerticesDataKinds = function () {
  31977. if (!this._geometry) {
  31978. var result = new Array();
  31979. if (this._delayInfo) {
  31980. this._delayInfo.forEach(function (kind, index, array) {
  31981. result.push(kind);
  31982. });
  31983. }
  31984. return result;
  31985. }
  31986. return this._geometry.getVerticesDataKinds();
  31987. };
  31988. /**
  31989. * Returns a positive integer : the total number of indices in this mesh geometry.
  31990. * Returns zero if the mesh has no geometry.
  31991. */
  31992. Mesh.prototype.getTotalIndices = function () {
  31993. if (!this._geometry) {
  31994. return 0;
  31995. }
  31996. return this._geometry.getTotalIndices();
  31997. };
  31998. /**
  31999. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32000. * 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.
  32001. * Returns an empty array if the mesh has no geometry.
  32002. */
  32003. Mesh.prototype.getIndices = function (copyWhenShared) {
  32004. if (!this._geometry) {
  32005. return [];
  32006. }
  32007. return this._geometry.getIndices(copyWhenShared);
  32008. };
  32009. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32010. get: function () {
  32011. return this._masterMesh !== null && this._masterMesh !== undefined;
  32012. },
  32013. enumerable: true,
  32014. configurable: true
  32015. });
  32016. /**
  32017. * Determine if the current mesh is ready to be rendered
  32018. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32019. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32020. * @returns true if all associated assets are ready (material, textures, shaders)
  32021. */
  32022. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32023. if (completeCheck === void 0) { completeCheck = false; }
  32024. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32025. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32026. return false;
  32027. }
  32028. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32029. return false;
  32030. }
  32031. if (!this.subMeshes || this.subMeshes.length === 0) {
  32032. return true;
  32033. }
  32034. if (!completeCheck) {
  32035. return true;
  32036. }
  32037. var engine = this.getEngine();
  32038. var scene = this.getScene();
  32039. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32040. this.computeWorldMatrix();
  32041. var mat = this.material || scene.defaultMaterial;
  32042. if (mat) {
  32043. if (mat.storeEffectOnSubMeshes) {
  32044. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32045. var subMesh = _a[_i];
  32046. var effectiveMaterial = subMesh.getMaterial();
  32047. if (effectiveMaterial) {
  32048. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32049. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32050. return false;
  32051. }
  32052. }
  32053. else {
  32054. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32055. return false;
  32056. }
  32057. }
  32058. }
  32059. }
  32060. }
  32061. else {
  32062. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32063. return false;
  32064. }
  32065. }
  32066. }
  32067. // Shadows
  32068. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32069. var light = _c[_b];
  32070. var generator = light.getShadowGenerator();
  32071. if (generator) {
  32072. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32073. var subMesh = _e[_d];
  32074. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32075. return false;
  32076. }
  32077. }
  32078. }
  32079. }
  32080. // LOD
  32081. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32082. var lod = _g[_f];
  32083. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32084. return false;
  32085. }
  32086. }
  32087. return true;
  32088. };
  32089. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32090. /**
  32091. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32092. * This property is pertinent only for updatable parametric shapes.
  32093. */
  32094. get: function () {
  32095. return this._areNormalsFrozen;
  32096. },
  32097. enumerable: true,
  32098. configurable: true
  32099. });
  32100. /**
  32101. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32102. * It has no effect at all on other shapes.
  32103. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32104. * Returns the Mesh.
  32105. */
  32106. Mesh.prototype.freezeNormals = function () {
  32107. this._areNormalsFrozen = true;
  32108. return this;
  32109. };
  32110. /**
  32111. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32112. * It has no effect at all on other shapes.
  32113. * It reactivates the mesh normals computation if it was previously frozen.
  32114. * Returns the Mesh.
  32115. */
  32116. Mesh.prototype.unfreezeNormals = function () {
  32117. this._areNormalsFrozen = false;
  32118. return this;
  32119. };
  32120. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32121. /**
  32122. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32123. */
  32124. set: function (count) {
  32125. this._overridenInstanceCount = count;
  32126. },
  32127. enumerable: true,
  32128. configurable: true
  32129. });
  32130. // Methods
  32131. Mesh.prototype._preActivate = function () {
  32132. var sceneRenderId = this.getScene().getRenderId();
  32133. if (this._preActivateId === sceneRenderId) {
  32134. return this;
  32135. }
  32136. this._preActivateId = sceneRenderId;
  32137. this._visibleInstances = null;
  32138. return this;
  32139. };
  32140. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32141. if (this._visibleInstances) {
  32142. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32143. }
  32144. return this;
  32145. };
  32146. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32147. if (!this._visibleInstances) {
  32148. this._visibleInstances = {};
  32149. this._visibleInstances.defaultRenderId = renderId;
  32150. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32151. }
  32152. if (!this._visibleInstances[renderId]) {
  32153. this._visibleInstances[renderId] = new Array();
  32154. }
  32155. this._visibleInstances[renderId].push(instance);
  32156. return this;
  32157. };
  32158. /**
  32159. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32160. * This means the mesh underlying bounding box and sphere are recomputed.
  32161. * Returns the Mesh.
  32162. */
  32163. Mesh.prototype.refreshBoundingInfo = function () {
  32164. return this._refreshBoundingInfo(false);
  32165. };
  32166. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32167. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32168. return this;
  32169. }
  32170. var data = this._getPositionData(applySkeleton);
  32171. if (data) {
  32172. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32173. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32174. }
  32175. if (this.subMeshes) {
  32176. for (var index = 0; index < this.subMeshes.length; index++) {
  32177. this.subMeshes[index].refreshBoundingInfo();
  32178. }
  32179. }
  32180. this._updateBoundingInfo();
  32181. return this;
  32182. };
  32183. Mesh.prototype._getPositionData = function (applySkeleton) {
  32184. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32185. if (data && applySkeleton && this.skeleton) {
  32186. data = BABYLON.Tools.Slice(data);
  32187. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32188. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32189. if (matricesWeightsData && matricesIndicesData) {
  32190. var needExtras = this.numBoneInfluencers > 4;
  32191. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32192. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32193. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32194. var tempVector = BABYLON.Tmp.Vector3[0];
  32195. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32196. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32197. var matWeightIdx = 0;
  32198. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32199. finalMatrix.reset();
  32200. var inf;
  32201. var weight;
  32202. for (inf = 0; inf < 4; inf++) {
  32203. weight = matricesWeightsData[matWeightIdx + inf];
  32204. if (weight <= 0)
  32205. break;
  32206. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32207. finalMatrix.addToSelf(tempMatrix);
  32208. }
  32209. if (needExtras) {
  32210. for (inf = 0; inf < 4; inf++) {
  32211. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32212. if (weight <= 0)
  32213. break;
  32214. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32215. finalMatrix.addToSelf(tempMatrix);
  32216. }
  32217. }
  32218. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32219. tempVector.toArray(data, index);
  32220. }
  32221. }
  32222. }
  32223. return data;
  32224. };
  32225. Mesh.prototype._createGlobalSubMesh = function (force) {
  32226. var totalVertices = this.getTotalVertices();
  32227. if (!totalVertices || !this.getIndices()) {
  32228. return null;
  32229. }
  32230. // Check if we need to recreate the submeshes
  32231. if (this.subMeshes && this.subMeshes.length > 0) {
  32232. var ib = this.getIndices();
  32233. if (!ib) {
  32234. return null;
  32235. }
  32236. var totalIndices = ib.length;
  32237. var needToRecreate = false;
  32238. if (force) {
  32239. needToRecreate = true;
  32240. }
  32241. else {
  32242. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32243. var submesh = _a[_i];
  32244. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32245. needToRecreate = true;
  32246. break;
  32247. }
  32248. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32249. needToRecreate = true;
  32250. break;
  32251. }
  32252. }
  32253. }
  32254. if (!needToRecreate) {
  32255. return this.subMeshes[0];
  32256. }
  32257. }
  32258. this.releaseSubMeshes();
  32259. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32260. };
  32261. Mesh.prototype.subdivide = function (count) {
  32262. if (count < 1) {
  32263. return;
  32264. }
  32265. var totalIndices = this.getTotalIndices();
  32266. var subdivisionSize = (totalIndices / count) | 0;
  32267. var offset = 0;
  32268. // Ensure that subdivisionSize is a multiple of 3
  32269. while (subdivisionSize % 3 !== 0) {
  32270. subdivisionSize++;
  32271. }
  32272. this.releaseSubMeshes();
  32273. for (var index = 0; index < count; index++) {
  32274. if (offset >= totalIndices) {
  32275. break;
  32276. }
  32277. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32278. offset += subdivisionSize;
  32279. }
  32280. this.synchronizeInstances();
  32281. };
  32282. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32283. if (updatable === void 0) { updatable = false; }
  32284. if (!this._geometry) {
  32285. var vertexData = new BABYLON.VertexData();
  32286. vertexData.set(data, kind);
  32287. var scene = this.getScene();
  32288. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32289. }
  32290. else {
  32291. this._geometry.setVerticesData(kind, data, updatable, stride);
  32292. }
  32293. return this;
  32294. };
  32295. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32296. if (updatable === void 0) { updatable = true; }
  32297. var vb = this.getVertexBuffer(kind);
  32298. if (!vb || vb.isUpdatable() === updatable) {
  32299. return;
  32300. }
  32301. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32302. };
  32303. /**
  32304. * Sets the mesh VertexBuffer.
  32305. * Returns the Mesh.
  32306. */
  32307. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32308. if (!this._geometry) {
  32309. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32310. }
  32311. this._geometry.setVerticesBuffer(buffer);
  32312. return this;
  32313. };
  32314. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32315. if (!this._geometry) {
  32316. return this;
  32317. }
  32318. if (!makeItUnique) {
  32319. this._geometry.updateVerticesData(kind, data, updateExtends);
  32320. }
  32321. else {
  32322. this.makeGeometryUnique();
  32323. this.updateVerticesData(kind, data, updateExtends, false);
  32324. }
  32325. return this;
  32326. };
  32327. /**
  32328. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32329. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32330. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32331. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32332. * Returns the Mesh.
  32333. */
  32334. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32335. if (computeNormals === void 0) { computeNormals = true; }
  32336. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32337. if (!positions) {
  32338. return this;
  32339. }
  32340. positionFunction(positions);
  32341. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32342. if (computeNormals) {
  32343. var indices = this.getIndices();
  32344. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32345. if (!normals) {
  32346. return this;
  32347. }
  32348. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32349. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32350. }
  32351. return this;
  32352. };
  32353. /**
  32354. * Creates a un-shared specific occurence of the geometry for the mesh.
  32355. * Returns the Mesh.
  32356. */
  32357. Mesh.prototype.makeGeometryUnique = function () {
  32358. if (!this._geometry) {
  32359. return this;
  32360. }
  32361. var oldGeometry = this._geometry;
  32362. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32363. oldGeometry.releaseForMesh(this, true);
  32364. geometry.applyToMesh(this);
  32365. return this;
  32366. };
  32367. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32368. if (totalVertices === void 0) { totalVertices = null; }
  32369. if (updatable === void 0) { updatable = false; }
  32370. if (!this._geometry) {
  32371. var vertexData = new BABYLON.VertexData();
  32372. vertexData.indices = indices;
  32373. var scene = this.getScene();
  32374. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32375. }
  32376. else {
  32377. this._geometry.setIndices(indices, totalVertices, updatable);
  32378. }
  32379. return this;
  32380. };
  32381. /**
  32382. * Update the current index buffer
  32383. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32384. * Returns the Mesh.
  32385. */
  32386. Mesh.prototype.updateIndices = function (indices, offset) {
  32387. if (!this._geometry) {
  32388. return this;
  32389. }
  32390. this._geometry.updateIndices(indices, offset);
  32391. return this;
  32392. };
  32393. /**
  32394. * Invert the geometry to move from a right handed system to a left handed one.
  32395. * Returns the Mesh.
  32396. */
  32397. Mesh.prototype.toLeftHanded = function () {
  32398. if (!this._geometry) {
  32399. return this;
  32400. }
  32401. this._geometry.toLeftHanded();
  32402. return this;
  32403. };
  32404. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32405. if (!this._geometry) {
  32406. return this;
  32407. }
  32408. var engine = this.getScene().getEngine();
  32409. // Wireframe
  32410. var indexToBind;
  32411. if (this._unIndexed) {
  32412. indexToBind = null;
  32413. }
  32414. else {
  32415. switch (fillMode) {
  32416. case BABYLON.Material.PointFillMode:
  32417. indexToBind = null;
  32418. break;
  32419. case BABYLON.Material.WireFrameFillMode:
  32420. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32421. break;
  32422. default:
  32423. case BABYLON.Material.TriangleFillMode:
  32424. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32425. break;
  32426. }
  32427. }
  32428. // VBOs
  32429. this._geometry._bind(effect, indexToBind);
  32430. return this;
  32431. };
  32432. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32433. if (alternate === void 0) { alternate = false; }
  32434. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32435. return this;
  32436. }
  32437. this.onBeforeDrawObservable.notifyObservers(this);
  32438. var scene = this.getScene();
  32439. var engine = scene.getEngine();
  32440. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32441. // or triangles as points
  32442. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32443. }
  32444. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32445. // Triangles as wireframe
  32446. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32447. }
  32448. else {
  32449. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32450. }
  32451. if (scene._isAlternateRenderingEnabled && !alternate) {
  32452. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32453. if (!effect || !scene.activeCamera) {
  32454. return this;
  32455. }
  32456. scene._switchToAlternateCameraConfiguration(true);
  32457. this._effectiveMaterial.bindView(effect);
  32458. this._effectiveMaterial.bindViewProjection(effect);
  32459. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32460. this._draw(subMesh, fillMode, instancesCount, true);
  32461. engine.setViewport(scene.activeCamera.viewport);
  32462. scene._switchToAlternateCameraConfiguration(false);
  32463. this._effectiveMaterial.bindView(effect);
  32464. this._effectiveMaterial.bindViewProjection(effect);
  32465. }
  32466. return this;
  32467. };
  32468. /**
  32469. * Registers for this mesh a javascript function called just before the rendering process.
  32470. * This function is passed the current mesh.
  32471. * Return the Mesh.
  32472. */
  32473. Mesh.prototype.registerBeforeRender = function (func) {
  32474. this.onBeforeRenderObservable.add(func);
  32475. return this;
  32476. };
  32477. /**
  32478. * Disposes a previously registered javascript function called before the rendering.
  32479. * This function is passed the current mesh.
  32480. * Returns the Mesh.
  32481. */
  32482. Mesh.prototype.unregisterBeforeRender = function (func) {
  32483. this.onBeforeRenderObservable.removeCallback(func);
  32484. return this;
  32485. };
  32486. /**
  32487. * Registers for this mesh a javascript function called just after the rendering is complete.
  32488. * This function is passed the current mesh.
  32489. * Returns the Mesh.
  32490. */
  32491. Mesh.prototype.registerAfterRender = function (func) {
  32492. this.onAfterRenderObservable.add(func);
  32493. return this;
  32494. };
  32495. /**
  32496. * Disposes a previously registered javascript function called after the rendering.
  32497. * This function is passed the current mesh.
  32498. * Return the Mesh.
  32499. */
  32500. Mesh.prototype.unregisterAfterRender = function (func) {
  32501. this.onAfterRenderObservable.removeCallback(func);
  32502. return this;
  32503. };
  32504. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32505. var scene = this.getScene();
  32506. this._batchCache.mustReturn = false;
  32507. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32508. this._batchCache.visibleInstances[subMeshId] = null;
  32509. if (this._visibleInstances) {
  32510. var currentRenderId = scene.getRenderId();
  32511. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32512. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32513. var selfRenderId = this._renderId;
  32514. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32515. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32516. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32517. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32518. }
  32519. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32520. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32521. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32522. this._batchCache.mustReturn = true;
  32523. return this._batchCache;
  32524. }
  32525. if (currentRenderId !== selfRenderId) {
  32526. this._batchCache.renderSelf[subMeshId] = false;
  32527. }
  32528. }
  32529. this._renderIdForInstances[subMeshId] = currentRenderId;
  32530. }
  32531. return this._batchCache;
  32532. };
  32533. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32534. var visibleInstances = batch.visibleInstances[subMesh._id];
  32535. if (!visibleInstances) {
  32536. return this;
  32537. }
  32538. var matricesCount = visibleInstances.length + 1;
  32539. var bufferSize = matricesCount * 16 * 4;
  32540. var currentInstancesBufferSize = this._instancesBufferSize;
  32541. var instancesBuffer = this._instancesBuffer;
  32542. while (this._instancesBufferSize < bufferSize) {
  32543. this._instancesBufferSize *= 2;
  32544. }
  32545. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32546. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32547. }
  32548. var offset = 0;
  32549. var instancesCount = 0;
  32550. var world = this.getWorldMatrix();
  32551. if (batch.renderSelf[subMesh._id]) {
  32552. world.copyToArray(this._instancesData, offset);
  32553. offset += 16;
  32554. instancesCount++;
  32555. }
  32556. if (visibleInstances) {
  32557. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32558. var instance = visibleInstances[instanceIndex];
  32559. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32560. offset += 16;
  32561. instancesCount++;
  32562. }
  32563. }
  32564. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32565. if (instancesBuffer) {
  32566. instancesBuffer.dispose();
  32567. }
  32568. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32569. this._instancesBuffer = instancesBuffer;
  32570. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32571. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32572. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32573. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32574. }
  32575. else {
  32576. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32577. }
  32578. this._bind(subMesh, effect, fillMode);
  32579. this._draw(subMesh, fillMode, instancesCount);
  32580. engine.unbindInstanceAttributes();
  32581. return this;
  32582. };
  32583. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32584. var scene = this.getScene();
  32585. var engine = scene.getEngine();
  32586. if (hardwareInstancedRendering) {
  32587. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32588. }
  32589. else {
  32590. if (batch.renderSelf[subMesh._id]) {
  32591. // Draw
  32592. if (onBeforeDraw) {
  32593. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32594. }
  32595. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32596. }
  32597. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32598. if (visibleInstancesForSubMesh) {
  32599. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32600. var instance = visibleInstancesForSubMesh[instanceIndex];
  32601. // World
  32602. var world = instance.getWorldMatrix();
  32603. if (onBeforeDraw) {
  32604. onBeforeDraw(true, world, effectiveMaterial);
  32605. }
  32606. // Draw
  32607. this._draw(subMesh, fillMode);
  32608. }
  32609. }
  32610. }
  32611. return this;
  32612. };
  32613. /**
  32614. * Triggers the draw call for the mesh.
  32615. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32616. * Returns the Mesh.
  32617. */
  32618. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32619. this._checkOcclusionQuery();
  32620. if (this._isOccluded) {
  32621. return this;
  32622. }
  32623. var scene = this.getScene();
  32624. // Managing instances
  32625. var batch = this._getInstancesRenderList(subMesh._id);
  32626. if (batch.mustReturn) {
  32627. return this;
  32628. }
  32629. // Checking geometry state
  32630. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32631. return this;
  32632. }
  32633. this.onBeforeRenderObservable.notifyObservers(this);
  32634. var engine = scene.getEngine();
  32635. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32636. // Material
  32637. var material = subMesh.getMaterial();
  32638. if (!material) {
  32639. return this;
  32640. }
  32641. this._effectiveMaterial = material;
  32642. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32643. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32644. return this;
  32645. }
  32646. }
  32647. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32648. return this;
  32649. }
  32650. // Alpha mode
  32651. if (enableAlphaMode) {
  32652. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32653. }
  32654. // Outline - step 1
  32655. var savedDepthWrite = engine.getDepthWrite();
  32656. if (this.renderOutline) {
  32657. engine.setDepthWrite(false);
  32658. scene.getOutlineRenderer().render(subMesh, batch);
  32659. engine.setDepthWrite(savedDepthWrite);
  32660. }
  32661. var effect;
  32662. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32663. effect = subMesh.effect;
  32664. }
  32665. else {
  32666. effect = this._effectiveMaterial.getEffect();
  32667. }
  32668. if (!effect) {
  32669. return this;
  32670. }
  32671. var sideOrientation = this.overrideMaterialSideOrientation;
  32672. if (sideOrientation == null) {
  32673. sideOrientation = this._effectiveMaterial.sideOrientation;
  32674. if (this._getWorldMatrixDeterminant() < 0) {
  32675. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32676. }
  32677. }
  32678. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32679. if (this._effectiveMaterial.forceDepthWrite) {
  32680. engine.setDepthWrite(true);
  32681. }
  32682. // Bind
  32683. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32684. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32685. this._bind(subMesh, effect, fillMode);
  32686. }
  32687. var world = this.getWorldMatrix();
  32688. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32689. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32690. }
  32691. else {
  32692. this._effectiveMaterial.bind(world, this);
  32693. }
  32694. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32695. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32696. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32697. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32698. }
  32699. // Draw
  32700. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32701. // Unbind
  32702. this._effectiveMaterial.unbind();
  32703. // Outline - step 2
  32704. if (this.renderOutline && savedDepthWrite) {
  32705. engine.setDepthWrite(true);
  32706. engine.setColorWrite(false);
  32707. scene.getOutlineRenderer().render(subMesh, batch);
  32708. engine.setColorWrite(true);
  32709. }
  32710. // Overlay
  32711. if (this.renderOverlay) {
  32712. var currentMode = engine.getAlphaMode();
  32713. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32714. scene.getOutlineRenderer().render(subMesh, batch, true);
  32715. engine.setAlphaMode(currentMode);
  32716. }
  32717. this.onAfterRenderObservable.notifyObservers(this);
  32718. return this;
  32719. };
  32720. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32721. if (isInstance && effectiveMaterial) {
  32722. effectiveMaterial.bindOnlyWorldMatrix(world);
  32723. }
  32724. };
  32725. /**
  32726. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32727. */
  32728. Mesh.prototype.getEmittedParticleSystems = function () {
  32729. var results = new Array();
  32730. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32731. var particleSystem = this.getScene().particleSystems[index];
  32732. if (particleSystem.emitter === this) {
  32733. results.push(particleSystem);
  32734. }
  32735. }
  32736. return results;
  32737. };
  32738. /**
  32739. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32740. */
  32741. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32742. var results = new Array();
  32743. var descendants = this.getDescendants();
  32744. descendants.push(this);
  32745. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32746. var particleSystem = this.getScene().particleSystems[index];
  32747. var emitter = particleSystem.emitter;
  32748. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32749. results.push(particleSystem);
  32750. }
  32751. }
  32752. return results;
  32753. };
  32754. /**
  32755. * Normalize matrix weights so that all vertices have a total weight set to 1
  32756. */
  32757. Mesh.prototype.cleanMatrixWeights = function () {
  32758. var epsilon = 1e-3;
  32759. var noInfluenceBoneIndex = 0.0;
  32760. if (this.skeleton) {
  32761. noInfluenceBoneIndex = this.skeleton.bones.length;
  32762. }
  32763. else {
  32764. return;
  32765. }
  32766. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32767. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32768. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32769. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32770. var influencers = this.numBoneInfluencers;
  32771. var size = matricesWeights.length;
  32772. for (var i = 0; i < size; i += 4) {
  32773. var weight = 0.0;
  32774. var firstZeroWeight = -1;
  32775. for (var j = 0; j < 4; j++) {
  32776. var w = matricesWeights[i + j];
  32777. weight += w;
  32778. if (w < epsilon && firstZeroWeight < 0) {
  32779. firstZeroWeight = j;
  32780. }
  32781. }
  32782. if (matricesWeightsExtra) {
  32783. for (var j = 0; j < 4; j++) {
  32784. var w = matricesWeightsExtra[i + j];
  32785. weight += w;
  32786. if (w < epsilon && firstZeroWeight < 0) {
  32787. firstZeroWeight = j + 4;
  32788. }
  32789. }
  32790. }
  32791. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32792. firstZeroWeight = influencers - 1;
  32793. }
  32794. if (weight > epsilon) {
  32795. var mweight = 1.0 / weight;
  32796. for (var j = 0; j < 4; j++) {
  32797. matricesWeights[i + j] *= mweight;
  32798. }
  32799. if (matricesWeightsExtra) {
  32800. for (var j = 0; j < 4; j++) {
  32801. matricesWeightsExtra[i + j] *= mweight;
  32802. }
  32803. }
  32804. }
  32805. else {
  32806. if (firstZeroWeight >= 4) {
  32807. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32808. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32809. }
  32810. else {
  32811. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32812. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32813. }
  32814. }
  32815. }
  32816. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32817. if (matricesIndicesExtra) {
  32818. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32819. }
  32820. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32821. if (matricesWeightsExtra) {
  32822. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32823. }
  32824. };
  32825. Mesh.prototype._checkDelayState = function () {
  32826. var scene = this.getScene();
  32827. if (this._geometry) {
  32828. this._geometry.load(scene);
  32829. }
  32830. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32831. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32832. this._queueLoad(scene);
  32833. }
  32834. return this;
  32835. };
  32836. Mesh.prototype._queueLoad = function (scene) {
  32837. var _this = this;
  32838. scene._addPendingData(this);
  32839. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32840. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32841. if (data instanceof ArrayBuffer) {
  32842. _this._delayLoadingFunction(data, _this);
  32843. }
  32844. else {
  32845. _this._delayLoadingFunction(JSON.parse(data), _this);
  32846. }
  32847. _this.instances.forEach(function (instance) {
  32848. instance._syncSubMeshes();
  32849. });
  32850. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32851. scene._removePendingData(_this);
  32852. }, function () { }, scene.database, getBinaryData);
  32853. return this;
  32854. };
  32855. /**
  32856. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32857. */
  32858. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32859. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32860. return false;
  32861. }
  32862. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32863. return false;
  32864. }
  32865. this._checkDelayState();
  32866. return true;
  32867. };
  32868. /**
  32869. * Sets the mesh material by the material or multiMaterial `id` property.
  32870. * The material `id` is a string identifying the material or the multiMaterial.
  32871. * This method returns the Mesh.
  32872. */
  32873. Mesh.prototype.setMaterialByID = function (id) {
  32874. var materials = this.getScene().materials;
  32875. var index;
  32876. for (index = materials.length - 1; index > -1; index--) {
  32877. if (materials[index].id === id) {
  32878. this.material = materials[index];
  32879. return this;
  32880. }
  32881. }
  32882. // Multi
  32883. var multiMaterials = this.getScene().multiMaterials;
  32884. for (index = multiMaterials.length - 1; index > -1; index--) {
  32885. if (multiMaterials[index].id === id) {
  32886. this.material = multiMaterials[index];
  32887. return this;
  32888. }
  32889. }
  32890. return this;
  32891. };
  32892. /**
  32893. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32894. */
  32895. Mesh.prototype.getAnimatables = function () {
  32896. var results = new Array();
  32897. if (this.material) {
  32898. results.push(this.material);
  32899. }
  32900. if (this.skeleton) {
  32901. results.push(this.skeleton);
  32902. }
  32903. return results;
  32904. };
  32905. /**
  32906. * Modifies the mesh geometry according to the passed transformation matrix.
  32907. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32908. * The mesh normals are modified accordingly the same transformation.
  32909. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32910. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32911. * Returns the Mesh.
  32912. */
  32913. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32914. // Position
  32915. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32916. return this;
  32917. }
  32918. var submeshes = this.subMeshes.splice(0);
  32919. this._resetPointsArrayCache();
  32920. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32921. var temp = new Array();
  32922. var index;
  32923. for (index = 0; index < data.length; index += 3) {
  32924. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32925. }
  32926. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32927. // Normals
  32928. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32929. return this;
  32930. }
  32931. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32932. temp = [];
  32933. for (index = 0; index < data.length; index += 3) {
  32934. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32935. }
  32936. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32937. // flip faces?
  32938. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32939. this.flipFaces();
  32940. }
  32941. // Restore submeshes
  32942. this.releaseSubMeshes();
  32943. this.subMeshes = submeshes;
  32944. return this;
  32945. };
  32946. /**
  32947. * Modifies the mesh geometry according to its own current World Matrix.
  32948. * The mesh World Matrix is then reset.
  32949. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32950. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32951. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32952. * Returns the Mesh.
  32953. */
  32954. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32955. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32956. this.scaling.copyFromFloats(1, 1, 1);
  32957. this.position.copyFromFloats(0, 0, 0);
  32958. this.rotation.copyFromFloats(0, 0, 0);
  32959. //only if quaternion is already set
  32960. if (this.rotationQuaternion) {
  32961. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32962. }
  32963. this._worldMatrix = BABYLON.Matrix.Identity();
  32964. return this;
  32965. };
  32966. Object.defineProperty(Mesh.prototype, "_positions", {
  32967. // Cache
  32968. get: function () {
  32969. if (this._geometry) {
  32970. return this._geometry._positions;
  32971. }
  32972. return null;
  32973. },
  32974. enumerable: true,
  32975. configurable: true
  32976. });
  32977. Mesh.prototype._resetPointsArrayCache = function () {
  32978. if (this._geometry) {
  32979. this._geometry._resetPointsArrayCache();
  32980. }
  32981. return this;
  32982. };
  32983. Mesh.prototype._generatePointsArray = function () {
  32984. if (this._geometry) {
  32985. return this._geometry._generatePointsArray();
  32986. }
  32987. return false;
  32988. };
  32989. /**
  32990. * Returns a new Mesh object generated from the current mesh properties.
  32991. * This method must not get confused with createInstance().
  32992. * The parameter `name` is a string, the name given to the new mesh.
  32993. * The optional parameter `newParent` can be any Node object (default `null`).
  32994. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32995. * 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.
  32996. */
  32997. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32998. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32999. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33000. };
  33001. /**
  33002. * Releases resources associated with this mesh.
  33003. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33004. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33005. */
  33006. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33007. var _this = this;
  33008. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33009. this.morphTargetManager = null;
  33010. if (this._geometry) {
  33011. this._geometry.releaseForMesh(this, true);
  33012. }
  33013. // Sources
  33014. var meshes = this.getScene().meshes;
  33015. meshes.forEach(function (abstractMesh) {
  33016. var mesh = abstractMesh;
  33017. if (mesh._source && mesh._source === _this) {
  33018. mesh._source = null;
  33019. }
  33020. });
  33021. this._source = null;
  33022. // Instances
  33023. if (this._instancesBuffer) {
  33024. this._instancesBuffer.dispose();
  33025. this._instancesBuffer = null;
  33026. }
  33027. while (this.instances.length) {
  33028. this.instances[0].dispose();
  33029. }
  33030. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33031. };
  33032. /**
  33033. * Modifies the mesh geometry according to a displacement map.
  33034. * 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.
  33035. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33036. * This method returns nothing.
  33037. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  33038. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33039. * 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.
  33040. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33041. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33042. *
  33043. * Returns the Mesh.
  33044. */
  33045. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  33046. var _this = this;
  33047. var scene = this.getScene();
  33048. var onload = function (img) {
  33049. // Getting height map data
  33050. var canvas = document.createElement("canvas");
  33051. var context = canvas.getContext("2d");
  33052. var heightMapWidth = img.width;
  33053. var heightMapHeight = img.height;
  33054. canvas.width = heightMapWidth;
  33055. canvas.height = heightMapHeight;
  33056. context.drawImage(img, 0, 0);
  33057. // Create VertexData from map data
  33058. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33059. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33060. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33061. //execute success callback, if set
  33062. if (onSuccess) {
  33063. onSuccess(_this);
  33064. }
  33065. };
  33066. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33067. return this;
  33068. };
  33069. /**
  33070. * Modifies the mesh geometry according to a displacementMap buffer.
  33071. * 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.
  33072. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33073. * This method returns nothing.
  33074. * 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.
  33075. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33076. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33077. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33078. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33079. *
  33080. * Returns the Mesh.
  33081. */
  33082. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33083. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33084. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33085. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33086. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33087. return this;
  33088. }
  33089. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33090. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33091. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33092. var position = BABYLON.Vector3.Zero();
  33093. var normal = BABYLON.Vector3.Zero();
  33094. var uv = BABYLON.Vector2.Zero();
  33095. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33096. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33097. for (var index = 0; index < positions.length; index += 3) {
  33098. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33099. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33100. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33101. // Compute height
  33102. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33103. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33104. var pos = (u + v * heightMapWidth) * 4;
  33105. var r = buffer[pos] / 255.0;
  33106. var g = buffer[pos + 1] / 255.0;
  33107. var b = buffer[pos + 2] / 255.0;
  33108. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33109. normal.normalize();
  33110. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33111. position = position.add(normal);
  33112. position.toArray(positions, index);
  33113. }
  33114. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33115. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33116. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33117. return this;
  33118. };
  33119. /**
  33120. * Modify the mesh to get a flat shading rendering.
  33121. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33122. * This method returns the Mesh.
  33123. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33124. */
  33125. Mesh.prototype.convertToFlatShadedMesh = function () {
  33126. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33127. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33128. var kinds = this.getVerticesDataKinds();
  33129. var vbs = {};
  33130. var data = {};
  33131. var newdata = {};
  33132. var updatableNormals = false;
  33133. var kindIndex;
  33134. var kind;
  33135. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33136. kind = kinds[kindIndex];
  33137. var vertexBuffer = this.getVertexBuffer(kind);
  33138. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33139. updatableNormals = vertexBuffer.isUpdatable();
  33140. kinds.splice(kindIndex, 1);
  33141. kindIndex--;
  33142. continue;
  33143. }
  33144. vbs[kind] = vertexBuffer;
  33145. data[kind] = vbs[kind].getData();
  33146. newdata[kind] = [];
  33147. }
  33148. // Save previous submeshes
  33149. var previousSubmeshes = this.subMeshes.slice(0);
  33150. var indices = this.getIndices();
  33151. var totalIndices = this.getTotalIndices();
  33152. // Generating unique vertices per face
  33153. var index;
  33154. for (index = 0; index < totalIndices; index++) {
  33155. var vertexIndex = indices[index];
  33156. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33157. kind = kinds[kindIndex];
  33158. var stride = vbs[kind].getStrideSize();
  33159. for (var offset = 0; offset < stride; offset++) {
  33160. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33161. }
  33162. }
  33163. }
  33164. // Updating faces & normal
  33165. var normals = [];
  33166. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33167. for (index = 0; index < totalIndices; index += 3) {
  33168. indices[index] = index;
  33169. indices[index + 1] = index + 1;
  33170. indices[index + 2] = index + 2;
  33171. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33172. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33173. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33174. var p1p2 = p1.subtract(p2);
  33175. var p3p2 = p3.subtract(p2);
  33176. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33177. // Store same normals for every vertex
  33178. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33179. normals.push(normal.x);
  33180. normals.push(normal.y);
  33181. normals.push(normal.z);
  33182. }
  33183. }
  33184. this.setIndices(indices);
  33185. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33186. // Updating vertex buffers
  33187. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33188. kind = kinds[kindIndex];
  33189. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33190. }
  33191. // Updating submeshes
  33192. this.releaseSubMeshes();
  33193. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33194. var previousOne = previousSubmeshes[submeshIndex];
  33195. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33196. }
  33197. this.synchronizeInstances();
  33198. return this;
  33199. };
  33200. /**
  33201. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33202. * In other words, more vertices, no more indices and a single bigger VBO.
  33203. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33204. * Returns the Mesh.
  33205. */
  33206. Mesh.prototype.convertToUnIndexedMesh = function () {
  33207. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33208. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33209. var kinds = this.getVerticesDataKinds();
  33210. var vbs = {};
  33211. var data = {};
  33212. var newdata = {};
  33213. var kindIndex;
  33214. var kind;
  33215. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33216. kind = kinds[kindIndex];
  33217. var vertexBuffer = this.getVertexBuffer(kind);
  33218. vbs[kind] = vertexBuffer;
  33219. data[kind] = vbs[kind].getData();
  33220. newdata[kind] = [];
  33221. }
  33222. // Save previous submeshes
  33223. var previousSubmeshes = this.subMeshes.slice(0);
  33224. var indices = this.getIndices();
  33225. var totalIndices = this.getTotalIndices();
  33226. // Generating unique vertices per face
  33227. var index;
  33228. for (index = 0; index < totalIndices; index++) {
  33229. var vertexIndex = indices[index];
  33230. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33231. kind = kinds[kindIndex];
  33232. var stride = vbs[kind].getStrideSize();
  33233. for (var offset = 0; offset < stride; offset++) {
  33234. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33235. }
  33236. }
  33237. }
  33238. // Updating indices
  33239. for (index = 0; index < totalIndices; index += 3) {
  33240. indices[index] = index;
  33241. indices[index + 1] = index + 1;
  33242. indices[index + 2] = index + 2;
  33243. }
  33244. this.setIndices(indices);
  33245. // Updating vertex buffers
  33246. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33247. kind = kinds[kindIndex];
  33248. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33249. }
  33250. // Updating submeshes
  33251. this.releaseSubMeshes();
  33252. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33253. var previousOne = previousSubmeshes[submeshIndex];
  33254. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33255. }
  33256. this._unIndexed = true;
  33257. this.synchronizeInstances();
  33258. return this;
  33259. };
  33260. /**
  33261. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33262. * This method returns the Mesh.
  33263. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33264. */
  33265. Mesh.prototype.flipFaces = function (flipNormals) {
  33266. if (flipNormals === void 0) { flipNormals = false; }
  33267. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33268. var i;
  33269. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33270. for (i = 0; i < vertex_data.normals.length; i++) {
  33271. vertex_data.normals[i] *= -1;
  33272. }
  33273. }
  33274. if (vertex_data.indices) {
  33275. var temp;
  33276. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33277. // reassign indices
  33278. temp = vertex_data.indices[i + 1];
  33279. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33280. vertex_data.indices[i + 2] = temp;
  33281. }
  33282. }
  33283. vertex_data.applyToMesh(this);
  33284. return this;
  33285. };
  33286. // Instances
  33287. /**
  33288. * Creates a new InstancedMesh object from the mesh model.
  33289. * An instance shares the same properties and the same material than its model.
  33290. * Only these properties of each instance can then be set individually :
  33291. * - position
  33292. * - rotation
  33293. * - rotationQuaternion
  33294. * - setPivotMatrix
  33295. * - scaling
  33296. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33297. * Warning : this method is not supported for Line mesh and LineSystem
  33298. */
  33299. Mesh.prototype.createInstance = function (name) {
  33300. return new BABYLON.InstancedMesh(name, this);
  33301. };
  33302. /**
  33303. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33304. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33305. * This method returns the Mesh.
  33306. */
  33307. Mesh.prototype.synchronizeInstances = function () {
  33308. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33309. var instance = this.instances[instanceIndex];
  33310. instance._syncSubMeshes();
  33311. }
  33312. return this;
  33313. };
  33314. /**
  33315. * Simplify the mesh according to the given array of settings.
  33316. * Function will return immediately and will simplify async. It returns the Mesh.
  33317. * @param settings a collection of simplification settings.
  33318. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33319. * @param type the type of simplification to run.
  33320. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33321. */
  33322. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33323. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33324. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33325. this.getScene().simplificationQueue.addTask({
  33326. settings: settings,
  33327. parallelProcessing: parallelProcessing,
  33328. mesh: this,
  33329. simplificationType: simplificationType,
  33330. successCallback: successCallback
  33331. });
  33332. return this;
  33333. };
  33334. /**
  33335. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33336. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33337. * This should be used together with the simplification to avoid disappearing triangles.
  33338. * Returns the Mesh.
  33339. * @param successCallback an optional success callback to be called after the optimization finished.
  33340. */
  33341. Mesh.prototype.optimizeIndices = function (successCallback) {
  33342. var _this = this;
  33343. var indices = this.getIndices();
  33344. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33345. if (!positions || !indices) {
  33346. return this;
  33347. }
  33348. var vectorPositions = new Array();
  33349. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33350. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33351. }
  33352. var dupes = new Array();
  33353. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33354. var realPos = vectorPositions.length - 1 - iteration;
  33355. var testedPosition = vectorPositions[realPos];
  33356. for (var j = 0; j < realPos; ++j) {
  33357. var againstPosition = vectorPositions[j];
  33358. if (testedPosition.equals(againstPosition)) {
  33359. dupes[realPos] = j;
  33360. break;
  33361. }
  33362. }
  33363. }, function () {
  33364. for (var i = 0; i < indices.length; ++i) {
  33365. indices[i] = dupes[indices[i]] || indices[i];
  33366. }
  33367. //indices are now reordered
  33368. var originalSubMeshes = _this.subMeshes.slice(0);
  33369. _this.setIndices(indices);
  33370. _this.subMeshes = originalSubMeshes;
  33371. if (successCallback) {
  33372. successCallback(_this);
  33373. }
  33374. });
  33375. return this;
  33376. };
  33377. Mesh.prototype.serialize = function (serializationObject) {
  33378. serializationObject.name = this.name;
  33379. serializationObject.id = this.id;
  33380. serializationObject.type = this.getClassName();
  33381. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33382. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33383. }
  33384. serializationObject.position = this.position.asArray();
  33385. if (this.rotationQuaternion) {
  33386. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33387. }
  33388. else if (this.rotation) {
  33389. serializationObject.rotation = this.rotation.asArray();
  33390. }
  33391. serializationObject.scaling = this.scaling.asArray();
  33392. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33393. serializationObject.isEnabled = this.isEnabled(false);
  33394. serializationObject.isVisible = this.isVisible;
  33395. serializationObject.infiniteDistance = this.infiniteDistance;
  33396. serializationObject.pickable = this.isPickable;
  33397. serializationObject.receiveShadows = this.receiveShadows;
  33398. serializationObject.billboardMode = this.billboardMode;
  33399. serializationObject.visibility = this.visibility;
  33400. serializationObject.checkCollisions = this.checkCollisions;
  33401. serializationObject.isBlocker = this.isBlocker;
  33402. // Parent
  33403. if (this.parent) {
  33404. serializationObject.parentId = this.parent.id;
  33405. }
  33406. // Geometry
  33407. serializationObject.isUnIndexed = this.isUnIndexed;
  33408. var geometry = this._geometry;
  33409. if (geometry) {
  33410. var geometryId = geometry.id;
  33411. serializationObject.geometryId = geometryId;
  33412. // SubMeshes
  33413. serializationObject.subMeshes = [];
  33414. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33415. var subMesh = this.subMeshes[subIndex];
  33416. serializationObject.subMeshes.push({
  33417. materialIndex: subMesh.materialIndex,
  33418. verticesStart: subMesh.verticesStart,
  33419. verticesCount: subMesh.verticesCount,
  33420. indexStart: subMesh.indexStart,
  33421. indexCount: subMesh.indexCount
  33422. });
  33423. }
  33424. }
  33425. // Material
  33426. if (this.material) {
  33427. serializationObject.materialId = this.material.id;
  33428. }
  33429. else {
  33430. this.material = null;
  33431. }
  33432. // Morph targets
  33433. if (this.morphTargetManager) {
  33434. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33435. }
  33436. // Skeleton
  33437. if (this.skeleton) {
  33438. serializationObject.skeletonId = this.skeleton.id;
  33439. }
  33440. // Physics
  33441. //TODO implement correct serialization for physics impostors.
  33442. var impostor = this.getPhysicsImpostor();
  33443. if (impostor) {
  33444. serializationObject.physicsMass = impostor.getParam("mass");
  33445. serializationObject.physicsFriction = impostor.getParam("friction");
  33446. serializationObject.physicsRestitution = impostor.getParam("mass");
  33447. serializationObject.physicsImpostor = impostor.type;
  33448. }
  33449. // Metadata
  33450. if (this.metadata) {
  33451. serializationObject.metadata = this.metadata;
  33452. }
  33453. // Instances
  33454. serializationObject.instances = [];
  33455. for (var index = 0; index < this.instances.length; index++) {
  33456. var instance = this.instances[index];
  33457. var serializationInstance = {
  33458. name: instance.name,
  33459. id: instance.id,
  33460. position: instance.position.asArray(),
  33461. scaling: instance.scaling.asArray()
  33462. };
  33463. if (instance.rotationQuaternion) {
  33464. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33465. }
  33466. else if (instance.rotation) {
  33467. serializationInstance.rotation = instance.rotation.asArray();
  33468. }
  33469. serializationObject.instances.push(serializationInstance);
  33470. // Animations
  33471. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33472. serializationInstance.ranges = instance.serializeAnimationRanges();
  33473. }
  33474. //
  33475. // Animations
  33476. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33477. serializationObject.ranges = this.serializeAnimationRanges();
  33478. // Layer mask
  33479. serializationObject.layerMask = this.layerMask;
  33480. // Alpha
  33481. serializationObject.alphaIndex = this.alphaIndex;
  33482. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33483. // Overlay
  33484. serializationObject.overlayAlpha = this.overlayAlpha;
  33485. serializationObject.overlayColor = this.overlayColor.asArray();
  33486. serializationObject.renderOverlay = this.renderOverlay;
  33487. // Fog
  33488. serializationObject.applyFog = this.applyFog;
  33489. // Action Manager
  33490. if (this.actionManager) {
  33491. serializationObject.actions = this.actionManager.serialize(this.name);
  33492. }
  33493. };
  33494. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33495. if (!this.geometry) {
  33496. return;
  33497. }
  33498. this._markSubMeshesAsAttributesDirty();
  33499. var morphTargetManager = this._morphTargetManager;
  33500. if (morphTargetManager && morphTargetManager.vertexCount) {
  33501. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33502. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33503. this.morphTargetManager = null;
  33504. return;
  33505. }
  33506. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33507. var morphTarget = morphTargetManager.getActiveTarget(index);
  33508. var positions = morphTarget.getPositions();
  33509. if (!positions) {
  33510. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33511. return;
  33512. }
  33513. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33514. var normals = morphTarget.getNormals();
  33515. if (normals) {
  33516. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33517. }
  33518. var tangents = morphTarget.getTangents();
  33519. if (tangents) {
  33520. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33521. }
  33522. }
  33523. }
  33524. else {
  33525. var index = 0;
  33526. // Positions
  33527. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33528. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33529. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33530. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33531. }
  33532. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33533. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33534. }
  33535. index++;
  33536. }
  33537. }
  33538. };
  33539. // Statics
  33540. /**
  33541. * Returns a new Mesh object parsed from the source provided.
  33542. * The parameter `parsedMesh` is the source.
  33543. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33544. */
  33545. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33546. var mesh;
  33547. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33548. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33549. }
  33550. else {
  33551. mesh = new Mesh(parsedMesh.name, scene);
  33552. }
  33553. mesh.id = parsedMesh.id;
  33554. if (BABYLON.Tags) {
  33555. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33556. }
  33557. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33558. if (parsedMesh.metadata !== undefined) {
  33559. mesh.metadata = parsedMesh.metadata;
  33560. }
  33561. if (parsedMesh.rotationQuaternion) {
  33562. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33563. }
  33564. else if (parsedMesh.rotation) {
  33565. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33566. }
  33567. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33568. if (parsedMesh.localMatrix) {
  33569. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33570. }
  33571. else if (parsedMesh.pivotMatrix) {
  33572. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33573. }
  33574. mesh.setEnabled(parsedMesh.isEnabled);
  33575. mesh.isVisible = parsedMesh.isVisible;
  33576. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33577. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33578. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33579. if (parsedMesh.applyFog !== undefined) {
  33580. mesh.applyFog = parsedMesh.applyFog;
  33581. }
  33582. if (parsedMesh.pickable !== undefined) {
  33583. mesh.isPickable = parsedMesh.pickable;
  33584. }
  33585. if (parsedMesh.alphaIndex !== undefined) {
  33586. mesh.alphaIndex = parsedMesh.alphaIndex;
  33587. }
  33588. mesh.receiveShadows = parsedMesh.receiveShadows;
  33589. mesh.billboardMode = parsedMesh.billboardMode;
  33590. if (parsedMesh.visibility !== undefined) {
  33591. mesh.visibility = parsedMesh.visibility;
  33592. }
  33593. mesh.checkCollisions = parsedMesh.checkCollisions;
  33594. if (parsedMesh.isBlocker !== undefined) {
  33595. mesh.isBlocker = parsedMesh.isBlocker;
  33596. }
  33597. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33598. // freezeWorldMatrix
  33599. if (parsedMesh.freezeWorldMatrix) {
  33600. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33601. }
  33602. // Parent
  33603. if (parsedMesh.parentId) {
  33604. mesh._waitingParentId = parsedMesh.parentId;
  33605. }
  33606. // Actions
  33607. if (parsedMesh.actions !== undefined) {
  33608. mesh._waitingActions = parsedMesh.actions;
  33609. }
  33610. // Overlay
  33611. if (parsedMesh.overlayAlpha !== undefined) {
  33612. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33613. }
  33614. if (parsedMesh.overlayColor !== undefined) {
  33615. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33616. }
  33617. if (parsedMesh.renderOverlay !== undefined) {
  33618. mesh.renderOverlay = parsedMesh.renderOverlay;
  33619. }
  33620. // Geometry
  33621. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33622. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33623. if (parsedMesh.delayLoadingFile) {
  33624. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33625. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33626. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33627. if (parsedMesh._binaryInfo) {
  33628. mesh._binaryInfo = parsedMesh._binaryInfo;
  33629. }
  33630. mesh._delayInfo = [];
  33631. if (parsedMesh.hasUVs) {
  33632. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33633. }
  33634. if (parsedMesh.hasUVs2) {
  33635. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33636. }
  33637. if (parsedMesh.hasUVs3) {
  33638. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33639. }
  33640. if (parsedMesh.hasUVs4) {
  33641. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33642. }
  33643. if (parsedMesh.hasUVs5) {
  33644. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33645. }
  33646. if (parsedMesh.hasUVs6) {
  33647. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33648. }
  33649. if (parsedMesh.hasColors) {
  33650. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33651. }
  33652. if (parsedMesh.hasMatricesIndices) {
  33653. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33654. }
  33655. if (parsedMesh.hasMatricesWeights) {
  33656. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33657. }
  33658. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33659. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33660. mesh._checkDelayState();
  33661. }
  33662. }
  33663. else {
  33664. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33665. }
  33666. // Material
  33667. if (parsedMesh.materialId) {
  33668. mesh.setMaterialByID(parsedMesh.materialId);
  33669. }
  33670. else {
  33671. mesh.material = null;
  33672. }
  33673. // Morph targets
  33674. if (parsedMesh.morphTargetManagerId > -1) {
  33675. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33676. }
  33677. // Skeleton
  33678. if (parsedMesh.skeletonId > -1) {
  33679. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33680. if (parsedMesh.numBoneInfluencers) {
  33681. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33682. }
  33683. }
  33684. // Animations
  33685. if (parsedMesh.animations) {
  33686. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33687. var parsedAnimation = parsedMesh.animations[animationIndex];
  33688. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33689. }
  33690. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33691. }
  33692. if (parsedMesh.autoAnimate) {
  33693. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33694. }
  33695. // Layer Mask
  33696. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33697. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33698. }
  33699. else {
  33700. mesh.layerMask = 0x0FFFFFFF;
  33701. }
  33702. // Physics
  33703. if (parsedMesh.physicsImpostor) {
  33704. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33705. mass: parsedMesh.physicsMass,
  33706. friction: parsedMesh.physicsFriction,
  33707. restitution: parsedMesh.physicsRestitution
  33708. }, scene);
  33709. }
  33710. // Instances
  33711. if (parsedMesh.instances) {
  33712. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33713. var parsedInstance = parsedMesh.instances[index];
  33714. var instance = mesh.createInstance(parsedInstance.name);
  33715. if (parsedInstance.id) {
  33716. instance.id = parsedInstance.id;
  33717. }
  33718. if (BABYLON.Tags) {
  33719. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33720. }
  33721. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33722. if (parsedInstance.parentId) {
  33723. instance._waitingParentId = parsedInstance.parentId;
  33724. }
  33725. if (parsedInstance.rotationQuaternion) {
  33726. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33727. }
  33728. else if (parsedInstance.rotation) {
  33729. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33730. }
  33731. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33732. instance.checkCollisions = mesh.checkCollisions;
  33733. if (parsedMesh.animations) {
  33734. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33735. parsedAnimation = parsedMesh.animations[animationIndex];
  33736. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33737. }
  33738. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33739. if (parsedMesh.autoAnimate) {
  33740. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33741. }
  33742. }
  33743. }
  33744. }
  33745. return mesh;
  33746. };
  33747. /**
  33748. * Creates a ribbon mesh.
  33749. * Please consider using the same method from the MeshBuilder class instead.
  33750. * 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.
  33751. *
  33752. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33753. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33754. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33755. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33756. * 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.
  33757. * 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.
  33758. * 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
  33759. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33760. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33761. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33762. */
  33763. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33764. if (closeArray === void 0) { closeArray = false; }
  33765. if (updatable === void 0) { updatable = false; }
  33766. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33767. pathArray: pathArray,
  33768. closeArray: closeArray,
  33769. closePath: closePath,
  33770. offset: offset,
  33771. updatable: updatable,
  33772. sideOrientation: sideOrientation,
  33773. instance: instance
  33774. }, scene);
  33775. };
  33776. /**
  33777. * Creates a plane polygonal mesh. By default, this is a disc.
  33778. * Please consider using the same method from the MeshBuilder class instead.
  33779. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33780. * 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.
  33781. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33782. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33783. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33784. */
  33785. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33786. if (scene === void 0) { scene = null; }
  33787. var options = {
  33788. radius: radius,
  33789. tessellation: tessellation,
  33790. sideOrientation: sideOrientation,
  33791. updatable: updatable
  33792. };
  33793. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33794. };
  33795. /**
  33796. * Creates a box mesh.
  33797. * Please consider using the same method from the MeshBuilder class instead.
  33798. * The parameter `size` sets the size (float) of each box side (default 1).
  33799. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33800. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33801. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33802. */
  33803. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33804. if (scene === void 0) { scene = null; }
  33805. var options = {
  33806. size: size,
  33807. sideOrientation: sideOrientation,
  33808. updatable: updatable
  33809. };
  33810. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33811. };
  33812. /**
  33813. * Creates a sphere mesh.
  33814. * Please consider using the same method from the MeshBuilder class instead.
  33815. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33816. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33817. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33818. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33820. */
  33821. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33822. var options = {
  33823. segments: segments,
  33824. diameterX: diameter,
  33825. diameterY: diameter,
  33826. diameterZ: diameter,
  33827. sideOrientation: sideOrientation,
  33828. updatable: updatable
  33829. };
  33830. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33831. };
  33832. /**
  33833. * Creates a cylinder or a cone mesh.
  33834. * Please consider using the same method from the MeshBuilder class instead.
  33835. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33836. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33837. * 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.
  33838. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33839. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33840. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33841. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33843. */
  33844. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33845. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33846. if (scene !== undefined) {
  33847. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33848. updatable = scene;
  33849. }
  33850. scene = subdivisions;
  33851. subdivisions = 1;
  33852. }
  33853. var options = {
  33854. height: height,
  33855. diameterTop: diameterTop,
  33856. diameterBottom: diameterBottom,
  33857. tessellation: tessellation,
  33858. subdivisions: subdivisions,
  33859. sideOrientation: sideOrientation,
  33860. updatable: updatable
  33861. };
  33862. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33863. };
  33864. // Torus (Code from SharpDX.org)
  33865. /**
  33866. * Creates a torus mesh.
  33867. * Please consider using the same method from the MeshBuilder class instead.
  33868. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33869. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33870. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33872. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33874. */
  33875. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33876. var options = {
  33877. diameter: diameter,
  33878. thickness: thickness,
  33879. tessellation: tessellation,
  33880. sideOrientation: sideOrientation,
  33881. updatable: updatable
  33882. };
  33883. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33884. };
  33885. /**
  33886. * Creates a torus knot mesh.
  33887. * Please consider using the same method from the MeshBuilder class instead.
  33888. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33889. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33890. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33891. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33892. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33893. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33894. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33895. */
  33896. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33897. var options = {
  33898. radius: radius,
  33899. tube: tube,
  33900. radialSegments: radialSegments,
  33901. tubularSegments: tubularSegments,
  33902. p: p,
  33903. q: q,
  33904. sideOrientation: sideOrientation,
  33905. updatable: updatable
  33906. };
  33907. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33908. };
  33909. /**
  33910. * Creates a line mesh.
  33911. * Please consider using the same method from the MeshBuilder class instead.
  33912. * 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.
  33913. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33914. * The parameter `points` is an array successive Vector3.
  33915. * 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
  33916. * When updating an instance, remember that only point positions can change, not the number of points.
  33917. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33918. */
  33919. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33920. if (scene === void 0) { scene = null; }
  33921. if (updatable === void 0) { updatable = false; }
  33922. if (instance === void 0) { instance = null; }
  33923. var options = {
  33924. points: points,
  33925. updatable: updatable,
  33926. instance: instance
  33927. };
  33928. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33929. };
  33930. /**
  33931. * Creates a dashed line mesh.
  33932. * Please consider using the same method from the MeshBuilder class instead.
  33933. * 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.
  33934. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33935. * The parameter `points` is an array successive Vector3.
  33936. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33937. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33938. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33939. * 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
  33940. * When updating an instance, remember that only point positions can change, not the number of points.
  33941. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33942. */
  33943. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33944. if (scene === void 0) { scene = null; }
  33945. var options = {
  33946. points: points,
  33947. dashSize: dashSize,
  33948. gapSize: gapSize,
  33949. dashNb: dashNb,
  33950. updatable: updatable,
  33951. instance: instance
  33952. };
  33953. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33954. };
  33955. /**
  33956. * Creates a polygon mesh.
  33957. * Please consider using the same method from the MeshBuilder class instead.
  33958. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33959. * 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.
  33960. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33961. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33962. * Remember you can only change the shape positions, not their number when updating a polygon.
  33963. */
  33964. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33965. var options = {
  33966. shape: shape,
  33967. holes: holes,
  33968. updatable: updatable,
  33969. sideOrientation: sideOrientation
  33970. };
  33971. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33972. };
  33973. /**
  33974. * Creates an extruded polygon mesh, with depth in the Y direction.
  33975. * Please consider using the same method from the MeshBuilder class instead.
  33976. */
  33977. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33978. var options = {
  33979. shape: shape,
  33980. holes: holes,
  33981. depth: depth,
  33982. updatable: updatable,
  33983. sideOrientation: sideOrientation
  33984. };
  33985. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33986. };
  33987. /**
  33988. * Creates an extruded shape mesh.
  33989. * 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.
  33990. * Please consider using the same method from the MeshBuilder class instead.
  33991. *
  33992. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33993. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  33994. * extruded along the Z axis.
  33995. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33996. * The parameter `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.
  33997. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33998. * 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
  33999. * 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
  34000. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34001. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34002. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34003. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34004. */
  34005. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34006. if (scene === void 0) { scene = null; }
  34007. var options = {
  34008. shape: shape,
  34009. path: path,
  34010. scale: scale,
  34011. rotation: rotation,
  34012. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34013. sideOrientation: sideOrientation,
  34014. instance: instance,
  34015. updatable: updatable
  34016. };
  34017. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34018. };
  34019. /**
  34020. * Creates an custom extruded shape mesh.
  34021. * 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.
  34022. * Please consider using the same method from the MeshBuilder class instead.
  34023. *
  34024. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34025. * 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
  34026. * extruded along the Z axis.
  34027. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34028. * 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
  34029. * and the distance of this point from the begining of the path :
  34030. * ```javascript
  34031. * var rotationFunction = function(i, distance) {
  34032. * // do things
  34033. * return rotationValue; }
  34034. * ```
  34035. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  34036. * 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
  34037. * and the distance of this point from the begining of the path :
  34038. * ```javascript
  34039. * var scaleFunction = function(i, distance) {
  34040. * // do things
  34041. * return scaleValue;}
  34042. * ```
  34043. * It must returns a float value that will be the scale value applied to the shape on each path point.
  34044. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  34045. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  34046. * 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
  34047. * 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
  34048. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34049. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34050. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34051. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34052. */
  34053. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34054. var options = {
  34055. shape: shape,
  34056. path: path,
  34057. scaleFunction: scaleFunction,
  34058. rotationFunction: rotationFunction,
  34059. ribbonCloseArray: ribbonCloseArray,
  34060. ribbonClosePath: ribbonClosePath,
  34061. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34062. sideOrientation: sideOrientation,
  34063. instance: instance,
  34064. updatable: updatable
  34065. };
  34066. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34067. };
  34068. /**
  34069. * Creates lathe mesh.
  34070. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34071. * Please consider using the same method from the MeshBuilder class instead.
  34072. * 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
  34073. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34074. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34075. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34076. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34077. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34078. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34079. */
  34080. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34081. var options = {
  34082. shape: shape,
  34083. radius: radius,
  34084. tessellation: tessellation,
  34085. sideOrientation: sideOrientation,
  34086. updatable: updatable
  34087. };
  34088. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34089. };
  34090. /**
  34091. * Creates a plane mesh.
  34092. * Please consider using the same method from the MeshBuilder class instead.
  34093. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34094. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34095. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34097. */
  34098. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34099. var options = {
  34100. size: size,
  34101. width: size,
  34102. height: size,
  34103. sideOrientation: sideOrientation,
  34104. updatable: updatable
  34105. };
  34106. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34107. };
  34108. /**
  34109. * Creates a ground mesh.
  34110. * Please consider using the same method from the MeshBuilder class instead.
  34111. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34112. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34113. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34114. */
  34115. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34116. var options = {
  34117. width: width,
  34118. height: height,
  34119. subdivisions: subdivisions,
  34120. updatable: updatable
  34121. };
  34122. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34123. };
  34124. /**
  34125. * Creates a tiled ground mesh.
  34126. * Please consider using the same method from the MeshBuilder class instead.
  34127. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34128. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34129. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34130. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34131. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34132. * numbers of subdivisions on the ground width and height of each tile.
  34133. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34134. */
  34135. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34136. var options = {
  34137. xmin: xmin,
  34138. zmin: zmin,
  34139. xmax: xmax,
  34140. zmax: zmax,
  34141. subdivisions: subdivisions,
  34142. precision: precision,
  34143. updatable: updatable
  34144. };
  34145. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34146. };
  34147. /**
  34148. * Creates a ground mesh from a height map.
  34149. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34150. * Please consider using the same method from the MeshBuilder class instead.
  34151. * The parameter `url` sets the URL of the height map image resource.
  34152. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34153. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34154. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34155. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34156. * 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).
  34157. * This function is passed the newly built mesh :
  34158. * ```javascript
  34159. * function(mesh) { // do things
  34160. * return; }
  34161. * ```
  34162. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34163. */
  34164. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34165. var options = {
  34166. width: width,
  34167. height: height,
  34168. subdivisions: subdivisions,
  34169. minHeight: minHeight,
  34170. maxHeight: maxHeight,
  34171. updatable: updatable,
  34172. onReady: onReady
  34173. };
  34174. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34175. };
  34176. /**
  34177. * Creates a tube mesh.
  34178. * 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.
  34179. * Please consider using the same method from the MeshBuilder class instead.
  34180. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34181. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34182. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34183. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34184. * 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.
  34185. * It must return a radius value (positive float) :
  34186. * ```javascript
  34187. * var radiusFunction = function(i, distance) {
  34188. * // do things
  34189. * return radius; }
  34190. * ```
  34191. * 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
  34192. * 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
  34193. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34194. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34196. */
  34197. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34198. var options = {
  34199. path: path,
  34200. radius: radius,
  34201. tessellation: tessellation,
  34202. radiusFunction: radiusFunction,
  34203. arc: 1,
  34204. cap: cap,
  34205. updatable: updatable,
  34206. sideOrientation: sideOrientation,
  34207. instance: instance
  34208. };
  34209. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34210. };
  34211. /**
  34212. * Creates a polyhedron mesh.
  34213. * Please consider using the same method from the MeshBuilder class instead.
  34214. * 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
  34215. * to choose the wanted type.
  34216. * The parameter `size` (positive float, default 1) sets the polygon size.
  34217. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34218. * 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`.
  34219. * 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
  34220. * 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)`).
  34221. * 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
  34222. * 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.
  34223. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34224. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34225. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34226. */
  34227. Mesh.CreatePolyhedron = function (name, options, scene) {
  34228. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34229. };
  34230. /**
  34231. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34232. * Please consider using the same method from the MeshBuilder class instead.
  34233. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34234. * 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`).
  34235. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34236. * 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.
  34237. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34238. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34240. */
  34241. Mesh.CreateIcoSphere = function (name, options, scene) {
  34242. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34243. };
  34244. /**
  34245. * Creates a decal mesh.
  34246. * Please consider using the same method from the MeshBuilder class instead.
  34247. * 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.
  34248. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34249. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34250. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34251. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34252. */
  34253. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34254. var options = {
  34255. position: position,
  34256. normal: normal,
  34257. size: size,
  34258. angle: angle
  34259. };
  34260. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34261. };
  34262. // Skeletons
  34263. /**
  34264. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34265. */
  34266. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34267. if (!this._sourcePositions) {
  34268. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34269. if (!source) {
  34270. return this._sourcePositions;
  34271. }
  34272. this._sourcePositions = new Float32Array(source);
  34273. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34274. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34275. }
  34276. }
  34277. return this._sourcePositions;
  34278. };
  34279. /**
  34280. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34281. */
  34282. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34283. if (!this._sourceNormals) {
  34284. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34285. if (!source) {
  34286. return this._sourceNormals;
  34287. }
  34288. this._sourceNormals = new Float32Array(source);
  34289. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34290. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34291. }
  34292. }
  34293. return this._sourceNormals;
  34294. };
  34295. /**
  34296. * Updates the vertex buffer by applying transformation from the bones.
  34297. * Returns the Mesh.
  34298. *
  34299. * @param {skeleton} skeleton to apply
  34300. */
  34301. Mesh.prototype.applySkeleton = function (skeleton) {
  34302. if (!this.geometry) {
  34303. return this;
  34304. }
  34305. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34306. return this;
  34307. }
  34308. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34309. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34310. return this;
  34311. }
  34312. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34313. return this;
  34314. }
  34315. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34316. return this;
  34317. }
  34318. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34319. return this;
  34320. }
  34321. if (!this._sourcePositions) {
  34322. var submeshes = this.subMeshes.slice();
  34323. this.setPositionsForCPUSkinning();
  34324. this.subMeshes = submeshes;
  34325. }
  34326. if (!this._sourceNormals) {
  34327. this.setNormalsForCPUSkinning();
  34328. }
  34329. // positionsData checks for not being Float32Array will only pass at most once
  34330. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34331. if (!positionsData) {
  34332. return this;
  34333. }
  34334. if (!(positionsData instanceof Float32Array)) {
  34335. positionsData = new Float32Array(positionsData);
  34336. }
  34337. // normalsData checks for not being Float32Array will only pass at most once
  34338. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34339. if (!normalsData) {
  34340. return this;
  34341. }
  34342. if (!(normalsData instanceof Float32Array)) {
  34343. normalsData = new Float32Array(normalsData);
  34344. }
  34345. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34346. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34347. if (!matricesWeightsData || !matricesIndicesData) {
  34348. return this;
  34349. }
  34350. var needExtras = this.numBoneInfluencers > 4;
  34351. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34352. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34353. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34354. var tempVector3 = BABYLON.Vector3.Zero();
  34355. var finalMatrix = new BABYLON.Matrix();
  34356. var tempMatrix = new BABYLON.Matrix();
  34357. var matWeightIdx = 0;
  34358. var inf;
  34359. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34360. var weight;
  34361. for (inf = 0; inf < 4; inf++) {
  34362. weight = matricesWeightsData[matWeightIdx + inf];
  34363. if (weight > 0) {
  34364. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34365. finalMatrix.addToSelf(tempMatrix);
  34366. }
  34367. else
  34368. break;
  34369. }
  34370. if (needExtras) {
  34371. for (inf = 0; inf < 4; inf++) {
  34372. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34373. if (weight > 0) {
  34374. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34375. finalMatrix.addToSelf(tempMatrix);
  34376. }
  34377. else
  34378. break;
  34379. }
  34380. }
  34381. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34382. tempVector3.toArray(positionsData, index);
  34383. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34384. tempVector3.toArray(normalsData, index);
  34385. finalMatrix.reset();
  34386. }
  34387. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34388. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34389. return this;
  34390. };
  34391. // Tools
  34392. /**
  34393. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34394. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34395. */
  34396. Mesh.MinMax = function (meshes) {
  34397. var minVector = null;
  34398. var maxVector = null;
  34399. meshes.forEach(function (mesh, index, array) {
  34400. var boundingInfo = mesh.getBoundingInfo();
  34401. var boundingBox = boundingInfo.boundingBox;
  34402. if (!minVector || !maxVector) {
  34403. minVector = boundingBox.minimumWorld;
  34404. maxVector = boundingBox.maximumWorld;
  34405. }
  34406. else {
  34407. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34408. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34409. }
  34410. });
  34411. if (!minVector || !maxVector) {
  34412. return {
  34413. min: BABYLON.Vector3.Zero(),
  34414. max: BABYLON.Vector3.Zero()
  34415. };
  34416. }
  34417. return {
  34418. min: minVector,
  34419. max: maxVector
  34420. };
  34421. };
  34422. /**
  34423. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34424. */
  34425. Mesh.Center = function (meshesOrMinMaxVector) {
  34426. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34427. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34428. };
  34429. /**
  34430. * Merge the array of meshes into a single mesh for performance reasons.
  34431. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34432. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34433. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34434. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34435. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34436. */
  34437. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34438. if (disposeSource === void 0) { disposeSource = true; }
  34439. var index;
  34440. if (!allow32BitsIndices) {
  34441. var totalVertices = 0;
  34442. // Counting vertices
  34443. for (index = 0; index < meshes.length; index++) {
  34444. if (meshes[index]) {
  34445. totalVertices += meshes[index].getTotalVertices();
  34446. if (totalVertices > 65536) {
  34447. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34448. return null;
  34449. }
  34450. }
  34451. }
  34452. }
  34453. // Merge
  34454. var vertexData = null;
  34455. var otherVertexData;
  34456. var indiceArray = new Array();
  34457. var source = null;
  34458. for (index = 0; index < meshes.length; index++) {
  34459. if (meshes[index]) {
  34460. meshes[index].computeWorldMatrix(true);
  34461. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34462. otherVertexData.transform(meshes[index].getWorldMatrix());
  34463. if (vertexData) {
  34464. vertexData.merge(otherVertexData);
  34465. }
  34466. else {
  34467. vertexData = otherVertexData;
  34468. source = meshes[index];
  34469. }
  34470. if (subdivideWithSubMeshes) {
  34471. indiceArray.push(meshes[index].getTotalIndices());
  34472. }
  34473. }
  34474. }
  34475. source = source;
  34476. if (!meshSubclass) {
  34477. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34478. }
  34479. vertexData.applyToMesh(meshSubclass);
  34480. // Setting properties
  34481. meshSubclass.material = source.material;
  34482. meshSubclass.checkCollisions = source.checkCollisions;
  34483. // Cleaning
  34484. if (disposeSource) {
  34485. for (index = 0; index < meshes.length; index++) {
  34486. if (meshes[index]) {
  34487. meshes[index].dispose();
  34488. }
  34489. }
  34490. }
  34491. // Subdivide
  34492. if (subdivideWithSubMeshes) {
  34493. //-- removal of global submesh
  34494. meshSubclass.releaseSubMeshes();
  34495. index = 0;
  34496. var offset = 0;
  34497. //-- apply subdivision according to index table
  34498. while (index < indiceArray.length) {
  34499. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34500. offset += indiceArray[index];
  34501. index++;
  34502. }
  34503. }
  34504. return meshSubclass;
  34505. };
  34506. // Consts
  34507. Mesh._FRONTSIDE = 0;
  34508. Mesh._BACKSIDE = 1;
  34509. Mesh._DOUBLESIDE = 2;
  34510. Mesh._DEFAULTSIDE = 0;
  34511. Mesh._NO_CAP = 0;
  34512. Mesh._CAP_START = 1;
  34513. Mesh._CAP_END = 2;
  34514. Mesh._CAP_ALL = 3;
  34515. return Mesh;
  34516. }(BABYLON.AbstractMesh));
  34517. BABYLON.Mesh = Mesh;
  34518. })(BABYLON || (BABYLON = {}));
  34519. //# sourceMappingURL=babylon.mesh.js.map
  34520. var BABYLON;
  34521. (function (BABYLON) {
  34522. var BaseSubMesh = /** @class */ (function () {
  34523. function BaseSubMesh() {
  34524. }
  34525. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34526. get: function () {
  34527. return this._materialEffect;
  34528. },
  34529. enumerable: true,
  34530. configurable: true
  34531. });
  34532. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34533. if (defines === void 0) { defines = null; }
  34534. if (this._materialEffect === effect) {
  34535. if (!effect) {
  34536. this._materialDefines = null;
  34537. }
  34538. return;
  34539. }
  34540. this._materialDefines = defines;
  34541. this._materialEffect = effect;
  34542. };
  34543. return BaseSubMesh;
  34544. }());
  34545. BABYLON.BaseSubMesh = BaseSubMesh;
  34546. var SubMesh = /** @class */ (function (_super) {
  34547. __extends(SubMesh, _super);
  34548. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34549. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34550. var _this = _super.call(this) || this;
  34551. _this.materialIndex = materialIndex;
  34552. _this.verticesStart = verticesStart;
  34553. _this.verticesCount = verticesCount;
  34554. _this.indexStart = indexStart;
  34555. _this.indexCount = indexCount;
  34556. _this._renderId = 0;
  34557. _this._mesh = mesh;
  34558. _this._renderingMesh = renderingMesh || mesh;
  34559. mesh.subMeshes.push(_this);
  34560. _this._trianglePlanes = [];
  34561. _this._id = mesh.subMeshes.length - 1;
  34562. if (createBoundingBox) {
  34563. _this.refreshBoundingInfo();
  34564. mesh.computeWorldMatrix(true);
  34565. }
  34566. return _this;
  34567. }
  34568. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34569. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34570. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34571. };
  34572. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34573. get: function () {
  34574. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34575. },
  34576. enumerable: true,
  34577. configurable: true
  34578. });
  34579. /**
  34580. * Returns the submesh BoudingInfo object.
  34581. */
  34582. SubMesh.prototype.getBoundingInfo = function () {
  34583. if (this.IsGlobal) {
  34584. return this._mesh.getBoundingInfo();
  34585. }
  34586. return this._boundingInfo;
  34587. };
  34588. /**
  34589. * Sets the submesh BoundingInfo.
  34590. * Return the SubMesh.
  34591. */
  34592. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34593. this._boundingInfo = boundingInfo;
  34594. return this;
  34595. };
  34596. /**
  34597. * Returns the mesh of the current submesh.
  34598. */
  34599. SubMesh.prototype.getMesh = function () {
  34600. return this._mesh;
  34601. };
  34602. /**
  34603. * Returns the rendering mesh of the submesh.
  34604. */
  34605. SubMesh.prototype.getRenderingMesh = function () {
  34606. return this._renderingMesh;
  34607. };
  34608. /**
  34609. * Returns the submesh material.
  34610. */
  34611. SubMesh.prototype.getMaterial = function () {
  34612. var rootMaterial = this._renderingMesh.material;
  34613. if (rootMaterial === null || rootMaterial === undefined) {
  34614. return this._mesh.getScene().defaultMaterial;
  34615. }
  34616. else if (rootMaterial.getSubMaterial) {
  34617. var multiMaterial = rootMaterial;
  34618. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34619. if (this._currentMaterial !== effectiveMaterial) {
  34620. this._currentMaterial = effectiveMaterial;
  34621. this._materialDefines = null;
  34622. }
  34623. return effectiveMaterial;
  34624. }
  34625. return rootMaterial;
  34626. };
  34627. // Methods
  34628. /**
  34629. * Sets a new updated BoundingInfo object to the submesh.
  34630. * Returns the SubMesh.
  34631. */
  34632. SubMesh.prototype.refreshBoundingInfo = function () {
  34633. this._lastColliderWorldVertices = null;
  34634. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34635. return this;
  34636. }
  34637. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34638. if (!data) {
  34639. this._boundingInfo = this._mesh.getBoundingInfo();
  34640. return this;
  34641. }
  34642. var indices = this._renderingMesh.getIndices();
  34643. var extend;
  34644. //is this the only submesh?
  34645. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34646. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34647. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34648. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34649. }
  34650. else {
  34651. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34652. }
  34653. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34654. return this;
  34655. };
  34656. SubMesh.prototype._checkCollision = function (collider) {
  34657. var boundingInfo = this.getBoundingInfo();
  34658. return boundingInfo._checkCollision(collider);
  34659. };
  34660. /**
  34661. * Updates the submesh BoundingInfo.
  34662. * Returns the Submesh.
  34663. */
  34664. SubMesh.prototype.updateBoundingInfo = function (world) {
  34665. var boundingInfo = this.getBoundingInfo();
  34666. if (!boundingInfo) {
  34667. this.refreshBoundingInfo();
  34668. boundingInfo = this.getBoundingInfo();
  34669. }
  34670. boundingInfo.update(world);
  34671. return this;
  34672. };
  34673. /**
  34674. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34675. * Boolean returned.
  34676. */
  34677. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34678. var boundingInfo = this.getBoundingInfo();
  34679. if (!boundingInfo) {
  34680. return false;
  34681. }
  34682. return boundingInfo.isInFrustum(frustumPlanes);
  34683. };
  34684. /**
  34685. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34686. * Boolean returned.
  34687. */
  34688. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34689. var boundingInfo = this.getBoundingInfo();
  34690. if (!boundingInfo) {
  34691. return false;
  34692. }
  34693. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34694. };
  34695. /**
  34696. * Renders the submesh.
  34697. * Returns it.
  34698. */
  34699. SubMesh.prototype.render = function (enableAlphaMode) {
  34700. this._renderingMesh.render(this, enableAlphaMode);
  34701. return this;
  34702. };
  34703. /**
  34704. * Returns a new Index Buffer.
  34705. * Type returned : WebGLBuffer.
  34706. */
  34707. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34708. if (!this._linesIndexBuffer) {
  34709. var linesIndices = [];
  34710. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34711. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34712. }
  34713. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34714. this.linesIndexCount = linesIndices.length;
  34715. }
  34716. return this._linesIndexBuffer;
  34717. };
  34718. /**
  34719. * True is the passed Ray intersects the submesh bounding box.
  34720. * Boolean returned.
  34721. */
  34722. SubMesh.prototype.canIntersects = function (ray) {
  34723. var boundingInfo = this.getBoundingInfo();
  34724. if (!boundingInfo) {
  34725. return false;
  34726. }
  34727. return ray.intersectsBox(boundingInfo.boundingBox);
  34728. };
  34729. /**
  34730. * Returns an object IntersectionInfo.
  34731. */
  34732. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34733. var intersectInfo = null;
  34734. var material = this.getMaterial();
  34735. if (!material) {
  34736. return null;
  34737. }
  34738. switch (material.fillMode) {
  34739. case BABYLON.Material.PointListDrawMode:
  34740. case BABYLON.Material.LineListDrawMode:
  34741. case BABYLON.Material.LineLoopDrawMode:
  34742. case BABYLON.Material.LineStripDrawMode:
  34743. case BABYLON.Material.TriangleFanDrawMode:
  34744. case BABYLON.Material.TriangleStripDrawMode:
  34745. return null;
  34746. }
  34747. // LineMesh first as it's also a Mesh...
  34748. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34749. var lineMesh = this._mesh;
  34750. // Line test
  34751. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34752. var p0 = positions[indices[index]];
  34753. var p1 = positions[indices[index + 1]];
  34754. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34755. if (length < 0) {
  34756. continue;
  34757. }
  34758. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34759. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34760. if (fastCheck) {
  34761. break;
  34762. }
  34763. }
  34764. }
  34765. }
  34766. else {
  34767. // Triangles test
  34768. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34769. var p0 = positions[indices[index]];
  34770. var p1 = positions[indices[index + 1]];
  34771. var p2 = positions[indices[index + 2]];
  34772. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34773. if (currentIntersectInfo) {
  34774. if (currentIntersectInfo.distance < 0) {
  34775. continue;
  34776. }
  34777. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34778. intersectInfo = currentIntersectInfo;
  34779. intersectInfo.faceId = index / 3;
  34780. if (fastCheck) {
  34781. break;
  34782. }
  34783. }
  34784. }
  34785. }
  34786. }
  34787. return intersectInfo;
  34788. };
  34789. SubMesh.prototype._rebuild = function () {
  34790. if (this._linesIndexBuffer) {
  34791. this._linesIndexBuffer = null;
  34792. }
  34793. };
  34794. // Clone
  34795. /**
  34796. * Creates a new Submesh from the passed Mesh.
  34797. */
  34798. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34799. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34800. if (!this.IsGlobal) {
  34801. var boundingInfo = this.getBoundingInfo();
  34802. if (!boundingInfo) {
  34803. return result;
  34804. }
  34805. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34806. }
  34807. return result;
  34808. };
  34809. // Dispose
  34810. /**
  34811. * Disposes the Submesh.
  34812. * Returns nothing.
  34813. */
  34814. SubMesh.prototype.dispose = function () {
  34815. if (this._linesIndexBuffer) {
  34816. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34817. this._linesIndexBuffer = null;
  34818. }
  34819. // Remove from mesh
  34820. var index = this._mesh.subMeshes.indexOf(this);
  34821. this._mesh.subMeshes.splice(index, 1);
  34822. };
  34823. // Statics
  34824. /**
  34825. * Creates a new Submesh from the passed parameters :
  34826. * - materialIndex (integer) : the index of the main mesh material.
  34827. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34828. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34829. * - mesh (Mesh) : the main mesh to create the submesh from.
  34830. * - renderingMesh (optional Mesh) : rendering mesh.
  34831. */
  34832. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34833. var minVertexIndex = Number.MAX_VALUE;
  34834. var maxVertexIndex = -Number.MAX_VALUE;
  34835. renderingMesh = (renderingMesh || mesh);
  34836. var indices = renderingMesh.getIndices();
  34837. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34838. var vertexIndex = indices[index];
  34839. if (vertexIndex < minVertexIndex)
  34840. minVertexIndex = vertexIndex;
  34841. if (vertexIndex > maxVertexIndex)
  34842. maxVertexIndex = vertexIndex;
  34843. }
  34844. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34845. };
  34846. return SubMesh;
  34847. }(BaseSubMesh));
  34848. BABYLON.SubMesh = SubMesh;
  34849. })(BABYLON || (BABYLON = {}));
  34850. //# sourceMappingURL=babylon.subMesh.js.map
  34851. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34852. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34853. s = arguments[i];
  34854. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34855. t[p] = s[p];
  34856. }
  34857. return t;
  34858. };
  34859. var BABYLON;
  34860. (function (BABYLON) {
  34861. /**
  34862. * Manages the defines for the Material
  34863. */
  34864. var MaterialDefines = /** @class */ (function () {
  34865. function MaterialDefines() {
  34866. this._isDirty = true;
  34867. /** @hidden */
  34868. this._areLightsDirty = true;
  34869. /** @hidden */
  34870. this._areAttributesDirty = true;
  34871. /** @hidden */
  34872. this._areTexturesDirty = true;
  34873. /** @hidden */
  34874. this._areFresnelDirty = true;
  34875. /** @hidden */
  34876. this._areMiscDirty = true;
  34877. /** @hidden */
  34878. this._areImageProcessingDirty = true;
  34879. /** @hidden */
  34880. this._normals = false;
  34881. /** @hidden */
  34882. this._uvs = false;
  34883. /** @hidden */
  34884. this._needNormals = false;
  34885. /** @hidden */
  34886. this._needUVs = false;
  34887. }
  34888. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34889. /**
  34890. * Specifies if the material needs to be re-calculated
  34891. */
  34892. get: function () {
  34893. return this._isDirty;
  34894. },
  34895. enumerable: true,
  34896. configurable: true
  34897. });
  34898. /**
  34899. * Marks the material to indicate that it has been re-calculated
  34900. */
  34901. MaterialDefines.prototype.markAsProcessed = function () {
  34902. this._isDirty = false;
  34903. this._areAttributesDirty = false;
  34904. this._areTexturesDirty = false;
  34905. this._areFresnelDirty = false;
  34906. this._areLightsDirty = false;
  34907. this._areMiscDirty = false;
  34908. this._areImageProcessingDirty = false;
  34909. };
  34910. /**
  34911. * Marks the material to indicate that it needs to be re-calculated
  34912. */
  34913. MaterialDefines.prototype.markAsUnprocessed = function () {
  34914. this._isDirty = true;
  34915. };
  34916. /**
  34917. * Marks the material to indicate all of its defines need to be re-calculated
  34918. */
  34919. MaterialDefines.prototype.markAllAsDirty = function () {
  34920. this._areTexturesDirty = true;
  34921. this._areAttributesDirty = true;
  34922. this._areLightsDirty = true;
  34923. this._areFresnelDirty = true;
  34924. this._areMiscDirty = true;
  34925. this._areImageProcessingDirty = true;
  34926. this._isDirty = true;
  34927. };
  34928. /**
  34929. * Marks the material to indicate that image processing needs to be re-calculated
  34930. */
  34931. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34932. this._areImageProcessingDirty = true;
  34933. this._isDirty = true;
  34934. };
  34935. /**
  34936. * Marks the material to indicate the lights need to be re-calculated
  34937. */
  34938. MaterialDefines.prototype.markAsLightDirty = function () {
  34939. this._areLightsDirty = true;
  34940. this._isDirty = true;
  34941. };
  34942. /**
  34943. * Marks the attribute state as changed
  34944. */
  34945. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34946. this._areAttributesDirty = true;
  34947. this._isDirty = true;
  34948. };
  34949. /**
  34950. * Marks the texture state as changed
  34951. */
  34952. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34953. this._areTexturesDirty = true;
  34954. this._isDirty = true;
  34955. };
  34956. /**
  34957. * Marks the fresnel state as changed
  34958. */
  34959. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34960. this._areFresnelDirty = true;
  34961. this._isDirty = true;
  34962. };
  34963. /**
  34964. * Marks the misc state as changed
  34965. */
  34966. MaterialDefines.prototype.markAsMiscDirty = function () {
  34967. this._areMiscDirty = true;
  34968. this._isDirty = true;
  34969. };
  34970. /**
  34971. * Rebuilds the material defines
  34972. */
  34973. MaterialDefines.prototype.rebuild = function () {
  34974. if (this._keys) {
  34975. delete this._keys;
  34976. }
  34977. this._keys = [];
  34978. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34979. var key = _a[_i];
  34980. if (key[0] === "_") {
  34981. continue;
  34982. }
  34983. this._keys.push(key);
  34984. }
  34985. };
  34986. /**
  34987. * Specifies if two material defines are equal
  34988. * @param other - A material define instance to compare to
  34989. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34990. */
  34991. MaterialDefines.prototype.isEqual = function (other) {
  34992. if (this._keys.length !== other._keys.length) {
  34993. return false;
  34994. }
  34995. for (var index = 0; index < this._keys.length; index++) {
  34996. var prop = this._keys[index];
  34997. if (this[prop] !== other[prop]) {
  34998. return false;
  34999. }
  35000. }
  35001. return true;
  35002. };
  35003. /**
  35004. * Clones this instance's defines to another instance
  35005. * @param other - material defines to clone values to
  35006. */
  35007. MaterialDefines.prototype.cloneTo = function (other) {
  35008. if (this._keys.length !== other._keys.length) {
  35009. other._keys = this._keys.slice(0);
  35010. }
  35011. for (var index = 0; index < this._keys.length; index++) {
  35012. var prop = this._keys[index];
  35013. other[prop] = this[prop];
  35014. }
  35015. };
  35016. /**
  35017. * Resets the material define values
  35018. */
  35019. MaterialDefines.prototype.reset = function () {
  35020. for (var index = 0; index < this._keys.length; index++) {
  35021. var prop = this._keys[index];
  35022. var type = typeof this[prop];
  35023. switch (type) {
  35024. case "number":
  35025. this[prop] = 0;
  35026. break;
  35027. case "string":
  35028. this[prop] = "";
  35029. break;
  35030. default:
  35031. this[prop] = false;
  35032. break;
  35033. }
  35034. }
  35035. };
  35036. /**
  35037. * Converts the material define values to a string
  35038. * @returns - String of material define information
  35039. */
  35040. MaterialDefines.prototype.toString = function () {
  35041. var result = "";
  35042. for (var index = 0; index < this._keys.length; index++) {
  35043. var prop = this._keys[index];
  35044. var value = this[prop];
  35045. var type = typeof value;
  35046. switch (type) {
  35047. case "number":
  35048. case "string":
  35049. result += "#define " + prop + " " + value + "\n";
  35050. break;
  35051. default:
  35052. if (value) {
  35053. result += "#define " + prop + "\n";
  35054. }
  35055. break;
  35056. }
  35057. }
  35058. return result;
  35059. };
  35060. return MaterialDefines;
  35061. }());
  35062. BABYLON.MaterialDefines = MaterialDefines;
  35063. /**
  35064. * Base class for the main features of a material in Babylon.js
  35065. */
  35066. var Material = /** @class */ (function () {
  35067. /**
  35068. * Creates a material instance
  35069. * @param name defines the name of the material
  35070. * @param scene defines the scene to reference
  35071. * @param doNotAdd specifies if the material should be added to the scene
  35072. */
  35073. function Material(name, scene, doNotAdd) {
  35074. /**
  35075. * Specifies if the ready state should be checked on each call
  35076. */
  35077. this.checkReadyOnEveryCall = false;
  35078. /**
  35079. * Specifies if the ready state should be checked once
  35080. */
  35081. this.checkReadyOnlyOnce = false;
  35082. /**
  35083. * The state of the material
  35084. */
  35085. this.state = "";
  35086. /**
  35087. * The alpha value of the material
  35088. */
  35089. this._alpha = 1.0;
  35090. /**
  35091. * Specifies if back face culling is enabled
  35092. */
  35093. this._backFaceCulling = true;
  35094. /**
  35095. * Specifies if the material should be serialized
  35096. */
  35097. this.doNotSerialize = false;
  35098. /**
  35099. * Specifies if the effect should be stored on sub meshes
  35100. */
  35101. this.storeEffectOnSubMeshes = false;
  35102. /**
  35103. * An event triggered when the material is disposed
  35104. */
  35105. this.onDisposeObservable = new BABYLON.Observable();
  35106. /**
  35107. * An event triggered when the material is bound
  35108. */
  35109. this.onBindObservable = new BABYLON.Observable();
  35110. /**
  35111. * An event triggered when the material is unbound
  35112. */
  35113. this.onUnBindObservable = new BABYLON.Observable();
  35114. /**
  35115. * Stores the value of the alpha mode
  35116. */
  35117. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35118. /**
  35119. * Stores the state of the need depth pre-pass value
  35120. */
  35121. this._needDepthPrePass = false;
  35122. /**
  35123. * Specifies if depth writing should be disabled
  35124. */
  35125. this.disableDepthWrite = false;
  35126. /**
  35127. * Specifies if depth writing should be forced
  35128. */
  35129. this.forceDepthWrite = false;
  35130. /**
  35131. * Specifies if there should be a separate pass for culling
  35132. */
  35133. this.separateCullingPass = false;
  35134. /**
  35135. * Stores the state specifing if fog should be enabled
  35136. */
  35137. this._fogEnabled = true;
  35138. /**
  35139. * Stores the size of points
  35140. */
  35141. this.pointSize = 1.0;
  35142. /**
  35143. * Stores the z offset value
  35144. */
  35145. this.zOffset = 0;
  35146. /**
  35147. * Specifies if the material was previously ready
  35148. */
  35149. this._wasPreviouslyReady = false;
  35150. /**
  35151. * Stores the fill mode state
  35152. */
  35153. this._fillMode = Material.TriangleFillMode;
  35154. this.name = name;
  35155. this.id = name || BABYLON.Tools.RandomId();
  35156. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35157. this.uniqueId = this._scene.getUniqueId();
  35158. if (this._scene.useRightHandedSystem) {
  35159. this.sideOrientation = Material.ClockWiseSideOrientation;
  35160. }
  35161. else {
  35162. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35163. }
  35164. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35165. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35166. if (!doNotAdd) {
  35167. this._scene.materials.push(this);
  35168. }
  35169. }
  35170. Object.defineProperty(Material, "TriangleFillMode", {
  35171. /**
  35172. * Returns the triangle fill mode
  35173. */
  35174. get: function () {
  35175. return Material._TriangleFillMode;
  35176. },
  35177. enumerable: true,
  35178. configurable: true
  35179. });
  35180. Object.defineProperty(Material, "WireFrameFillMode", {
  35181. /**
  35182. * Returns the wireframe mode
  35183. */
  35184. get: function () {
  35185. return Material._WireFrameFillMode;
  35186. },
  35187. enumerable: true,
  35188. configurable: true
  35189. });
  35190. Object.defineProperty(Material, "PointFillMode", {
  35191. /**
  35192. * Returns the point fill mode
  35193. */
  35194. get: function () {
  35195. return Material._PointFillMode;
  35196. },
  35197. enumerable: true,
  35198. configurable: true
  35199. });
  35200. Object.defineProperty(Material, "PointListDrawMode", {
  35201. /**
  35202. * Returns the point list draw mode
  35203. */
  35204. get: function () {
  35205. return Material._PointListDrawMode;
  35206. },
  35207. enumerable: true,
  35208. configurable: true
  35209. });
  35210. Object.defineProperty(Material, "LineListDrawMode", {
  35211. /**
  35212. * Returns the line list draw mode
  35213. */
  35214. get: function () {
  35215. return Material._LineListDrawMode;
  35216. },
  35217. enumerable: true,
  35218. configurable: true
  35219. });
  35220. Object.defineProperty(Material, "LineLoopDrawMode", {
  35221. /**
  35222. * Returns the line loop draw mode
  35223. */
  35224. get: function () {
  35225. return Material._LineLoopDrawMode;
  35226. },
  35227. enumerable: true,
  35228. configurable: true
  35229. });
  35230. Object.defineProperty(Material, "LineStripDrawMode", {
  35231. /**
  35232. * Returns the line strip draw mode
  35233. */
  35234. get: function () {
  35235. return Material._LineStripDrawMode;
  35236. },
  35237. enumerable: true,
  35238. configurable: true
  35239. });
  35240. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35241. /**
  35242. * Returns the triangle strip draw mode
  35243. */
  35244. get: function () {
  35245. return Material._TriangleStripDrawMode;
  35246. },
  35247. enumerable: true,
  35248. configurable: true
  35249. });
  35250. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35251. /**
  35252. * Returns the triangle fan draw mode
  35253. */
  35254. get: function () {
  35255. return Material._TriangleFanDrawMode;
  35256. },
  35257. enumerable: true,
  35258. configurable: true
  35259. });
  35260. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35261. /**
  35262. * Returns the clock-wise side orientation
  35263. */
  35264. get: function () {
  35265. return Material._ClockWiseSideOrientation;
  35266. },
  35267. enumerable: true,
  35268. configurable: true
  35269. });
  35270. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35271. /**
  35272. * Returns the counter clock-wise side orientation
  35273. */
  35274. get: function () {
  35275. return Material._CounterClockWiseSideOrientation;
  35276. },
  35277. enumerable: true,
  35278. configurable: true
  35279. });
  35280. Object.defineProperty(Material, "TextureDirtyFlag", {
  35281. /**
  35282. * Returns the dirty texture flag value
  35283. */
  35284. get: function () {
  35285. return Material._TextureDirtyFlag;
  35286. },
  35287. enumerable: true,
  35288. configurable: true
  35289. });
  35290. Object.defineProperty(Material, "LightDirtyFlag", {
  35291. /**
  35292. * Returns the dirty light flag value
  35293. */
  35294. get: function () {
  35295. return Material._LightDirtyFlag;
  35296. },
  35297. enumerable: true,
  35298. configurable: true
  35299. });
  35300. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35301. /**
  35302. * Returns the dirty fresnel flag value
  35303. */
  35304. get: function () {
  35305. return Material._FresnelDirtyFlag;
  35306. },
  35307. enumerable: true,
  35308. configurable: true
  35309. });
  35310. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35311. /**
  35312. * Returns the dirty attributes flag value
  35313. */
  35314. get: function () {
  35315. return Material._AttributesDirtyFlag;
  35316. },
  35317. enumerable: true,
  35318. configurable: true
  35319. });
  35320. Object.defineProperty(Material, "MiscDirtyFlag", {
  35321. /**
  35322. * Returns the dirty misc flag value
  35323. */
  35324. get: function () {
  35325. return Material._MiscDirtyFlag;
  35326. },
  35327. enumerable: true,
  35328. configurable: true
  35329. });
  35330. Object.defineProperty(Material.prototype, "alpha", {
  35331. /**
  35332. * Gets the alpha value of the material
  35333. */
  35334. get: function () {
  35335. return this._alpha;
  35336. },
  35337. /**
  35338. * Sets the alpha value of the material
  35339. */
  35340. set: function (value) {
  35341. if (this._alpha === value) {
  35342. return;
  35343. }
  35344. this._alpha = value;
  35345. this.markAsDirty(Material.MiscDirtyFlag);
  35346. },
  35347. enumerable: true,
  35348. configurable: true
  35349. });
  35350. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35351. /**
  35352. * Gets the back-face culling state
  35353. */
  35354. get: function () {
  35355. return this._backFaceCulling;
  35356. },
  35357. /**
  35358. * Sets the back-face culling state
  35359. */
  35360. set: function (value) {
  35361. if (this._backFaceCulling === value) {
  35362. return;
  35363. }
  35364. this._backFaceCulling = value;
  35365. this.markAsDirty(Material.TextureDirtyFlag);
  35366. },
  35367. enumerable: true,
  35368. configurable: true
  35369. });
  35370. Object.defineProperty(Material.prototype, "onDispose", {
  35371. /**
  35372. * Called during a dispose event
  35373. */
  35374. set: function (callback) {
  35375. if (this._onDisposeObserver) {
  35376. this.onDisposeObservable.remove(this._onDisposeObserver);
  35377. }
  35378. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35379. },
  35380. enumerable: true,
  35381. configurable: true
  35382. });
  35383. Object.defineProperty(Material.prototype, "onBind", {
  35384. /**
  35385. * Called during a bind event
  35386. */
  35387. set: function (callback) {
  35388. if (this._onBindObserver) {
  35389. this.onBindObservable.remove(this._onBindObserver);
  35390. }
  35391. this._onBindObserver = this.onBindObservable.add(callback);
  35392. },
  35393. enumerable: true,
  35394. configurable: true
  35395. });
  35396. Object.defineProperty(Material.prototype, "alphaMode", {
  35397. /**
  35398. * Gets the value of the alpha mode
  35399. */
  35400. get: function () {
  35401. return this._alphaMode;
  35402. },
  35403. /**
  35404. * Sets the value of the alpha mode.
  35405. *
  35406. * | Value | Type | Description |
  35407. * | --- | --- | --- |
  35408. * | 0 | ALPHA_DISABLE | |
  35409. * | 1 | ALPHA_ADD | |
  35410. * | 2 | ALPHA_COMBINE | |
  35411. * | 3 | ALPHA_SUBTRACT | |
  35412. * | 4 | ALPHA_MULTIPLY | |
  35413. * | 5 | ALPHA_MAXIMIZED | |
  35414. * | 6 | ALPHA_ONEONE | |
  35415. * | 7 | ALPHA_PREMULTIPLIED | |
  35416. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35417. * | 9 | ALPHA_INTERPOLATE | |
  35418. * | 10 | ALPHA_SCREENMODE | |
  35419. *
  35420. */
  35421. set: function (value) {
  35422. if (this._alphaMode === value) {
  35423. return;
  35424. }
  35425. this._alphaMode = value;
  35426. this.markAsDirty(Material.TextureDirtyFlag);
  35427. },
  35428. enumerable: true,
  35429. configurable: true
  35430. });
  35431. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35432. /**
  35433. * Gets the depth pre-pass value
  35434. */
  35435. get: function () {
  35436. return this._needDepthPrePass;
  35437. },
  35438. /**
  35439. * Sets the need depth pre-pass value
  35440. */
  35441. set: function (value) {
  35442. if (this._needDepthPrePass === value) {
  35443. return;
  35444. }
  35445. this._needDepthPrePass = value;
  35446. if (this._needDepthPrePass) {
  35447. this.checkReadyOnEveryCall = true;
  35448. }
  35449. },
  35450. enumerable: true,
  35451. configurable: true
  35452. });
  35453. Object.defineProperty(Material.prototype, "fogEnabled", {
  35454. /**
  35455. * Gets the value of the fog enabled state
  35456. */
  35457. get: function () {
  35458. return this._fogEnabled;
  35459. },
  35460. /**
  35461. * Sets the state for enabling fog
  35462. */
  35463. set: function (value) {
  35464. if (this._fogEnabled === value) {
  35465. return;
  35466. }
  35467. this._fogEnabled = value;
  35468. this.markAsDirty(Material.MiscDirtyFlag);
  35469. },
  35470. enumerable: true,
  35471. configurable: true
  35472. });
  35473. Object.defineProperty(Material.prototype, "wireframe", {
  35474. /**
  35475. * Gets a value specifying if wireframe mode is enabled
  35476. */
  35477. get: function () {
  35478. switch (this._fillMode) {
  35479. case Material.WireFrameFillMode:
  35480. case Material.LineListDrawMode:
  35481. case Material.LineLoopDrawMode:
  35482. case Material.LineStripDrawMode:
  35483. return true;
  35484. }
  35485. return this._scene.forceWireframe;
  35486. },
  35487. /**
  35488. * Sets the state of wireframe mode
  35489. */
  35490. set: function (value) {
  35491. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35492. },
  35493. enumerable: true,
  35494. configurable: true
  35495. });
  35496. Object.defineProperty(Material.prototype, "pointsCloud", {
  35497. /**
  35498. * Gets the value specifying if point clouds are enabled
  35499. */
  35500. get: function () {
  35501. switch (this._fillMode) {
  35502. case Material.PointFillMode:
  35503. case Material.PointListDrawMode:
  35504. return true;
  35505. }
  35506. return this._scene.forcePointsCloud;
  35507. },
  35508. /**
  35509. * Sets the state of point cloud mode
  35510. */
  35511. set: function (value) {
  35512. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35513. },
  35514. enumerable: true,
  35515. configurable: true
  35516. });
  35517. Object.defineProperty(Material.prototype, "fillMode", {
  35518. /**
  35519. * Gets the material fill mode
  35520. */
  35521. get: function () {
  35522. return this._fillMode;
  35523. },
  35524. /**
  35525. * Sets the material fill mode
  35526. */
  35527. set: function (value) {
  35528. if (this._fillMode === value) {
  35529. return;
  35530. }
  35531. this._fillMode = value;
  35532. this.markAsDirty(Material.MiscDirtyFlag);
  35533. },
  35534. enumerable: true,
  35535. configurable: true
  35536. });
  35537. /**
  35538. * Returns a string representation of the current material
  35539. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35540. * @returns a string with material information
  35541. */
  35542. Material.prototype.toString = function (fullDetails) {
  35543. var ret = "Name: " + this.name;
  35544. if (fullDetails) {
  35545. }
  35546. return ret;
  35547. };
  35548. /**
  35549. * Gets the class name of the material
  35550. * @returns a string with the class name of the material
  35551. */
  35552. Material.prototype.getClassName = function () {
  35553. return "Material";
  35554. };
  35555. Object.defineProperty(Material.prototype, "isFrozen", {
  35556. /**
  35557. * Specifies if updates for the material been locked
  35558. */
  35559. get: function () {
  35560. return this.checkReadyOnlyOnce;
  35561. },
  35562. enumerable: true,
  35563. configurable: true
  35564. });
  35565. /**
  35566. * Locks updates for the material
  35567. */
  35568. Material.prototype.freeze = function () {
  35569. this.checkReadyOnlyOnce = true;
  35570. };
  35571. /**
  35572. * Unlocks updates for the material
  35573. */
  35574. Material.prototype.unfreeze = function () {
  35575. this.checkReadyOnlyOnce = false;
  35576. };
  35577. /**
  35578. * Specifies if the material is ready to be used
  35579. * @param mesh defines the mesh to check
  35580. * @param useInstances specifies if instances should be used
  35581. * @returns a boolean indicating if the material is ready to be used
  35582. */
  35583. Material.prototype.isReady = function (mesh, useInstances) {
  35584. return true;
  35585. };
  35586. /**
  35587. * Specifies that the submesh is ready to be used
  35588. * @param mesh defines the mesh to check
  35589. * @param subMesh defines which submesh to check
  35590. * @param useInstances specifies that instances should be used
  35591. * @returns a boolean indicating that the submesh is ready or not
  35592. */
  35593. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35594. return false;
  35595. };
  35596. /**
  35597. * Returns the material effect
  35598. * @returns the effect associated with the material
  35599. */
  35600. Material.prototype.getEffect = function () {
  35601. return this._effect;
  35602. };
  35603. /**
  35604. * Returns the current scene
  35605. * @returns a Scene
  35606. */
  35607. Material.prototype.getScene = function () {
  35608. return this._scene;
  35609. };
  35610. /**
  35611. * Specifies if the material will require alpha blending
  35612. * @returns a boolean specifying if alpha blending is needed
  35613. */
  35614. Material.prototype.needAlphaBlending = function () {
  35615. return (this.alpha < 1.0);
  35616. };
  35617. /**
  35618. * Specifies if the mesh will require alpha blending
  35619. * @param mesh defines the mesh to check
  35620. * @returns a boolean specifying if alpha blending is needed for the mesh
  35621. */
  35622. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35623. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35624. };
  35625. /**
  35626. * Specifies if this material should be rendered in alpha test mode
  35627. * @returns a boolean specifying if an alpha test is needed.
  35628. */
  35629. Material.prototype.needAlphaTesting = function () {
  35630. return false;
  35631. };
  35632. /**
  35633. * Gets the texture used for the alpha test
  35634. * @returns the texture to use for alpha testing
  35635. */
  35636. Material.prototype.getAlphaTestTexture = function () {
  35637. return null;
  35638. };
  35639. /**
  35640. * Marks the material to indicate that it needs to be re-calculated
  35641. */
  35642. Material.prototype.markDirty = function () {
  35643. this._wasPreviouslyReady = false;
  35644. };
  35645. /** @hidden */
  35646. Material.prototype._preBind = function (effect, overrideOrientation) {
  35647. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35648. var engine = this._scene.getEngine();
  35649. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35650. var reverse = orientation === Material.ClockWiseSideOrientation;
  35651. engine.enableEffect(effect ? effect : this._effect);
  35652. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35653. return reverse;
  35654. };
  35655. /**
  35656. * Binds the material to the mesh
  35657. * @param world defines the world transformation matrix
  35658. * @param mesh defines the mesh to bind the material to
  35659. */
  35660. Material.prototype.bind = function (world, mesh) {
  35661. };
  35662. /**
  35663. * Binds the submesh to the material
  35664. * @param world defines the world transformation matrix
  35665. * @param mesh defines the mesh containing the submesh
  35666. * @param subMesh defines the submesh to bind the material to
  35667. */
  35668. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35669. };
  35670. /**
  35671. * Binds the world matrix to the material
  35672. * @param world defines the world transformation matrix
  35673. */
  35674. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35675. };
  35676. /**
  35677. * Binds the scene's uniform buffer to the effect.
  35678. * @param effect defines the effect to bind to the scene uniform buffer
  35679. * @param sceneUbo defines the uniform buffer storing scene data
  35680. */
  35681. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35682. sceneUbo.bindToEffect(effect, "Scene");
  35683. };
  35684. /**
  35685. * Binds the view matrix to the effect
  35686. * @param effect defines the effect to bind the view matrix to
  35687. */
  35688. Material.prototype.bindView = function (effect) {
  35689. if (!this._useUBO) {
  35690. effect.setMatrix("view", this.getScene().getViewMatrix());
  35691. }
  35692. else {
  35693. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35694. }
  35695. };
  35696. /**
  35697. * Binds the view projection matrix to the effect
  35698. * @param effect defines the effect to bind the view projection matrix to
  35699. */
  35700. Material.prototype.bindViewProjection = function (effect) {
  35701. if (!this._useUBO) {
  35702. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35703. }
  35704. else {
  35705. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35706. }
  35707. };
  35708. /**
  35709. * Specifies if material alpha testing should be turned on for the mesh
  35710. * @param mesh defines the mesh to check
  35711. */
  35712. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35713. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35714. };
  35715. /**
  35716. * Processes to execute after binding the material to a mesh
  35717. * @param mesh defines the rendered mesh
  35718. */
  35719. Material.prototype._afterBind = function (mesh) {
  35720. this._scene._cachedMaterial = this;
  35721. if (mesh) {
  35722. this._scene._cachedVisibility = mesh.visibility;
  35723. }
  35724. else {
  35725. this._scene._cachedVisibility = 1;
  35726. }
  35727. if (mesh) {
  35728. this.onBindObservable.notifyObservers(mesh);
  35729. }
  35730. if (this.disableDepthWrite) {
  35731. var engine = this._scene.getEngine();
  35732. this._cachedDepthWriteState = engine.getDepthWrite();
  35733. engine.setDepthWrite(false);
  35734. }
  35735. };
  35736. /**
  35737. * Unbinds the material from the mesh
  35738. */
  35739. Material.prototype.unbind = function () {
  35740. this.onUnBindObservable.notifyObservers(this);
  35741. if (this.disableDepthWrite) {
  35742. var engine = this._scene.getEngine();
  35743. engine.setDepthWrite(this._cachedDepthWriteState);
  35744. }
  35745. };
  35746. /**
  35747. * Gets the active textures from the material
  35748. * @returns an array of textures
  35749. */
  35750. Material.prototype.getActiveTextures = function () {
  35751. return [];
  35752. };
  35753. /**
  35754. * Specifies if the material uses a texture
  35755. * @param texture defines the texture to check against the material
  35756. * @returns a boolean specifying if the material uses the texture
  35757. */
  35758. Material.prototype.hasTexture = function (texture) {
  35759. return false;
  35760. };
  35761. /**
  35762. * Makes a duplicate of the material, and gives it a new name
  35763. * @param name defines the new name for the duplicated material
  35764. * @returns the cloned material
  35765. */
  35766. Material.prototype.clone = function (name) {
  35767. return null;
  35768. };
  35769. /**
  35770. * Gets the meshes bound to the material
  35771. * @returns an array of meshes bound to the material
  35772. */
  35773. Material.prototype.getBindedMeshes = function () {
  35774. var result = new Array();
  35775. for (var index = 0; index < this._scene.meshes.length; index++) {
  35776. var mesh = this._scene.meshes[index];
  35777. if (mesh.material === this) {
  35778. result.push(mesh);
  35779. }
  35780. }
  35781. return result;
  35782. };
  35783. /**
  35784. * Force shader compilation
  35785. * @param mesh defines the mesh associated with this material
  35786. * @param onCompiled defines a function to execute once the material is compiled
  35787. * @param options defines the options to configure the compilation
  35788. */
  35789. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35790. var _this = this;
  35791. var localOptions = __assign({ clipPlane: false }, options);
  35792. var subMesh = new BABYLON.BaseSubMesh();
  35793. var scene = this.getScene();
  35794. var checkReady = function () {
  35795. if (!_this._scene || !_this._scene.getEngine()) {
  35796. return;
  35797. }
  35798. if (subMesh._materialDefines) {
  35799. subMesh._materialDefines._renderId = -1;
  35800. }
  35801. var clipPlaneState = scene.clipPlane;
  35802. if (localOptions.clipPlane) {
  35803. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35804. }
  35805. if (_this.storeEffectOnSubMeshes) {
  35806. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35807. if (onCompiled) {
  35808. onCompiled(_this);
  35809. }
  35810. }
  35811. else {
  35812. setTimeout(checkReady, 16);
  35813. }
  35814. }
  35815. else {
  35816. if (_this.isReady(mesh)) {
  35817. if (onCompiled) {
  35818. onCompiled(_this);
  35819. }
  35820. }
  35821. else {
  35822. setTimeout(checkReady, 16);
  35823. }
  35824. }
  35825. if (localOptions.clipPlane) {
  35826. scene.clipPlane = clipPlaneState;
  35827. }
  35828. };
  35829. checkReady();
  35830. };
  35831. /**
  35832. * Force shader compilation
  35833. * @param mesh defines the mesh that will use this material
  35834. * @param options defines additional options for compiling the shaders
  35835. * @returns a promise that resolves when the compilation completes
  35836. */
  35837. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35838. var _this = this;
  35839. return new Promise(function (resolve) {
  35840. _this.forceCompilation(mesh, function () {
  35841. resolve();
  35842. }, options);
  35843. });
  35844. };
  35845. /**
  35846. * Marks a define in the material to indicate that it needs to be re-computed
  35847. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35848. */
  35849. Material.prototype.markAsDirty = function (flag) {
  35850. if (flag & Material.TextureDirtyFlag) {
  35851. this._markAllSubMeshesAsTexturesDirty();
  35852. }
  35853. if (flag & Material.LightDirtyFlag) {
  35854. this._markAllSubMeshesAsLightsDirty();
  35855. }
  35856. if (flag & Material.FresnelDirtyFlag) {
  35857. this._markAllSubMeshesAsFresnelDirty();
  35858. }
  35859. if (flag & Material.AttributesDirtyFlag) {
  35860. this._markAllSubMeshesAsAttributesDirty();
  35861. }
  35862. if (flag & Material.MiscDirtyFlag) {
  35863. this._markAllSubMeshesAsMiscDirty();
  35864. }
  35865. this.getScene().resetCachedMaterial();
  35866. };
  35867. /**
  35868. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35869. * @param func defines a function which checks material defines against the submeshes
  35870. */
  35871. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35872. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35873. var mesh = _a[_i];
  35874. if (!mesh.subMeshes) {
  35875. continue;
  35876. }
  35877. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35878. var subMesh = _c[_b];
  35879. if (subMesh.getMaterial() !== this) {
  35880. continue;
  35881. }
  35882. if (!subMesh._materialDefines) {
  35883. continue;
  35884. }
  35885. func(subMesh._materialDefines);
  35886. }
  35887. }
  35888. };
  35889. /**
  35890. * Indicates that image processing needs to be re-calculated for all submeshes
  35891. */
  35892. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35893. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35894. };
  35895. /**
  35896. * Indicates that textures need to be re-calculated for all submeshes
  35897. */
  35898. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35899. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35900. };
  35901. /**
  35902. * Indicates that fresnel needs to be re-calculated for all submeshes
  35903. */
  35904. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35905. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35906. };
  35907. /**
  35908. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35909. */
  35910. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35911. this._markAllSubMeshesAsDirty(function (defines) {
  35912. defines.markAsFresnelDirty();
  35913. defines.markAsMiscDirty();
  35914. });
  35915. };
  35916. /**
  35917. * Indicates that lights need to be re-calculated for all submeshes
  35918. */
  35919. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35920. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35921. };
  35922. /**
  35923. * Indicates that attributes need to be re-calculated for all submeshes
  35924. */
  35925. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35926. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35927. };
  35928. /**
  35929. * Indicates that misc needs to be re-calculated for all submeshes
  35930. */
  35931. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35932. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35933. };
  35934. /**
  35935. * Indicates that textures and misc need to be re-calculated for all submeshes
  35936. */
  35937. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35938. this._markAllSubMeshesAsDirty(function (defines) {
  35939. defines.markAsTexturesDirty();
  35940. defines.markAsMiscDirty();
  35941. });
  35942. };
  35943. /**
  35944. * Disposes the material
  35945. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35946. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35947. */
  35948. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35949. // Animations
  35950. this.getScene().stopAnimation(this);
  35951. this.getScene().freeProcessedMaterials();
  35952. // Remove from scene
  35953. var index = this._scene.materials.indexOf(this);
  35954. if (index >= 0) {
  35955. this._scene.materials.splice(index, 1);
  35956. }
  35957. // Remove from meshes
  35958. for (index = 0; index < this._scene.meshes.length; index++) {
  35959. var mesh = this._scene.meshes[index];
  35960. if (mesh.material === this) {
  35961. mesh.material = null;
  35962. if (mesh.geometry) {
  35963. var geometry = (mesh.geometry);
  35964. if (this.storeEffectOnSubMeshes) {
  35965. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35966. var subMesh = _a[_i];
  35967. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35968. if (forceDisposeEffect && subMesh._materialEffect) {
  35969. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35970. }
  35971. }
  35972. }
  35973. else {
  35974. geometry._releaseVertexArrayObject(this._effect);
  35975. }
  35976. }
  35977. }
  35978. }
  35979. this._uniformBuffer.dispose();
  35980. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35981. if (forceDisposeEffect && this._effect) {
  35982. if (!this.storeEffectOnSubMeshes) {
  35983. this._scene.getEngine()._releaseEffect(this._effect);
  35984. }
  35985. this._effect = null;
  35986. }
  35987. // Callback
  35988. this.onDisposeObservable.notifyObservers(this);
  35989. this.onDisposeObservable.clear();
  35990. this.onBindObservable.clear();
  35991. this.onUnBindObservable.clear();
  35992. };
  35993. /**
  35994. * Serializes this material
  35995. * @returns the serialized material object
  35996. */
  35997. Material.prototype.serialize = function () {
  35998. return BABYLON.SerializationHelper.Serialize(this);
  35999. };
  36000. /**
  36001. * Creates a MultiMaterial from parsed MultiMaterial data.
  36002. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36003. * @param scene defines the hosting scene
  36004. * @returns a new MultiMaterial
  36005. */
  36006. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36007. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36008. multiMaterial.id = parsedMultiMaterial.id;
  36009. if (BABYLON.Tags) {
  36010. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36011. }
  36012. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36013. var subMatId = parsedMultiMaterial.materials[matIndex];
  36014. if (subMatId) {
  36015. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36016. }
  36017. else {
  36018. multiMaterial.subMaterials.push(null);
  36019. }
  36020. }
  36021. return multiMaterial;
  36022. };
  36023. /**
  36024. * Creates a material from parsed material data
  36025. * @param parsedMaterial defines parsed material data
  36026. * @param scene defines the hosting scene
  36027. * @param rootUrl defines the root URL to use to load textures
  36028. * @returns a new material
  36029. */
  36030. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36031. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36032. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36033. }
  36034. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36035. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36036. if (!BABYLON.LegacyPBRMaterial) {
  36037. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36038. return;
  36039. }
  36040. }
  36041. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36042. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36043. };
  36044. // Triangle views
  36045. Material._TriangleFillMode = 0;
  36046. Material._WireFrameFillMode = 1;
  36047. Material._PointFillMode = 2;
  36048. // Draw modes
  36049. Material._PointListDrawMode = 3;
  36050. Material._LineListDrawMode = 4;
  36051. Material._LineLoopDrawMode = 5;
  36052. Material._LineStripDrawMode = 6;
  36053. Material._TriangleStripDrawMode = 7;
  36054. Material._TriangleFanDrawMode = 8;
  36055. /**
  36056. * Stores the clock-wise side orientation
  36057. */
  36058. Material._ClockWiseSideOrientation = 0;
  36059. /**
  36060. * Stores the counter clock-wise side orientation
  36061. */
  36062. Material._CounterClockWiseSideOrientation = 1;
  36063. /**
  36064. * The dirty texture flag value
  36065. */
  36066. Material._TextureDirtyFlag = 1;
  36067. /**
  36068. * The dirty light flag value
  36069. */
  36070. Material._LightDirtyFlag = 2;
  36071. /**
  36072. * The dirty fresnel flag value
  36073. */
  36074. Material._FresnelDirtyFlag = 4;
  36075. /**
  36076. * The dirty attribute flag value
  36077. */
  36078. Material._AttributesDirtyFlag = 8;
  36079. /**
  36080. * The dirty misc flag value
  36081. */
  36082. Material._MiscDirtyFlag = 16;
  36083. __decorate([
  36084. BABYLON.serialize()
  36085. ], Material.prototype, "id", void 0);
  36086. __decorate([
  36087. BABYLON.serialize()
  36088. ], Material.prototype, "uniqueId", void 0);
  36089. __decorate([
  36090. BABYLON.serialize()
  36091. ], Material.prototype, "name", void 0);
  36092. __decorate([
  36093. BABYLON.serialize()
  36094. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36095. __decorate([
  36096. BABYLON.serialize()
  36097. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36098. __decorate([
  36099. BABYLON.serialize()
  36100. ], Material.prototype, "state", void 0);
  36101. __decorate([
  36102. BABYLON.serialize("alpha")
  36103. ], Material.prototype, "_alpha", void 0);
  36104. __decorate([
  36105. BABYLON.serialize("backFaceCulling")
  36106. ], Material.prototype, "_backFaceCulling", void 0);
  36107. __decorate([
  36108. BABYLON.serialize()
  36109. ], Material.prototype, "sideOrientation", void 0);
  36110. __decorate([
  36111. BABYLON.serialize("alphaMode")
  36112. ], Material.prototype, "_alphaMode", void 0);
  36113. __decorate([
  36114. BABYLON.serialize()
  36115. ], Material.prototype, "_needDepthPrePass", void 0);
  36116. __decorate([
  36117. BABYLON.serialize()
  36118. ], Material.prototype, "disableDepthWrite", void 0);
  36119. __decorate([
  36120. BABYLON.serialize()
  36121. ], Material.prototype, "forceDepthWrite", void 0);
  36122. __decorate([
  36123. BABYLON.serialize()
  36124. ], Material.prototype, "separateCullingPass", void 0);
  36125. __decorate([
  36126. BABYLON.serialize("fogEnabled")
  36127. ], Material.prototype, "_fogEnabled", void 0);
  36128. __decorate([
  36129. BABYLON.serialize()
  36130. ], Material.prototype, "pointSize", void 0);
  36131. __decorate([
  36132. BABYLON.serialize()
  36133. ], Material.prototype, "zOffset", void 0);
  36134. __decorate([
  36135. BABYLON.serialize()
  36136. ], Material.prototype, "wireframe", null);
  36137. __decorate([
  36138. BABYLON.serialize()
  36139. ], Material.prototype, "pointsCloud", null);
  36140. __decorate([
  36141. BABYLON.serialize()
  36142. ], Material.prototype, "fillMode", null);
  36143. return Material;
  36144. }());
  36145. BABYLON.Material = Material;
  36146. })(BABYLON || (BABYLON = {}));
  36147. //# sourceMappingURL=babylon.material.js.map
  36148. var BABYLON;
  36149. (function (BABYLON) {
  36150. var UniformBuffer = /** @class */ (function () {
  36151. /**
  36152. * Uniform buffer objects.
  36153. *
  36154. * Handles blocks of uniform on the GPU.
  36155. *
  36156. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36157. *
  36158. * For more information, please refer to :
  36159. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36160. */
  36161. function UniformBuffer(engine, data, dynamic) {
  36162. this._engine = engine;
  36163. this._noUBO = !engine.supportsUniformBuffers;
  36164. this._dynamic = dynamic;
  36165. this._data = data || [];
  36166. this._uniformLocations = {};
  36167. this._uniformSizes = {};
  36168. this._uniformLocationPointer = 0;
  36169. this._needSync = false;
  36170. if (this._noUBO) {
  36171. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36172. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36173. this.updateFloat = this._updateFloatForEffect;
  36174. this.updateFloat2 = this._updateFloat2ForEffect;
  36175. this.updateFloat3 = this._updateFloat3ForEffect;
  36176. this.updateFloat4 = this._updateFloat4ForEffect;
  36177. this.updateMatrix = this._updateMatrixForEffect;
  36178. this.updateVector3 = this._updateVector3ForEffect;
  36179. this.updateVector4 = this._updateVector4ForEffect;
  36180. this.updateColor3 = this._updateColor3ForEffect;
  36181. this.updateColor4 = this._updateColor4ForEffect;
  36182. }
  36183. else {
  36184. this._engine._uniformBuffers.push(this);
  36185. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36186. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36187. this.updateFloat = this._updateFloatForUniform;
  36188. this.updateFloat2 = this._updateFloat2ForUniform;
  36189. this.updateFloat3 = this._updateFloat3ForUniform;
  36190. this.updateFloat4 = this._updateFloat4ForUniform;
  36191. this.updateMatrix = this._updateMatrixForUniform;
  36192. this.updateVector3 = this._updateVector3ForUniform;
  36193. this.updateVector4 = this._updateVector4ForUniform;
  36194. this.updateColor3 = this._updateColor3ForUniform;
  36195. this.updateColor4 = this._updateColor4ForUniform;
  36196. }
  36197. }
  36198. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36199. // Properties
  36200. /**
  36201. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36202. * or just falling back on setUniformXXX calls.
  36203. */
  36204. get: function () {
  36205. return !this._noUBO;
  36206. },
  36207. enumerable: true,
  36208. configurable: true
  36209. });
  36210. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36211. /**
  36212. * Indicates if the WebGL underlying uniform buffer is in sync
  36213. * with the javascript cache data.
  36214. */
  36215. get: function () {
  36216. return !this._needSync;
  36217. },
  36218. enumerable: true,
  36219. configurable: true
  36220. });
  36221. /**
  36222. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36223. * Also, a dynamic UniformBuffer will disable cache verification and always
  36224. * update the underlying WebGL uniform buffer to the GPU.
  36225. */
  36226. UniformBuffer.prototype.isDynamic = function () {
  36227. return this._dynamic !== undefined;
  36228. };
  36229. /**
  36230. * The data cache on JS side.
  36231. */
  36232. UniformBuffer.prototype.getData = function () {
  36233. return this._bufferData;
  36234. };
  36235. /**
  36236. * The underlying WebGL Uniform buffer.
  36237. */
  36238. UniformBuffer.prototype.getBuffer = function () {
  36239. return this._buffer;
  36240. };
  36241. /**
  36242. * std140 layout specifies how to align data within an UBO structure.
  36243. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36244. * for specs.
  36245. */
  36246. UniformBuffer.prototype._fillAlignment = function (size) {
  36247. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36248. // and 4x4 matrices
  36249. // TODO : change if other types are used
  36250. var alignment;
  36251. if (size <= 2) {
  36252. alignment = size;
  36253. }
  36254. else {
  36255. alignment = 4;
  36256. }
  36257. if ((this._uniformLocationPointer % alignment) !== 0) {
  36258. var oldPointer = this._uniformLocationPointer;
  36259. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36260. var diff = this._uniformLocationPointer - oldPointer;
  36261. for (var i = 0; i < diff; i++) {
  36262. this._data.push(0);
  36263. }
  36264. }
  36265. };
  36266. /**
  36267. * Adds an uniform in the buffer.
  36268. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36269. * for the layout to be correct !
  36270. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36271. * @param {number|number[]} size Data size, or data directly.
  36272. */
  36273. UniformBuffer.prototype.addUniform = function (name, size) {
  36274. if (this._noUBO) {
  36275. return;
  36276. }
  36277. if (this._uniformLocations[name] !== undefined) {
  36278. // Already existing uniform
  36279. return;
  36280. }
  36281. // This function must be called in the order of the shader layout !
  36282. // size can be the size of the uniform, or data directly
  36283. var data;
  36284. if (size instanceof Array) {
  36285. data = size;
  36286. size = data.length;
  36287. }
  36288. else {
  36289. size = size;
  36290. data = [];
  36291. // Fill with zeros
  36292. for (var i = 0; i < size; i++) {
  36293. data.push(0);
  36294. }
  36295. }
  36296. this._fillAlignment(size);
  36297. this._uniformSizes[name] = size;
  36298. this._uniformLocations[name] = this._uniformLocationPointer;
  36299. this._uniformLocationPointer += size;
  36300. for (var i = 0; i < size; i++) {
  36301. this._data.push(data[i]);
  36302. }
  36303. this._needSync = true;
  36304. };
  36305. /**
  36306. * Wrapper for addUniform.
  36307. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36308. * @param {Matrix} mat A 4x4 matrix.
  36309. */
  36310. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36311. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36312. };
  36313. /**
  36314. * Wrapper for addUniform.
  36315. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36316. * @param {number} x
  36317. * @param {number} y
  36318. */
  36319. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36320. var temp = [x, y];
  36321. this.addUniform(name, temp);
  36322. };
  36323. /**
  36324. * Wrapper for addUniform.
  36325. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36326. * @param {number} x
  36327. * @param {number} y
  36328. * @param {number} z
  36329. */
  36330. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36331. var temp = [x, y, z];
  36332. this.addUniform(name, temp);
  36333. };
  36334. /**
  36335. * Wrapper for addUniform.
  36336. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36337. * @param {Color3} color
  36338. */
  36339. UniformBuffer.prototype.addColor3 = function (name, color) {
  36340. var temp = new Array();
  36341. color.toArray(temp);
  36342. this.addUniform(name, temp);
  36343. };
  36344. /**
  36345. * Wrapper for addUniform.
  36346. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36347. * @param {Color3} color
  36348. * @param {number} alpha
  36349. */
  36350. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36351. var temp = new Array();
  36352. color.toArray(temp);
  36353. temp.push(alpha);
  36354. this.addUniform(name, temp);
  36355. };
  36356. /**
  36357. * Wrapper for addUniform.
  36358. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36359. * @param {Vector3} vector
  36360. */
  36361. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36362. var temp = new Array();
  36363. vector.toArray(temp);
  36364. this.addUniform(name, temp);
  36365. };
  36366. /**
  36367. * Wrapper for addUniform.
  36368. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36369. */
  36370. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36371. this.addUniform(name, 12);
  36372. };
  36373. /**
  36374. * Wrapper for addUniform.
  36375. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36376. */
  36377. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36378. this.addUniform(name, 8);
  36379. };
  36380. /**
  36381. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36382. */
  36383. UniformBuffer.prototype.create = function () {
  36384. if (this._noUBO) {
  36385. return;
  36386. }
  36387. if (this._buffer) {
  36388. return; // nothing to do
  36389. }
  36390. // See spec, alignment must be filled as a vec4
  36391. this._fillAlignment(4);
  36392. this._bufferData = new Float32Array(this._data);
  36393. this._rebuild();
  36394. this._needSync = true;
  36395. };
  36396. UniformBuffer.prototype._rebuild = function () {
  36397. if (this._noUBO) {
  36398. return;
  36399. }
  36400. if (this._dynamic) {
  36401. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36402. }
  36403. else {
  36404. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36405. }
  36406. };
  36407. /**
  36408. * Updates the WebGL Uniform Buffer on the GPU.
  36409. * If the `dynamic` flag is set to true, no cache comparison is done.
  36410. * Otherwise, the buffer will be updated only if the cache differs.
  36411. */
  36412. UniformBuffer.prototype.update = function () {
  36413. if (!this._buffer) {
  36414. this.create();
  36415. return;
  36416. }
  36417. if (!this._dynamic && !this._needSync) {
  36418. return;
  36419. }
  36420. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36421. this._needSync = false;
  36422. };
  36423. /**
  36424. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36425. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36426. * @param {number[]|Float32Array} data Flattened data
  36427. * @param {number} size Size of the data.
  36428. */
  36429. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36430. var location = this._uniformLocations[uniformName];
  36431. if (location === undefined) {
  36432. if (this._buffer) {
  36433. // Cannot add an uniform if the buffer is already created
  36434. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36435. return;
  36436. }
  36437. this.addUniform(uniformName, size);
  36438. location = this._uniformLocations[uniformName];
  36439. }
  36440. if (!this._buffer) {
  36441. this.create();
  36442. }
  36443. if (!this._dynamic) {
  36444. // Cache for static uniform buffers
  36445. var changed = false;
  36446. for (var i = 0; i < size; i++) {
  36447. if (this._bufferData[location + i] !== data[i]) {
  36448. changed = true;
  36449. this._bufferData[location + i] = data[i];
  36450. }
  36451. }
  36452. this._needSync = this._needSync || changed;
  36453. }
  36454. else {
  36455. // No cache for dynamic
  36456. for (var i = 0; i < size; i++) {
  36457. this._bufferData[location + i] = data[i];
  36458. }
  36459. }
  36460. };
  36461. // Update methods
  36462. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36463. // To match std140, matrix must be realigned
  36464. for (var i = 0; i < 3; i++) {
  36465. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36466. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36467. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36468. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36469. }
  36470. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36471. };
  36472. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36473. this._currentEffect.setMatrix3x3(name, matrix);
  36474. };
  36475. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36476. this._currentEffect.setMatrix2x2(name, matrix);
  36477. };
  36478. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36479. // To match std140, matrix must be realigned
  36480. for (var i = 0; i < 2; i++) {
  36481. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36482. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36483. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36484. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36485. }
  36486. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36487. };
  36488. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36489. this._currentEffect.setFloat(name, x);
  36490. };
  36491. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36492. UniformBuffer._tempBuffer[0] = x;
  36493. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36494. };
  36495. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36496. if (suffix === void 0) { suffix = ""; }
  36497. this._currentEffect.setFloat2(name + suffix, x, y);
  36498. };
  36499. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36500. if (suffix === void 0) { suffix = ""; }
  36501. UniformBuffer._tempBuffer[0] = x;
  36502. UniformBuffer._tempBuffer[1] = y;
  36503. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36504. };
  36505. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36506. if (suffix === void 0) { suffix = ""; }
  36507. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36508. };
  36509. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36510. if (suffix === void 0) { suffix = ""; }
  36511. UniformBuffer._tempBuffer[0] = x;
  36512. UniformBuffer._tempBuffer[1] = y;
  36513. UniformBuffer._tempBuffer[2] = z;
  36514. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36515. };
  36516. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36517. if (suffix === void 0) { suffix = ""; }
  36518. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36519. };
  36520. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36521. if (suffix === void 0) { suffix = ""; }
  36522. UniformBuffer._tempBuffer[0] = x;
  36523. UniformBuffer._tempBuffer[1] = y;
  36524. UniformBuffer._tempBuffer[2] = z;
  36525. UniformBuffer._tempBuffer[3] = w;
  36526. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36527. };
  36528. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36529. this._currentEffect.setMatrix(name, mat);
  36530. };
  36531. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36532. this.updateUniform(name, mat.toArray(), 16);
  36533. };
  36534. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36535. this._currentEffect.setVector3(name, vector);
  36536. };
  36537. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36538. vector.toArray(UniformBuffer._tempBuffer);
  36539. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36540. };
  36541. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36542. this._currentEffect.setVector4(name, vector);
  36543. };
  36544. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36545. vector.toArray(UniformBuffer._tempBuffer);
  36546. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36547. };
  36548. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36549. if (suffix === void 0) { suffix = ""; }
  36550. this._currentEffect.setColor3(name + suffix, color);
  36551. };
  36552. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36553. if (suffix === void 0) { suffix = ""; }
  36554. color.toArray(UniformBuffer._tempBuffer);
  36555. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36556. };
  36557. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36558. if (suffix === void 0) { suffix = ""; }
  36559. this._currentEffect.setColor4(name + suffix, color, alpha);
  36560. };
  36561. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36562. if (suffix === void 0) { suffix = ""; }
  36563. color.toArray(UniformBuffer._tempBuffer);
  36564. UniformBuffer._tempBuffer[3] = alpha;
  36565. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36566. };
  36567. /**
  36568. * Sets a sampler uniform on the effect.
  36569. * @param {string} name Name of the sampler.
  36570. * @param {Texture} texture
  36571. */
  36572. UniformBuffer.prototype.setTexture = function (name, texture) {
  36573. this._currentEffect.setTexture(name, texture);
  36574. };
  36575. /**
  36576. * Directly updates the value of the uniform in the cache AND on the GPU.
  36577. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36578. * @param {number[]|Float32Array} data Flattened data
  36579. */
  36580. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36581. this.updateUniform(uniformName, data, data.length);
  36582. this.update();
  36583. };
  36584. /**
  36585. * Binds this uniform buffer to an effect.
  36586. * @param {Effect} effect
  36587. * @param {string} name Name of the uniform block in the shader.
  36588. */
  36589. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36590. this._currentEffect = effect;
  36591. if (this._noUBO || !this._buffer) {
  36592. return;
  36593. }
  36594. effect.bindUniformBuffer(this._buffer, name);
  36595. };
  36596. /**
  36597. * Disposes the uniform buffer.
  36598. */
  36599. UniformBuffer.prototype.dispose = function () {
  36600. if (this._noUBO) {
  36601. return;
  36602. }
  36603. var index = this._engine._uniformBuffers.indexOf(this);
  36604. if (index !== -1) {
  36605. this._engine._uniformBuffers.splice(index, 1);
  36606. }
  36607. if (!this._buffer) {
  36608. return;
  36609. }
  36610. if (this._engine._releaseBuffer(this._buffer)) {
  36611. this._buffer = null;
  36612. }
  36613. };
  36614. // Pool for avoiding memory leaks
  36615. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36616. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36617. return UniformBuffer;
  36618. }());
  36619. BABYLON.UniformBuffer = UniformBuffer;
  36620. })(BABYLON || (BABYLON = {}));
  36621. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36622. var BABYLON;
  36623. (function (BABYLON) {
  36624. /**
  36625. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36626. */
  36627. var VertexData = /** @class */ (function () {
  36628. function VertexData() {
  36629. }
  36630. /**
  36631. * Uses the passed data array to set the set the values for the specified kind of data
  36632. * @param data a linear array of floating numbers
  36633. * @param kind the type of data that is being set, eg positions, colors etc
  36634. */
  36635. VertexData.prototype.set = function (data, kind) {
  36636. switch (kind) {
  36637. case BABYLON.VertexBuffer.PositionKind:
  36638. this.positions = data;
  36639. break;
  36640. case BABYLON.VertexBuffer.NormalKind:
  36641. this.normals = data;
  36642. break;
  36643. case BABYLON.VertexBuffer.TangentKind:
  36644. this.tangents = data;
  36645. break;
  36646. case BABYLON.VertexBuffer.UVKind:
  36647. this.uvs = data;
  36648. break;
  36649. case BABYLON.VertexBuffer.UV2Kind:
  36650. this.uvs2 = data;
  36651. break;
  36652. case BABYLON.VertexBuffer.UV3Kind:
  36653. this.uvs3 = data;
  36654. break;
  36655. case BABYLON.VertexBuffer.UV4Kind:
  36656. this.uvs4 = data;
  36657. break;
  36658. case BABYLON.VertexBuffer.UV5Kind:
  36659. this.uvs5 = data;
  36660. break;
  36661. case BABYLON.VertexBuffer.UV6Kind:
  36662. this.uvs6 = data;
  36663. break;
  36664. case BABYLON.VertexBuffer.ColorKind:
  36665. this.colors = data;
  36666. break;
  36667. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36668. this.matricesIndices = data;
  36669. break;
  36670. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36671. this.matricesWeights = data;
  36672. break;
  36673. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36674. this.matricesIndicesExtra = data;
  36675. break;
  36676. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36677. this.matricesWeightsExtra = data;
  36678. break;
  36679. }
  36680. };
  36681. /**
  36682. * Associates the vertexData to the passed Mesh.
  36683. * Sets it as updatable or not (default `false`)
  36684. * @param mesh the mesh the vertexData is applied to
  36685. * @param updatable when used and having the value true allows new data to update the vertexData
  36686. * @returns the VertexData
  36687. */
  36688. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36689. this._applyTo(mesh, updatable);
  36690. return this;
  36691. };
  36692. /**
  36693. * Associates the vertexData to the passed Geometry.
  36694. * Sets it as updatable or not (default `false`)
  36695. * @param geometry the geometry the vertexData is applied to
  36696. * @param updatable when used and having the value true allows new data to update the vertexData
  36697. * @returns VertexData
  36698. */
  36699. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36700. this._applyTo(geometry, updatable);
  36701. return this;
  36702. };
  36703. /**
  36704. * Updates the associated mesh
  36705. * @param mesh the mesh to be updated
  36706. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36707. * @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
  36708. * @returns VertexData
  36709. */
  36710. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36711. this._update(mesh);
  36712. return this;
  36713. };
  36714. /**
  36715. * Updates the associated geometry
  36716. * @param geometry the geometry to be updated
  36717. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36718. * @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
  36719. * @returns VertexData.
  36720. */
  36721. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36722. this._update(geometry);
  36723. return this;
  36724. };
  36725. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36726. if (updatable === void 0) { updatable = false; }
  36727. if (this.positions) {
  36728. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36729. }
  36730. if (this.normals) {
  36731. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36732. }
  36733. if (this.tangents) {
  36734. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36735. }
  36736. if (this.uvs) {
  36737. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36738. }
  36739. if (this.uvs2) {
  36740. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36741. }
  36742. if (this.uvs3) {
  36743. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36744. }
  36745. if (this.uvs4) {
  36746. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36747. }
  36748. if (this.uvs5) {
  36749. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36750. }
  36751. if (this.uvs6) {
  36752. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36753. }
  36754. if (this.colors) {
  36755. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36756. }
  36757. if (this.matricesIndices) {
  36758. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36759. }
  36760. if (this.matricesWeights) {
  36761. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36762. }
  36763. if (this.matricesIndicesExtra) {
  36764. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36765. }
  36766. if (this.matricesWeightsExtra) {
  36767. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36768. }
  36769. if (this.indices) {
  36770. meshOrGeometry.setIndices(this.indices, null, updatable);
  36771. }
  36772. else {
  36773. meshOrGeometry.setIndices([], null);
  36774. }
  36775. return this;
  36776. };
  36777. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36778. if (this.positions) {
  36779. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36780. }
  36781. if (this.normals) {
  36782. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36783. }
  36784. if (this.tangents) {
  36785. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36786. }
  36787. if (this.uvs) {
  36788. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36789. }
  36790. if (this.uvs2) {
  36791. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36792. }
  36793. if (this.uvs3) {
  36794. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36795. }
  36796. if (this.uvs4) {
  36797. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36798. }
  36799. if (this.uvs5) {
  36800. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36801. }
  36802. if (this.uvs6) {
  36803. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36804. }
  36805. if (this.colors) {
  36806. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36807. }
  36808. if (this.matricesIndices) {
  36809. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36810. }
  36811. if (this.matricesWeights) {
  36812. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36813. }
  36814. if (this.matricesIndicesExtra) {
  36815. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36816. }
  36817. if (this.matricesWeightsExtra) {
  36818. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36819. }
  36820. if (this.indices) {
  36821. meshOrGeometry.setIndices(this.indices, null);
  36822. }
  36823. return this;
  36824. };
  36825. /**
  36826. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36827. * @param matrix the transforming matrix
  36828. * @returns the VertexData
  36829. */
  36830. VertexData.prototype.transform = function (matrix) {
  36831. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36832. var transformed = BABYLON.Vector3.Zero();
  36833. var index;
  36834. if (this.positions) {
  36835. var position = BABYLON.Vector3.Zero();
  36836. for (index = 0; index < this.positions.length; index += 3) {
  36837. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36838. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36839. this.positions[index] = transformed.x;
  36840. this.positions[index + 1] = transformed.y;
  36841. this.positions[index + 2] = transformed.z;
  36842. }
  36843. }
  36844. if (this.normals) {
  36845. var normal = BABYLON.Vector3.Zero();
  36846. for (index = 0; index < this.normals.length; index += 3) {
  36847. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36848. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36849. this.normals[index] = transformed.x;
  36850. this.normals[index + 1] = transformed.y;
  36851. this.normals[index + 2] = transformed.z;
  36852. }
  36853. }
  36854. if (this.tangents) {
  36855. var tangent = BABYLON.Vector4.Zero();
  36856. var tangentTransformed = BABYLON.Vector4.Zero();
  36857. for (index = 0; index < this.tangents.length; index += 4) {
  36858. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36859. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36860. this.tangents[index] = tangentTransformed.x;
  36861. this.tangents[index + 1] = tangentTransformed.y;
  36862. this.tangents[index + 2] = tangentTransformed.z;
  36863. this.tangents[index + 3] = tangentTransformed.w;
  36864. }
  36865. }
  36866. if (flip && this.indices) {
  36867. for (index = 0; index < this.indices.length; index += 3) {
  36868. var tmp = this.indices[index + 1];
  36869. this.indices[index + 1] = this.indices[index + 2];
  36870. this.indices[index + 2] = tmp;
  36871. }
  36872. }
  36873. return this;
  36874. };
  36875. /**
  36876. * Merges the passed VertexData into the current one
  36877. * @param other the VertexData to be merged into the current one
  36878. * @returns the modified VertexData
  36879. */
  36880. VertexData.prototype.merge = function (other) {
  36881. this._validate();
  36882. other._validate();
  36883. if (!this.normals !== !other.normals ||
  36884. !this.tangents !== !other.tangents ||
  36885. !this.uvs !== !other.uvs ||
  36886. !this.uvs2 !== !other.uvs2 ||
  36887. !this.uvs3 !== !other.uvs3 ||
  36888. !this.uvs4 !== !other.uvs4 ||
  36889. !this.uvs5 !== !other.uvs5 ||
  36890. !this.uvs6 !== !other.uvs6 ||
  36891. !this.colors !== !other.colors ||
  36892. !this.matricesIndices !== !other.matricesIndices ||
  36893. !this.matricesWeights !== !other.matricesWeights ||
  36894. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36895. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36896. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36897. }
  36898. if (other.indices) {
  36899. if (!this.indices) {
  36900. this.indices = [];
  36901. }
  36902. var offset = this.positions ? this.positions.length / 3 : 0;
  36903. for (var index = 0; index < other.indices.length; index++) {
  36904. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36905. this.indices.push(other.indices[index] + offset);
  36906. }
  36907. }
  36908. this.positions = this._mergeElement(this.positions, other.positions);
  36909. this.normals = this._mergeElement(this.normals, other.normals);
  36910. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36911. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36912. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36913. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36914. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36915. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36916. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36917. this.colors = this._mergeElement(this.colors, other.colors);
  36918. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36919. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36920. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36921. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36922. return this;
  36923. };
  36924. VertexData.prototype._mergeElement = function (source, other) {
  36925. if (!source) {
  36926. return other;
  36927. }
  36928. if (!other) {
  36929. return source;
  36930. }
  36931. var len = other.length + source.length;
  36932. var isSrcTypedArray = source instanceof Float32Array;
  36933. var isOthTypedArray = other instanceof Float32Array;
  36934. // use non-loop method when the source is Float32Array
  36935. if (isSrcTypedArray) {
  36936. var ret32 = new Float32Array(len);
  36937. ret32.set(source);
  36938. ret32.set(other, source.length);
  36939. return ret32;
  36940. // source is number[], when other is also use concat
  36941. }
  36942. else if (!isOthTypedArray) {
  36943. return source.concat(other);
  36944. // source is a number[], but other is a Float32Array, loop required
  36945. }
  36946. else {
  36947. var ret = source.slice(0); // copy source to a separate array
  36948. for (var i = 0, len = other.length; i < len; i++) {
  36949. ret.push(other[i]);
  36950. }
  36951. return ret;
  36952. }
  36953. };
  36954. VertexData.prototype._validate = function () {
  36955. if (!this.positions) {
  36956. throw new Error("Positions are required");
  36957. }
  36958. var getElementCount = function (kind, values) {
  36959. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36960. if ((values.length % stride) !== 0) {
  36961. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36962. }
  36963. return values.length / stride;
  36964. };
  36965. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36966. var validateElementCount = function (kind, values) {
  36967. var elementCount = getElementCount(kind, values);
  36968. if (elementCount !== positionsElementCount) {
  36969. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36970. }
  36971. };
  36972. if (this.normals)
  36973. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36974. if (this.tangents)
  36975. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36976. if (this.uvs)
  36977. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36978. if (this.uvs2)
  36979. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36980. if (this.uvs3)
  36981. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36982. if (this.uvs4)
  36983. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36984. if (this.uvs5)
  36985. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36986. if (this.uvs6)
  36987. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36988. if (this.colors)
  36989. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36990. if (this.matricesIndices)
  36991. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36992. if (this.matricesWeights)
  36993. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36994. if (this.matricesIndicesExtra)
  36995. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36996. if (this.matricesWeightsExtra)
  36997. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36998. };
  36999. /**
  37000. * Serializes the VertexData
  37001. * @returns a serialized object
  37002. */
  37003. VertexData.prototype.serialize = function () {
  37004. var serializationObject = this.serialize();
  37005. if (this.positions) {
  37006. serializationObject.positions = this.positions;
  37007. }
  37008. if (this.normals) {
  37009. serializationObject.normals = this.normals;
  37010. }
  37011. if (this.tangents) {
  37012. serializationObject.tangents = this.tangents;
  37013. }
  37014. if (this.uvs) {
  37015. serializationObject.uvs = this.uvs;
  37016. }
  37017. if (this.uvs2) {
  37018. serializationObject.uvs2 = this.uvs2;
  37019. }
  37020. if (this.uvs3) {
  37021. serializationObject.uvs3 = this.uvs3;
  37022. }
  37023. if (this.uvs4) {
  37024. serializationObject.uvs4 = this.uvs4;
  37025. }
  37026. if (this.uvs5) {
  37027. serializationObject.uvs5 = this.uvs5;
  37028. }
  37029. if (this.uvs6) {
  37030. serializationObject.uvs6 = this.uvs6;
  37031. }
  37032. if (this.colors) {
  37033. serializationObject.colors = this.colors;
  37034. }
  37035. if (this.matricesIndices) {
  37036. serializationObject.matricesIndices = this.matricesIndices;
  37037. serializationObject.matricesIndices._isExpanded = true;
  37038. }
  37039. if (this.matricesWeights) {
  37040. serializationObject.matricesWeights = this.matricesWeights;
  37041. }
  37042. if (this.matricesIndicesExtra) {
  37043. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37044. serializationObject.matricesIndicesExtra._isExpanded = true;
  37045. }
  37046. if (this.matricesWeightsExtra) {
  37047. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37048. }
  37049. serializationObject.indices = this.indices;
  37050. return serializationObject;
  37051. };
  37052. // Statics
  37053. /**
  37054. * Extracts the vertexData from a mesh
  37055. * @param mesh the mesh from which to extract the VertexData
  37056. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37057. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37058. * @returns the object VertexData associated to the passed mesh
  37059. */
  37060. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37061. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37062. };
  37063. /**
  37064. * Extracts the vertexData from the geometry
  37065. * @param geometry the geometry from which to extract the VertexData
  37066. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37067. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37068. * @returns the object VertexData associated to the passed mesh
  37069. */
  37070. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37071. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37072. };
  37073. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37074. var result = new VertexData();
  37075. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37076. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37077. }
  37078. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37079. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37080. }
  37081. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37082. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37083. }
  37084. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37085. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37086. }
  37087. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37088. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37089. }
  37090. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37091. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37092. }
  37093. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37094. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37095. }
  37096. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37097. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37098. }
  37099. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37100. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37101. }
  37102. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37103. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37104. }
  37105. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37106. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37107. }
  37108. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37109. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37110. }
  37111. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37112. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37113. }
  37114. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37115. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37116. }
  37117. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37118. return result;
  37119. };
  37120. /**
  37121. * Creates the VertexData for a Ribbon
  37122. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37123. * * pathArray array of paths, each of which an array of successive Vector3
  37124. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37125. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37126. * * 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
  37127. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37128. * * 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)
  37129. * * 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)
  37130. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37131. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37132. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37133. * @returns the VertexData of the ribbon
  37134. */
  37135. VertexData.CreateRibbon = function (options) {
  37136. var pathArray = options.pathArray;
  37137. var closeArray = options.closeArray || false;
  37138. var closePath = options.closePath || false;
  37139. var invertUV = options.invertUV || false;
  37140. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37141. var offset = options.offset || defaultOffset;
  37142. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37143. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37144. var customUV = options.uvs;
  37145. var customColors = options.colors;
  37146. var positions = [];
  37147. var indices = [];
  37148. var normals = [];
  37149. var uvs = [];
  37150. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37151. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37152. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37153. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37154. var minlg; // minimal length among all paths from pathArray
  37155. var lg = []; // array of path lengths : nb of vertex per path
  37156. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37157. var p; // path iterator
  37158. var i; // point iterator
  37159. var j; // point iterator
  37160. // if single path in pathArray
  37161. if (pathArray.length < 2) {
  37162. var ar1 = [];
  37163. var ar2 = [];
  37164. for (i = 0; i < pathArray[0].length - offset; i++) {
  37165. ar1.push(pathArray[0][i]);
  37166. ar2.push(pathArray[0][i + offset]);
  37167. }
  37168. pathArray = [ar1, ar2];
  37169. }
  37170. // positions and horizontal distances (u)
  37171. var idc = 0;
  37172. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37173. var path;
  37174. var l;
  37175. minlg = pathArray[0].length;
  37176. var vectlg;
  37177. var dist;
  37178. for (p = 0; p < pathArray.length; p++) {
  37179. uTotalDistance[p] = 0;
  37180. us[p] = [0];
  37181. path = pathArray[p];
  37182. l = path.length;
  37183. minlg = (minlg < l) ? minlg : l;
  37184. j = 0;
  37185. while (j < l) {
  37186. positions.push(path[j].x, path[j].y, path[j].z);
  37187. if (j > 0) {
  37188. vectlg = path[j].subtract(path[j - 1]).length();
  37189. dist = vectlg + uTotalDistance[p];
  37190. us[p].push(dist);
  37191. uTotalDistance[p] = dist;
  37192. }
  37193. j++;
  37194. }
  37195. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37196. j--;
  37197. positions.push(path[0].x, path[0].y, path[0].z);
  37198. vectlg = path[j].subtract(path[0]).length();
  37199. dist = vectlg + uTotalDistance[p];
  37200. us[p].push(dist);
  37201. uTotalDistance[p] = dist;
  37202. }
  37203. lg[p] = l + closePathCorr;
  37204. idx[p] = idc;
  37205. idc += (l + closePathCorr);
  37206. }
  37207. // vertical distances (v)
  37208. var path1;
  37209. var path2;
  37210. var vertex1 = null;
  37211. var vertex2 = null;
  37212. for (i = 0; i < minlg + closePathCorr; i++) {
  37213. vTotalDistance[i] = 0;
  37214. vs[i] = [0];
  37215. for (p = 0; p < pathArray.length - 1; p++) {
  37216. path1 = pathArray[p];
  37217. path2 = pathArray[p + 1];
  37218. if (i === minlg) { // closePath
  37219. vertex1 = path1[0];
  37220. vertex2 = path2[0];
  37221. }
  37222. else {
  37223. vertex1 = path1[i];
  37224. vertex2 = path2[i];
  37225. }
  37226. vectlg = vertex2.subtract(vertex1).length();
  37227. dist = vectlg + vTotalDistance[i];
  37228. vs[i].push(dist);
  37229. vTotalDistance[i] = dist;
  37230. }
  37231. if (closeArray && vertex2 && vertex1) {
  37232. path1 = pathArray[p];
  37233. path2 = pathArray[0];
  37234. if (i === minlg) { // closePath
  37235. vertex2 = path2[0];
  37236. }
  37237. vectlg = vertex2.subtract(vertex1).length();
  37238. dist = vectlg + vTotalDistance[i];
  37239. vTotalDistance[i] = dist;
  37240. }
  37241. }
  37242. // uvs
  37243. var u;
  37244. var v;
  37245. if (customUV) {
  37246. for (p = 0; p < customUV.length; p++) {
  37247. uvs.push(customUV[p].x, customUV[p].y);
  37248. }
  37249. }
  37250. else {
  37251. for (p = 0; p < pathArray.length; p++) {
  37252. for (i = 0; i < minlg + closePathCorr; i++) {
  37253. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37254. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37255. if (invertUV) {
  37256. uvs.push(v, u);
  37257. }
  37258. else {
  37259. uvs.push(u, v);
  37260. }
  37261. }
  37262. }
  37263. }
  37264. // indices
  37265. p = 0; // path index
  37266. var pi = 0; // positions array index
  37267. var l1 = lg[p] - 1; // path1 length
  37268. var l2 = lg[p + 1] - 1; // path2 length
  37269. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37270. var shft = idx[1] - idx[0]; // shift
  37271. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37272. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37273. // 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
  37274. indices.push(pi, pi + shft, pi + 1);
  37275. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37276. pi += 1;
  37277. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37278. p++;
  37279. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37280. shft = idx[0] - idx[p];
  37281. l1 = lg[p] - 1;
  37282. l2 = lg[0] - 1;
  37283. }
  37284. else {
  37285. shft = idx[p + 1] - idx[p];
  37286. l1 = lg[p] - 1;
  37287. l2 = lg[p + 1] - 1;
  37288. }
  37289. pi = idx[p];
  37290. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37291. }
  37292. }
  37293. // normals
  37294. VertexData.ComputeNormals(positions, indices, normals);
  37295. if (closePath) { // update both the first and last vertex normals to their average value
  37296. var indexFirst = 0;
  37297. var indexLast = 0;
  37298. for (p = 0; p < pathArray.length; p++) {
  37299. indexFirst = idx[p] * 3;
  37300. if (p + 1 < pathArray.length) {
  37301. indexLast = (idx[p + 1] - 1) * 3;
  37302. }
  37303. else {
  37304. indexLast = normals.length - 3;
  37305. }
  37306. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37307. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37308. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37309. normals[indexLast] = normals[indexFirst];
  37310. normals[indexLast + 1] = normals[indexFirst + 1];
  37311. normals[indexLast + 2] = normals[indexFirst + 2];
  37312. }
  37313. }
  37314. // sides
  37315. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37316. // Colors
  37317. var colors = null;
  37318. if (customColors) {
  37319. colors = new Float32Array(customColors.length * 4);
  37320. for (var c = 0; c < customColors.length; c++) {
  37321. colors[c * 4] = customColors[c].r;
  37322. colors[c * 4 + 1] = customColors[c].g;
  37323. colors[c * 4 + 2] = customColors[c].b;
  37324. colors[c * 4 + 3] = customColors[c].a;
  37325. }
  37326. }
  37327. // Result
  37328. var vertexData = new VertexData();
  37329. var positions32 = new Float32Array(positions);
  37330. var normals32 = new Float32Array(normals);
  37331. var uvs32 = new Float32Array(uvs);
  37332. vertexData.indices = indices;
  37333. vertexData.positions = positions32;
  37334. vertexData.normals = normals32;
  37335. vertexData.uvs = uvs32;
  37336. if (colors) {
  37337. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37338. }
  37339. if (closePath) {
  37340. vertexData._idx = idx;
  37341. }
  37342. return vertexData;
  37343. };
  37344. /**
  37345. * Creates the VertexData for a box
  37346. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37347. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37348. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37349. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37350. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37351. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37352. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37353. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37354. * * 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)
  37355. * * 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)
  37356. * @returns the VertexData of the box
  37357. */
  37358. VertexData.CreateBox = function (options) {
  37359. var normalsSource = [
  37360. new BABYLON.Vector3(0, 0, 1),
  37361. new BABYLON.Vector3(0, 0, -1),
  37362. new BABYLON.Vector3(1, 0, 0),
  37363. new BABYLON.Vector3(-1, 0, 0),
  37364. new BABYLON.Vector3(0, 1, 0),
  37365. new BABYLON.Vector3(0, -1, 0)
  37366. ];
  37367. var indices = [];
  37368. var positions = [];
  37369. var normals = [];
  37370. var uvs = [];
  37371. var width = options.width || options.size || 1;
  37372. var height = options.height || options.size || 1;
  37373. var depth = options.depth || options.size || 1;
  37374. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37375. var faceUV = options.faceUV || new Array(6);
  37376. var faceColors = options.faceColors;
  37377. var colors = [];
  37378. // default face colors and UV if undefined
  37379. for (var f = 0; f < 6; f++) {
  37380. if (faceUV[f] === undefined) {
  37381. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37382. }
  37383. if (faceColors && faceColors[f] === undefined) {
  37384. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37385. }
  37386. }
  37387. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37388. // Create each face in turn.
  37389. for (var index = 0; index < normalsSource.length; index++) {
  37390. var normal = normalsSource[index];
  37391. // Get two vectors perpendicular to the face normal and to each other.
  37392. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37393. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37394. // Six indices (two triangles) per face.
  37395. var verticesLength = positions.length / 3;
  37396. indices.push(verticesLength);
  37397. indices.push(verticesLength + 1);
  37398. indices.push(verticesLength + 2);
  37399. indices.push(verticesLength);
  37400. indices.push(verticesLength + 2);
  37401. indices.push(verticesLength + 3);
  37402. // Four vertices per face.
  37403. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37404. positions.push(vertex.x, vertex.y, vertex.z);
  37405. normals.push(normal.x, normal.y, normal.z);
  37406. uvs.push(faceUV[index].z, faceUV[index].w);
  37407. if (faceColors) {
  37408. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37409. }
  37410. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37411. positions.push(vertex.x, vertex.y, vertex.z);
  37412. normals.push(normal.x, normal.y, normal.z);
  37413. uvs.push(faceUV[index].x, faceUV[index].w);
  37414. if (faceColors) {
  37415. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37416. }
  37417. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37418. positions.push(vertex.x, vertex.y, vertex.z);
  37419. normals.push(normal.x, normal.y, normal.z);
  37420. uvs.push(faceUV[index].x, faceUV[index].y);
  37421. if (faceColors) {
  37422. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37423. }
  37424. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37425. positions.push(vertex.x, vertex.y, vertex.z);
  37426. normals.push(normal.x, normal.y, normal.z);
  37427. uvs.push(faceUV[index].z, faceUV[index].y);
  37428. if (faceColors) {
  37429. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37430. }
  37431. }
  37432. // sides
  37433. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37434. // Result
  37435. var vertexData = new VertexData();
  37436. vertexData.indices = indices;
  37437. vertexData.positions = positions;
  37438. vertexData.normals = normals;
  37439. vertexData.uvs = uvs;
  37440. if (faceColors) {
  37441. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37442. vertexData.colors = totalColors;
  37443. }
  37444. return vertexData;
  37445. };
  37446. /**
  37447. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37448. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37449. * * segments sets the number of horizontal strips optional, default 32
  37450. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37451. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37452. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37453. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37454. * * 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
  37455. * * 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
  37456. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37457. * * 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)
  37458. * * 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)
  37459. * @returns the VertexData of the ellipsoid
  37460. */
  37461. VertexData.CreateSphere = function (options) {
  37462. var segments = options.segments || 32;
  37463. var diameterX = options.diameterX || options.diameter || 1;
  37464. var diameterY = options.diameterY || options.diameter || 1;
  37465. var diameterZ = options.diameterZ || options.diameter || 1;
  37466. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37467. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37468. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37469. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37470. var totalZRotationSteps = 2 + segments;
  37471. var totalYRotationSteps = 2 * totalZRotationSteps;
  37472. var indices = [];
  37473. var positions = [];
  37474. var normals = [];
  37475. var uvs = [];
  37476. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37477. var normalizedZ = zRotationStep / totalZRotationSteps;
  37478. var angleZ = normalizedZ * Math.PI * slice;
  37479. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37480. var normalizedY = yRotationStep / totalYRotationSteps;
  37481. var angleY = normalizedY * Math.PI * 2 * arc;
  37482. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37483. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37484. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37485. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37486. var vertex = complete.multiply(radius);
  37487. var normal = complete.divide(radius).normalize();
  37488. positions.push(vertex.x, vertex.y, vertex.z);
  37489. normals.push(normal.x, normal.y, normal.z);
  37490. uvs.push(normalizedY, normalizedZ);
  37491. }
  37492. if (zRotationStep > 0) {
  37493. var verticesCount = positions.length / 3;
  37494. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37495. indices.push((firstIndex));
  37496. indices.push((firstIndex + 1));
  37497. indices.push(firstIndex + totalYRotationSteps + 1);
  37498. indices.push((firstIndex + totalYRotationSteps + 1));
  37499. indices.push((firstIndex + 1));
  37500. indices.push((firstIndex + totalYRotationSteps + 2));
  37501. }
  37502. }
  37503. }
  37504. // Sides
  37505. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37506. // Result
  37507. var vertexData = new VertexData();
  37508. vertexData.indices = indices;
  37509. vertexData.positions = positions;
  37510. vertexData.normals = normals;
  37511. vertexData.uvs = uvs;
  37512. return vertexData;
  37513. };
  37514. /**
  37515. * Creates the VertexData for a cylinder, cone or prism
  37516. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37517. * * height sets the height (y direction) of the cylinder, optional, default 2
  37518. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37519. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37520. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37521. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37522. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37523. * * 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
  37524. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37525. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37526. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37527. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37528. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37529. * * 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)
  37530. * * 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)
  37531. * @returns the VertexData of the cylinder, cone or prism
  37532. */
  37533. VertexData.CreateCylinder = function (options) {
  37534. var height = options.height || 2;
  37535. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37536. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37537. var tessellation = options.tessellation || 24;
  37538. var subdivisions = options.subdivisions || 1;
  37539. var hasRings = options.hasRings ? true : false;
  37540. var enclose = options.enclose ? true : false;
  37541. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37542. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37543. var faceUV = options.faceUV || new Array(3);
  37544. var faceColors = options.faceColors;
  37545. // default face colors and UV if undefined
  37546. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37547. var ringNb = (hasRings) ? subdivisions : 1;
  37548. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37549. var f;
  37550. for (f = 0; f < surfaceNb; f++) {
  37551. if (faceColors && faceColors[f] === undefined) {
  37552. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37553. }
  37554. }
  37555. for (f = 0; f < surfaceNb; f++) {
  37556. if (faceUV && faceUV[f] === undefined) {
  37557. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37558. }
  37559. }
  37560. var indices = new Array();
  37561. var positions = new Array();
  37562. var normals = new Array();
  37563. var uvs = new Array();
  37564. var colors = new Array();
  37565. var angle_step = Math.PI * 2 * arc / tessellation;
  37566. var angle;
  37567. var h;
  37568. var radius;
  37569. var tan = (diameterBottom - diameterTop) / 2 / height;
  37570. var ringVertex = BABYLON.Vector3.Zero();
  37571. var ringNormal = BABYLON.Vector3.Zero();
  37572. var ringFirstVertex = BABYLON.Vector3.Zero();
  37573. var ringFirstNormal = BABYLON.Vector3.Zero();
  37574. var quadNormal = BABYLON.Vector3.Zero();
  37575. var Y = BABYLON.Axis.Y;
  37576. // positions, normals, uvs
  37577. var i;
  37578. var j;
  37579. var r;
  37580. var ringIdx = 1;
  37581. var s = 1; // surface index
  37582. var cs = 0;
  37583. var v = 0;
  37584. for (i = 0; i <= subdivisions; i++) {
  37585. h = i / subdivisions;
  37586. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37587. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37588. for (r = 0; r < ringIdx; r++) {
  37589. if (hasRings) {
  37590. s += r;
  37591. }
  37592. if (enclose) {
  37593. s += 2 * r;
  37594. }
  37595. for (j = 0; j <= tessellation; j++) {
  37596. angle = j * angle_step;
  37597. // position
  37598. ringVertex.x = Math.cos(-angle) * radius;
  37599. ringVertex.y = -height / 2 + h * height;
  37600. ringVertex.z = Math.sin(-angle) * radius;
  37601. // normal
  37602. if (diameterTop === 0 && i === subdivisions) {
  37603. // if no top cap, reuse former normals
  37604. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37605. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37606. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37607. }
  37608. else {
  37609. ringNormal.x = ringVertex.x;
  37610. ringNormal.z = ringVertex.z;
  37611. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37612. ringNormal.normalize();
  37613. }
  37614. // keep first ring vertex values for enclose
  37615. if (j === 0) {
  37616. ringFirstVertex.copyFrom(ringVertex);
  37617. ringFirstNormal.copyFrom(ringNormal);
  37618. }
  37619. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37620. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37621. if (hasRings) {
  37622. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37623. }
  37624. else {
  37625. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37626. }
  37627. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37628. if (faceColors) {
  37629. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37630. }
  37631. }
  37632. // if enclose, add four vertices and their dedicated normals
  37633. if (arc !== 1 && enclose) {
  37634. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37635. positions.push(0, ringVertex.y, 0);
  37636. positions.push(0, ringVertex.y, 0);
  37637. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37638. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37639. quadNormal.normalize();
  37640. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37641. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37642. quadNormal.normalize();
  37643. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37644. if (hasRings) {
  37645. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37646. }
  37647. else {
  37648. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37649. }
  37650. uvs.push(faceUV[s + 1].x, v);
  37651. uvs.push(faceUV[s + 1].z, v);
  37652. if (hasRings) {
  37653. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37654. }
  37655. else {
  37656. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37657. }
  37658. uvs.push(faceUV[s + 2].x, v);
  37659. uvs.push(faceUV[s + 2].z, v);
  37660. if (faceColors) {
  37661. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37662. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37663. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37664. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37665. }
  37666. }
  37667. if (cs !== s) {
  37668. cs = s;
  37669. }
  37670. }
  37671. }
  37672. // indices
  37673. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37674. var s;
  37675. i = 0;
  37676. for (s = 0; s < subdivisions; s++) {
  37677. var i0 = 0;
  37678. var i1 = 0;
  37679. var i2 = 0;
  37680. var i3 = 0;
  37681. for (j = 0; j < tessellation; j++) {
  37682. i0 = i * (e + 1) + j;
  37683. i1 = (i + 1) * (e + 1) + j;
  37684. i2 = i * (e + 1) + (j + 1);
  37685. i3 = (i + 1) * (e + 1) + (j + 1);
  37686. indices.push(i0, i1, i2);
  37687. indices.push(i3, i2, i1);
  37688. }
  37689. if (arc !== 1 && enclose) { // if enclose, add two quads
  37690. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37691. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37692. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37693. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37694. }
  37695. i = (hasRings) ? (i + 2) : (i + 1);
  37696. }
  37697. // Caps
  37698. var createCylinderCap = function (isTop) {
  37699. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37700. if (radius === 0) {
  37701. return;
  37702. }
  37703. // Cap positions, normals & uvs
  37704. var angle;
  37705. var circleVector;
  37706. var i;
  37707. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37708. var c = null;
  37709. if (faceColors) {
  37710. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37711. }
  37712. // cap center
  37713. var vbase = positions.length / 3;
  37714. var offset = isTop ? height / 2 : -height / 2;
  37715. var center = new BABYLON.Vector3(0, offset, 0);
  37716. positions.push(center.x, center.y, center.z);
  37717. normals.push(0, isTop ? 1 : -1, 0);
  37718. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37719. if (c) {
  37720. colors.push(c.r, c.g, c.b, c.a);
  37721. }
  37722. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37723. for (i = 0; i <= tessellation; i++) {
  37724. angle = Math.PI * 2 * i * arc / tessellation;
  37725. var cos = Math.cos(-angle);
  37726. var sin = Math.sin(-angle);
  37727. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37728. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37729. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37730. normals.push(0, isTop ? 1 : -1, 0);
  37731. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37732. if (c) {
  37733. colors.push(c.r, c.g, c.b, c.a);
  37734. }
  37735. }
  37736. // Cap indices
  37737. for (i = 0; i < tessellation; i++) {
  37738. if (!isTop) {
  37739. indices.push(vbase);
  37740. indices.push(vbase + (i + 1));
  37741. indices.push(vbase + (i + 2));
  37742. }
  37743. else {
  37744. indices.push(vbase);
  37745. indices.push(vbase + (i + 2));
  37746. indices.push(vbase + (i + 1));
  37747. }
  37748. }
  37749. };
  37750. // add caps to geometry
  37751. createCylinderCap(false);
  37752. createCylinderCap(true);
  37753. // Sides
  37754. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37755. var vertexData = new VertexData();
  37756. vertexData.indices = indices;
  37757. vertexData.positions = positions;
  37758. vertexData.normals = normals;
  37759. vertexData.uvs = uvs;
  37760. if (faceColors) {
  37761. vertexData.colors = colors;
  37762. }
  37763. return vertexData;
  37764. };
  37765. /**
  37766. * Creates the VertexData for a torus
  37767. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37768. * * diameter the diameter of the torus, optional default 1
  37769. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37770. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37771. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37772. * * 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)
  37773. * * 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)
  37774. * @returns the VertexData of the torus
  37775. */
  37776. VertexData.CreateTorus = function (options) {
  37777. var indices = [];
  37778. var positions = [];
  37779. var normals = [];
  37780. var uvs = [];
  37781. var diameter = options.diameter || 1;
  37782. var thickness = options.thickness || 0.5;
  37783. var tessellation = options.tessellation || 16;
  37784. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37785. var stride = tessellation + 1;
  37786. for (var i = 0; i <= tessellation; i++) {
  37787. var u = i / tessellation;
  37788. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37789. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37790. for (var j = 0; j <= tessellation; j++) {
  37791. var v = 1 - j / tessellation;
  37792. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37793. var dx = Math.cos(innerAngle);
  37794. var dy = Math.sin(innerAngle);
  37795. // Create a vertex.
  37796. var normal = new BABYLON.Vector3(dx, dy, 0);
  37797. var position = normal.scale(thickness / 2);
  37798. var textureCoordinate = new BABYLON.Vector2(u, v);
  37799. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37800. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37801. positions.push(position.x, position.y, position.z);
  37802. normals.push(normal.x, normal.y, normal.z);
  37803. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37804. // And create indices for two triangles.
  37805. var nextI = (i + 1) % stride;
  37806. var nextJ = (j + 1) % stride;
  37807. indices.push(i * stride + j);
  37808. indices.push(i * stride + nextJ);
  37809. indices.push(nextI * stride + j);
  37810. indices.push(i * stride + nextJ);
  37811. indices.push(nextI * stride + nextJ);
  37812. indices.push(nextI * stride + j);
  37813. }
  37814. }
  37815. // Sides
  37816. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37817. // Result
  37818. var vertexData = new VertexData();
  37819. vertexData.indices = indices;
  37820. vertexData.positions = positions;
  37821. vertexData.normals = normals;
  37822. vertexData.uvs = uvs;
  37823. return vertexData;
  37824. };
  37825. /**
  37826. * Creates the VertexData of the LineSystem
  37827. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37828. * - lines an array of lines, each line being an array of successive Vector3
  37829. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37830. * @returns the VertexData of the LineSystem
  37831. */
  37832. VertexData.CreateLineSystem = function (options) {
  37833. var indices = [];
  37834. var positions = [];
  37835. var lines = options.lines;
  37836. var colors = options.colors;
  37837. var vertexColors = [];
  37838. var idx = 0;
  37839. for (var l = 0; l < lines.length; l++) {
  37840. var points = lines[l];
  37841. for (var index = 0; index < points.length; index++) {
  37842. positions.push(points[index].x, points[index].y, points[index].z);
  37843. if (colors) {
  37844. var color = colors[l];
  37845. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37846. }
  37847. if (index > 0) {
  37848. indices.push(idx - 1);
  37849. indices.push(idx);
  37850. }
  37851. idx++;
  37852. }
  37853. }
  37854. var vertexData = new VertexData();
  37855. vertexData.indices = indices;
  37856. vertexData.positions = positions;
  37857. if (colors) {
  37858. vertexData.colors = vertexColors;
  37859. }
  37860. return vertexData;
  37861. };
  37862. /**
  37863. * Create the VertexData for a DashedLines
  37864. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37865. * - points an array successive Vector3
  37866. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37867. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37868. * - dashNb the intended total number of dashes, optional, default 200
  37869. * @returns the VertexData for the DashedLines
  37870. */
  37871. VertexData.CreateDashedLines = function (options) {
  37872. var dashSize = options.dashSize || 3;
  37873. var gapSize = options.gapSize || 1;
  37874. var dashNb = options.dashNb || 200;
  37875. var points = options.points;
  37876. var positions = new Array();
  37877. var indices = new Array();
  37878. var curvect = BABYLON.Vector3.Zero();
  37879. var lg = 0;
  37880. var nb = 0;
  37881. var shft = 0;
  37882. var dashshft = 0;
  37883. var curshft = 0;
  37884. var idx = 0;
  37885. var i = 0;
  37886. for (i = 0; i < points.length - 1; i++) {
  37887. points[i + 1].subtractToRef(points[i], curvect);
  37888. lg += curvect.length();
  37889. }
  37890. shft = lg / dashNb;
  37891. dashshft = dashSize * shft / (dashSize + gapSize);
  37892. for (i = 0; i < points.length - 1; i++) {
  37893. points[i + 1].subtractToRef(points[i], curvect);
  37894. nb = Math.floor(curvect.length() / shft);
  37895. curvect.normalize();
  37896. for (var j = 0; j < nb; j++) {
  37897. curshft = shft * j;
  37898. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37899. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37900. indices.push(idx, idx + 1);
  37901. idx += 2;
  37902. }
  37903. }
  37904. // Result
  37905. var vertexData = new VertexData();
  37906. vertexData.positions = positions;
  37907. vertexData.indices = indices;
  37908. return vertexData;
  37909. };
  37910. /**
  37911. * Creates the VertexData for a Ground
  37912. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37913. * - width the width (x direction) of the ground, optional, default 1
  37914. * - height the height (z direction) of the ground, optional, default 1
  37915. * - subdivisions the number of subdivisions per side, optional, default 1
  37916. * @returns the VertexData of the Ground
  37917. */
  37918. VertexData.CreateGround = function (options) {
  37919. var indices = [];
  37920. var positions = [];
  37921. var normals = [];
  37922. var uvs = [];
  37923. var row, col;
  37924. var width = options.width || 1;
  37925. var height = options.height || 1;
  37926. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37927. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37928. for (row = 0; row <= subdivisionsY; row++) {
  37929. for (col = 0; col <= subdivisionsX; col++) {
  37930. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37931. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37932. positions.push(position.x, position.y, position.z);
  37933. normals.push(normal.x, normal.y, normal.z);
  37934. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37935. }
  37936. }
  37937. for (row = 0; row < subdivisionsY; row++) {
  37938. for (col = 0; col < subdivisionsX; col++) {
  37939. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37940. indices.push(col + 1 + row * (subdivisionsX + 1));
  37941. indices.push(col + row * (subdivisionsX + 1));
  37942. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37943. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37944. indices.push(col + row * (subdivisionsX + 1));
  37945. }
  37946. }
  37947. // Result
  37948. var vertexData = new VertexData();
  37949. vertexData.indices = indices;
  37950. vertexData.positions = positions;
  37951. vertexData.normals = normals;
  37952. vertexData.uvs = uvs;
  37953. return vertexData;
  37954. };
  37955. /**
  37956. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37957. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37958. * * xmin the ground minimum X coordinate, optional, default -1
  37959. * * zmin the ground minimum Z coordinate, optional, default -1
  37960. * * xmax the ground maximum X coordinate, optional, default 1
  37961. * * zmax the ground maximum Z coordinate, optional, default 1
  37962. * * 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}
  37963. * * 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}
  37964. * @returns the VertexData of the TiledGround
  37965. */
  37966. VertexData.CreateTiledGround = function (options) {
  37967. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37968. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37969. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37970. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37971. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37972. var precision = options.precision || { w: 1, h: 1 };
  37973. var indices = new Array();
  37974. var positions = new Array();
  37975. var normals = new Array();
  37976. var uvs = new Array();
  37977. var row, col, tileRow, tileCol;
  37978. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37979. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37980. precision.w = (precision.w < 1) ? 1 : precision.w;
  37981. precision.h = (precision.h < 1) ? 1 : precision.h;
  37982. var tileSize = {
  37983. 'w': (xmax - xmin) / subdivisions.w,
  37984. 'h': (zmax - zmin) / subdivisions.h
  37985. };
  37986. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37987. // Indices
  37988. var base = positions.length / 3;
  37989. var rowLength = precision.w + 1;
  37990. for (row = 0; row < precision.h; row++) {
  37991. for (col = 0; col < precision.w; col++) {
  37992. var square = [
  37993. base + col + row * rowLength,
  37994. base + (col + 1) + row * rowLength,
  37995. base + (col + 1) + (row + 1) * rowLength,
  37996. base + col + (row + 1) * rowLength
  37997. ];
  37998. indices.push(square[1]);
  37999. indices.push(square[2]);
  38000. indices.push(square[3]);
  38001. indices.push(square[0]);
  38002. indices.push(square[1]);
  38003. indices.push(square[3]);
  38004. }
  38005. }
  38006. // Position, normals and uvs
  38007. var position = BABYLON.Vector3.Zero();
  38008. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38009. for (row = 0; row <= precision.h; row++) {
  38010. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38011. for (col = 0; col <= precision.w; col++) {
  38012. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38013. position.y = 0;
  38014. positions.push(position.x, position.y, position.z);
  38015. normals.push(normal.x, normal.y, normal.z);
  38016. uvs.push(col / precision.w, row / precision.h);
  38017. }
  38018. }
  38019. }
  38020. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38021. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38022. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38023. }
  38024. }
  38025. // Result
  38026. var vertexData = new VertexData();
  38027. vertexData.indices = indices;
  38028. vertexData.positions = positions;
  38029. vertexData.normals = normals;
  38030. vertexData.uvs = uvs;
  38031. return vertexData;
  38032. };
  38033. /**
  38034. * Creates the VertexData of the Ground designed from a heightmap
  38035. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38036. * * width the width (x direction) of the ground
  38037. * * height the height (z direction) of the ground
  38038. * * subdivisions the number of subdivisions per side
  38039. * * minHeight the minimum altitude on the ground, optional, default 0
  38040. * * maxHeight the maximum altitude on the ground, optional default 1
  38041. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38042. * * buffer the array holding the image color data
  38043. * * bufferWidth the width of image
  38044. * * bufferHeight the height of image
  38045. * @returns the VertexData of the Ground designed from a heightmap
  38046. */
  38047. VertexData.CreateGroundFromHeightMap = function (options) {
  38048. var indices = [];
  38049. var positions = [];
  38050. var normals = [];
  38051. var uvs = [];
  38052. var row, col;
  38053. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38054. // Vertices
  38055. for (row = 0; row <= options.subdivisions; row++) {
  38056. for (col = 0; col <= options.subdivisions; col++) {
  38057. 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));
  38058. // Compute height
  38059. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38060. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38061. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38062. var r = options.buffer[pos] / 255.0;
  38063. var g = options.buffer[pos + 1] / 255.0;
  38064. var b = options.buffer[pos + 2] / 255.0;
  38065. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38066. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38067. // Add vertex
  38068. positions.push(position.x, position.y, position.z);
  38069. normals.push(0, 0, 0);
  38070. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38071. }
  38072. }
  38073. // Indices
  38074. for (row = 0; row < options.subdivisions; row++) {
  38075. for (col = 0; col < options.subdivisions; col++) {
  38076. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38077. indices.push(col + 1 + row * (options.subdivisions + 1));
  38078. indices.push(col + row * (options.subdivisions + 1));
  38079. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38080. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38081. indices.push(col + row * (options.subdivisions + 1));
  38082. }
  38083. }
  38084. // Normals
  38085. VertexData.ComputeNormals(positions, indices, normals);
  38086. // Result
  38087. var vertexData = new VertexData();
  38088. vertexData.indices = indices;
  38089. vertexData.positions = positions;
  38090. vertexData.normals = normals;
  38091. vertexData.uvs = uvs;
  38092. return vertexData;
  38093. };
  38094. /**
  38095. * Creates the VertexData for a Plane
  38096. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38097. * * size sets the width and height of the plane to the value of size, optional default 1
  38098. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38099. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38100. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38101. * * 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)
  38102. * * 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)
  38103. * @returns the VertexData of the box
  38104. */
  38105. VertexData.CreatePlane = function (options) {
  38106. var indices = [];
  38107. var positions = [];
  38108. var normals = [];
  38109. var uvs = [];
  38110. var width = options.width || options.size || 1;
  38111. var height = options.height || options.size || 1;
  38112. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38113. // Vertices
  38114. var halfWidth = width / 2.0;
  38115. var halfHeight = height / 2.0;
  38116. positions.push(-halfWidth, -halfHeight, 0);
  38117. normals.push(0, 0, -1.0);
  38118. uvs.push(0.0, 0.0);
  38119. positions.push(halfWidth, -halfHeight, 0);
  38120. normals.push(0, 0, -1.0);
  38121. uvs.push(1.0, 0.0);
  38122. positions.push(halfWidth, halfHeight, 0);
  38123. normals.push(0, 0, -1.0);
  38124. uvs.push(1.0, 1.0);
  38125. positions.push(-halfWidth, halfHeight, 0);
  38126. normals.push(0, 0, -1.0);
  38127. uvs.push(0.0, 1.0);
  38128. // Indices
  38129. indices.push(0);
  38130. indices.push(1);
  38131. indices.push(2);
  38132. indices.push(0);
  38133. indices.push(2);
  38134. indices.push(3);
  38135. // Sides
  38136. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38137. // Result
  38138. var vertexData = new VertexData();
  38139. vertexData.indices = indices;
  38140. vertexData.positions = positions;
  38141. vertexData.normals = normals;
  38142. vertexData.uvs = uvs;
  38143. return vertexData;
  38144. };
  38145. /**
  38146. * Creates the VertexData of the Disc or regular Polygon
  38147. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38148. * * radius the radius of the disc, optional default 0.5
  38149. * * tessellation the number of polygon sides, optional, default 64
  38150. * * 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
  38151. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38152. * * 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)
  38153. * * 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)
  38154. * @returns the VertexData of the box
  38155. */
  38156. VertexData.CreateDisc = function (options) {
  38157. var positions = new Array();
  38158. var indices = new Array();
  38159. var normals = new Array();
  38160. var uvs = new Array();
  38161. var radius = options.radius || 0.5;
  38162. var tessellation = options.tessellation || 64;
  38163. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38164. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38165. // positions and uvs
  38166. positions.push(0, 0, 0); // disc center first
  38167. uvs.push(0.5, 0.5);
  38168. var theta = Math.PI * 2 * arc;
  38169. var step = theta / tessellation;
  38170. for (var a = 0; a < theta; a += step) {
  38171. var x = Math.cos(a);
  38172. var y = Math.sin(a);
  38173. var u = (x + 1) / 2;
  38174. var v = (1 - y) / 2;
  38175. positions.push(radius * x, radius * y, 0);
  38176. uvs.push(u, v);
  38177. }
  38178. if (arc === 1) {
  38179. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38180. uvs.push(uvs[2], uvs[3]);
  38181. }
  38182. //indices
  38183. var vertexNb = positions.length / 3;
  38184. for (var i = 1; i < vertexNb - 1; i++) {
  38185. indices.push(i + 1, 0, i);
  38186. }
  38187. // result
  38188. VertexData.ComputeNormals(positions, indices, normals);
  38189. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38190. var vertexData = new VertexData();
  38191. vertexData.indices = indices;
  38192. vertexData.positions = positions;
  38193. vertexData.normals = normals;
  38194. vertexData.uvs = uvs;
  38195. return vertexData;
  38196. };
  38197. /**
  38198. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38199. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38200. * @param polygon a mesh built from polygonTriangulation.build()
  38201. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38202. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38203. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38204. * @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)
  38205. * @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)
  38206. * @returns the VertexData of the Polygon
  38207. */
  38208. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38209. var faceUV = fUV || new Array(3);
  38210. var faceColors = fColors;
  38211. var colors = [];
  38212. // default face colors and UV if undefined
  38213. for (var f = 0; f < 3; f++) {
  38214. if (faceUV[f] === undefined) {
  38215. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38216. }
  38217. if (faceColors && faceColors[f] === undefined) {
  38218. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38219. }
  38220. }
  38221. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38222. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38223. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38224. var indices = polygon.getIndices();
  38225. // set face colours and textures
  38226. var idx = 0;
  38227. var face = 0;
  38228. for (var index = 0; index < normals.length; index += 3) {
  38229. //Edge Face no. 1
  38230. if (Math.abs(normals[index + 1]) < 0.001) {
  38231. face = 1;
  38232. }
  38233. //Top Face no. 0
  38234. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38235. face = 0;
  38236. }
  38237. //Bottom Face no. 2
  38238. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38239. face = 2;
  38240. }
  38241. idx = index / 3;
  38242. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38243. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38244. if (faceColors) {
  38245. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38246. }
  38247. }
  38248. // sides
  38249. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38250. // Result
  38251. var vertexData = new VertexData();
  38252. vertexData.indices = indices;
  38253. vertexData.positions = positions;
  38254. vertexData.normals = normals;
  38255. vertexData.uvs = uvs;
  38256. if (faceColors) {
  38257. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38258. vertexData.colors = totalColors;
  38259. }
  38260. return vertexData;
  38261. };
  38262. /**
  38263. * Creates the VertexData of the IcoSphere
  38264. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38265. * * radius the radius of the IcoSphere, optional default 1
  38266. * * radiusX allows stretching in the x direction, optional, default radius
  38267. * * radiusY allows stretching in the y direction, optional, default radius
  38268. * * radiusZ allows stretching in the z direction, optional, default radius
  38269. * * flat when true creates a flat shaded mesh, optional, default true
  38270. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38271. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38272. * * 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)
  38273. * * 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)
  38274. * @returns the VertexData of the IcoSphere
  38275. */
  38276. VertexData.CreateIcoSphere = function (options) {
  38277. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38278. var radius = options.radius || 1;
  38279. var flat = (options.flat === undefined) ? true : options.flat;
  38280. var subdivisions = options.subdivisions || 4;
  38281. var radiusX = options.radiusX || radius;
  38282. var radiusY = options.radiusY || radius;
  38283. var radiusZ = options.radiusZ || radius;
  38284. var t = (1 + Math.sqrt(5)) / 2;
  38285. // 12 vertex x,y,z
  38286. var ico_vertices = [
  38287. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38288. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38289. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38290. ];
  38291. // index of 3 vertex makes a face of icopshere
  38292. var ico_indices = [
  38293. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38294. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38295. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38296. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38297. ];
  38298. // vertex for uv have aliased position, not for UV
  38299. var vertices_unalias_id = [
  38300. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38301. // vertex alias
  38302. 0,
  38303. 2,
  38304. 3,
  38305. 3,
  38306. 3,
  38307. 4,
  38308. 7,
  38309. 8,
  38310. 9,
  38311. 9,
  38312. 10,
  38313. 11 // 23: B + 12
  38314. ];
  38315. // uv as integer step (not pixels !)
  38316. var ico_vertexuv = [
  38317. 5, 1, 3, 1, 6, 4, 0, 0,
  38318. 5, 3, 4, 2, 2, 2, 4, 0,
  38319. 2, 0, 1, 1, 6, 0, 6, 2,
  38320. // vertex alias (for same vertex on different faces)
  38321. 0, 4,
  38322. 3, 3,
  38323. 4, 4,
  38324. 3, 1,
  38325. 4, 2,
  38326. 4, 4,
  38327. 0, 2,
  38328. 1, 1,
  38329. 2, 2,
  38330. 3, 3,
  38331. 1, 3,
  38332. 2, 4 // 23: B + 12
  38333. ];
  38334. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38335. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38336. // First island of uv mapping
  38337. // v = 4h 3+ 2
  38338. // v = 3h 9+ 4
  38339. // v = 2h 9+ 5 B
  38340. // v = 1h 9 1 0
  38341. // v = 0h 3 8 7 A
  38342. // u = 0 1 2 3 4 5 6 *a
  38343. // Second island of uv mapping
  38344. // v = 4h 0+ B+ 4+
  38345. // v = 3h A+ 2+
  38346. // v = 2h 7+ 6 3+
  38347. // v = 1h 8+ 3+
  38348. // v = 0h
  38349. // u = 0 1 2 3 4 5 6 *a
  38350. // Face layout on texture UV mapping
  38351. // ============
  38352. // \ 4 /\ 16 / ======
  38353. // \ / \ / /\ 11 /
  38354. // \/ 7 \/ / \ /
  38355. // ======= / 10 \/
  38356. // /\ 17 /\ =======
  38357. // / \ / \ \ 15 /\
  38358. // / 8 \/ 12 \ \ / \
  38359. // ============ \/ 6 \
  38360. // \ 18 /\ ============
  38361. // \ / \ \ 5 /\ 0 /
  38362. // \/ 13 \ \ / \ /
  38363. // ======= \/ 1 \/
  38364. // =============
  38365. // /\ 19 /\ 2 /\
  38366. // / \ / \ / \
  38367. // / 14 \/ 9 \/ 3 \
  38368. // ===================
  38369. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38370. var ustep = 138 / 1024;
  38371. var vstep = 239 / 1024;
  38372. var uoffset = 60 / 1024;
  38373. var voffset = 26 / 1024;
  38374. // Second island should have margin, not to touch the first island
  38375. // avoid any borderline artefact in pixel rounding
  38376. var island_u_offset = -40 / 1024;
  38377. var island_v_offset = +20 / 1024;
  38378. // face is either island 0 or 1 :
  38379. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38380. var island = [
  38381. 0, 0, 0, 0, 1,
  38382. 0, 0, 1, 1, 0,
  38383. 0, 0, 1, 1, 0,
  38384. 0, 1, 1, 1, 0 // 15 - 19
  38385. ];
  38386. var indices = new Array();
  38387. var positions = new Array();
  38388. var normals = new Array();
  38389. var uvs = new Array();
  38390. var current_indice = 0;
  38391. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38392. var face_vertex_pos = new Array(3);
  38393. var face_vertex_uv = new Array(3);
  38394. var v012;
  38395. for (v012 = 0; v012 < 3; v012++) {
  38396. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38397. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38398. }
  38399. // create all with normals
  38400. for (var face = 0; face < 20; face++) {
  38401. // 3 vertex per face
  38402. for (v012 = 0; v012 < 3; v012++) {
  38403. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38404. var v_id = ico_indices[3 * face + v012];
  38405. // vertex have 3D position (x,y,z)
  38406. 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]);
  38407. // Normalize to get normal, then scale to radius
  38408. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38409. // uv Coordinates from vertex ID
  38410. 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);
  38411. }
  38412. // Subdivide the face (interpolate pos, norm, uv)
  38413. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38414. // - norm is linear interpolation of vertex corner normal
  38415. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38416. // - uv is linear interpolation
  38417. //
  38418. // Topology is as below for sub-divide by 2
  38419. // vertex shown as v0,v1,v2
  38420. // interp index is i1 to progress in range [v0,v1[
  38421. // interp index is i2 to progress in range [v0,v2[
  38422. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38423. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38424. //
  38425. //
  38426. // i2 v2
  38427. // ^ ^
  38428. // / / \
  38429. // / / \
  38430. // / / \
  38431. // / / (0,1) \
  38432. // / #---------\
  38433. // / / \ (0,0)'/ \
  38434. // / / \ / \
  38435. // / / \ / \
  38436. // / / (0,0) \ / (1,0) \
  38437. // / #---------#---------\
  38438. // v0 v1
  38439. //
  38440. // --------------------> i1
  38441. //
  38442. // interp of (i1,i2):
  38443. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38444. // along i1 : lerp(x0,x1, i1/(S-i2))
  38445. //
  38446. // centroid of triangle is needed to get help normal computation
  38447. // (c1,c2) are used for centroid location
  38448. var interp_vertex = function (i1, i2, c1, c2) {
  38449. // vertex is interpolated from
  38450. // - face_vertex_pos[0..2]
  38451. // - face_vertex_uv[0..2]
  38452. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38453. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38454. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38455. pos_interp.normalize();
  38456. var vertex_normal;
  38457. if (flat) {
  38458. // in flat mode, recalculate normal as face centroid normal
  38459. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38460. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38461. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38462. }
  38463. else {
  38464. // in smooth mode, recalculate normal from each single vertex position
  38465. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38466. }
  38467. // Vertex normal need correction due to X,Y,Z radius scaling
  38468. vertex_normal.x /= radiusX;
  38469. vertex_normal.y /= radiusY;
  38470. vertex_normal.z /= radiusZ;
  38471. vertex_normal.normalize();
  38472. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38473. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38474. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38475. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38476. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38477. uvs.push(uv_interp.x, uv_interp.y);
  38478. // push each vertex has member of a face
  38479. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38480. indices.push(current_indice);
  38481. current_indice++;
  38482. };
  38483. for (var i2 = 0; i2 < subdivisions; i2++) {
  38484. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38485. // face : (i1,i2) for /\ :
  38486. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38487. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38488. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38489. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38490. if (i1 + i2 + 1 < subdivisions) {
  38491. // face : (i1,i2)' for \/ :
  38492. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38493. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38494. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38495. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38496. }
  38497. }
  38498. }
  38499. }
  38500. // Sides
  38501. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38502. // Result
  38503. var vertexData = new VertexData();
  38504. vertexData.indices = indices;
  38505. vertexData.positions = positions;
  38506. vertexData.normals = normals;
  38507. vertexData.uvs = uvs;
  38508. return vertexData;
  38509. };
  38510. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38511. /**
  38512. * Creates the VertexData for a Polyhedron
  38513. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38514. * * type provided types are:
  38515. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38516. * * 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)
  38517. * * size the size of the IcoSphere, optional default 1
  38518. * * sizeX allows stretching in the x direction, optional, default size
  38519. * * sizeY allows stretching in the y direction, optional, default size
  38520. * * sizeZ allows stretching in the z direction, optional, default size
  38521. * * 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
  38522. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38523. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38524. * * flat when true creates a flat shaded mesh, optional, default true
  38525. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38526. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38527. * * 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)
  38528. * * 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)
  38529. * @returns the VertexData of the Polyhedron
  38530. */
  38531. VertexData.CreatePolyhedron = function (options) {
  38532. // provided polyhedron types :
  38533. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38534. // 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)
  38535. var polyhedra = [];
  38536. 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]] };
  38537. 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]] };
  38538. polyhedra[2] = {
  38539. 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]],
  38540. 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]]
  38541. };
  38542. polyhedra[3] = {
  38543. 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]],
  38544. 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]]
  38545. };
  38546. polyhedra[4] = {
  38547. 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]],
  38548. 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]]
  38549. };
  38550. 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]] };
  38551. 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]] };
  38552. 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]] };
  38553. 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]] };
  38554. 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]] };
  38555. 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]] };
  38556. 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]] };
  38557. 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]] };
  38558. 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]] };
  38559. polyhedra[14] = {
  38560. 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]],
  38561. 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]]
  38562. };
  38563. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38564. var size = options.size;
  38565. var sizeX = options.sizeX || size || 1;
  38566. var sizeY = options.sizeY || size || 1;
  38567. var sizeZ = options.sizeZ || size || 1;
  38568. var data = options.custom || polyhedra[type];
  38569. var nbfaces = data.face.length;
  38570. var faceUV = options.faceUV || new Array(nbfaces);
  38571. var faceColors = options.faceColors;
  38572. var flat = (options.flat === undefined) ? true : options.flat;
  38573. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38574. var positions = new Array();
  38575. var indices = new Array();
  38576. var normals = new Array();
  38577. var uvs = new Array();
  38578. var colors = new Array();
  38579. var index = 0;
  38580. var faceIdx = 0; // face cursor in the array "indexes"
  38581. var indexes = new Array();
  38582. var i = 0;
  38583. var f = 0;
  38584. var u, v, ang, x, y, tmp;
  38585. // default face colors and UV if undefined
  38586. if (flat) {
  38587. for (f = 0; f < nbfaces; f++) {
  38588. if (faceColors && faceColors[f] === undefined) {
  38589. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38590. }
  38591. if (faceUV && faceUV[f] === undefined) {
  38592. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38593. }
  38594. }
  38595. }
  38596. if (!flat) {
  38597. for (i = 0; i < data.vertex.length; i++) {
  38598. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38599. uvs.push(0, 0);
  38600. }
  38601. for (f = 0; f < nbfaces; f++) {
  38602. for (i = 0; i < data.face[f].length - 2; i++) {
  38603. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38604. }
  38605. }
  38606. }
  38607. else {
  38608. for (f = 0; f < nbfaces; f++) {
  38609. var fl = data.face[f].length; // number of vertices of the current face
  38610. ang = 2 * Math.PI / fl;
  38611. x = 0.5 * Math.tan(ang / 2);
  38612. y = 0.5;
  38613. // positions, uvs, colors
  38614. for (i = 0; i < fl; i++) {
  38615. // positions
  38616. 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);
  38617. indexes.push(index);
  38618. index++;
  38619. // uvs
  38620. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38621. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38622. uvs.push(u, v);
  38623. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38624. y = x * Math.sin(ang) + y * Math.cos(ang);
  38625. x = tmp;
  38626. // colors
  38627. if (faceColors) {
  38628. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38629. }
  38630. }
  38631. // indices from indexes
  38632. for (i = 0; i < fl - 2; i++) {
  38633. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38634. }
  38635. faceIdx += fl;
  38636. }
  38637. }
  38638. VertexData.ComputeNormals(positions, indices, normals);
  38639. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38640. var vertexData = new VertexData();
  38641. vertexData.positions = positions;
  38642. vertexData.indices = indices;
  38643. vertexData.normals = normals;
  38644. vertexData.uvs = uvs;
  38645. if (faceColors && flat) {
  38646. vertexData.colors = colors;
  38647. }
  38648. return vertexData;
  38649. };
  38650. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38651. /**
  38652. * Creates the VertexData for a TorusKnot
  38653. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38654. * * radius the radius of the torus knot, optional, default 2
  38655. * * tube the thickness of the tube, optional, default 0.5
  38656. * * radialSegments the number of sides on each tube segments, optional, default 32
  38657. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38658. * * p the number of windings around the z axis, optional, default 2
  38659. * * q the number of windings around the x axis, optional, default 3
  38660. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38661. * * 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)
  38662. * * 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)
  38663. * @returns the VertexData of the Torus Knot
  38664. */
  38665. VertexData.CreateTorusKnot = function (options) {
  38666. var indices = new Array();
  38667. var positions = new Array();
  38668. var normals = new Array();
  38669. var uvs = new Array();
  38670. var radius = options.radius || 2;
  38671. var tube = options.tube || 0.5;
  38672. var radialSegments = options.radialSegments || 32;
  38673. var tubularSegments = options.tubularSegments || 32;
  38674. var p = options.p || 2;
  38675. var q = options.q || 3;
  38676. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38677. // Helper
  38678. var getPos = function (angle) {
  38679. var cu = Math.cos(angle);
  38680. var su = Math.sin(angle);
  38681. var quOverP = q / p * angle;
  38682. var cs = Math.cos(quOverP);
  38683. var tx = radius * (2 + cs) * 0.5 * cu;
  38684. var ty = radius * (2 + cs) * su * 0.5;
  38685. var tz = radius * Math.sin(quOverP) * 0.5;
  38686. return new BABYLON.Vector3(tx, ty, tz);
  38687. };
  38688. // Vertices
  38689. var i;
  38690. var j;
  38691. for (i = 0; i <= radialSegments; i++) {
  38692. var modI = i % radialSegments;
  38693. var u = modI / radialSegments * 2 * p * Math.PI;
  38694. var p1 = getPos(u);
  38695. var p2 = getPos(u + 0.01);
  38696. var tang = p2.subtract(p1);
  38697. var n = p2.add(p1);
  38698. var bitan = BABYLON.Vector3.Cross(tang, n);
  38699. n = BABYLON.Vector3.Cross(bitan, tang);
  38700. bitan.normalize();
  38701. n.normalize();
  38702. for (j = 0; j < tubularSegments; j++) {
  38703. var modJ = j % tubularSegments;
  38704. var v = modJ / tubularSegments * 2 * Math.PI;
  38705. var cx = -tube * Math.cos(v);
  38706. var cy = tube * Math.sin(v);
  38707. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38708. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38709. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38710. uvs.push(i / radialSegments);
  38711. uvs.push(j / tubularSegments);
  38712. }
  38713. }
  38714. for (i = 0; i < radialSegments; i++) {
  38715. for (j = 0; j < tubularSegments; j++) {
  38716. var jNext = (j + 1) % tubularSegments;
  38717. var a = i * tubularSegments + j;
  38718. var b = (i + 1) * tubularSegments + j;
  38719. var c = (i + 1) * tubularSegments + jNext;
  38720. var d = i * tubularSegments + jNext;
  38721. indices.push(d);
  38722. indices.push(b);
  38723. indices.push(a);
  38724. indices.push(d);
  38725. indices.push(c);
  38726. indices.push(b);
  38727. }
  38728. }
  38729. // Normals
  38730. VertexData.ComputeNormals(positions, indices, normals);
  38731. // Sides
  38732. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38733. // Result
  38734. var vertexData = new VertexData();
  38735. vertexData.indices = indices;
  38736. vertexData.positions = positions;
  38737. vertexData.normals = normals;
  38738. vertexData.uvs = uvs;
  38739. return vertexData;
  38740. };
  38741. // Tools
  38742. /**
  38743. * Compute normals for given positions and indices
  38744. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38745. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38746. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38747. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38748. * * facetNormals : optional array of facet normals (vector3)
  38749. * * facetPositions : optional array of facet positions (vector3)
  38750. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38751. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38752. * * bInfo : optional bounding info, required for facetPartitioning computation
  38753. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38754. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38755. * * useRightHandedSystem: optional boolean to for right handed system computation
  38756. * * depthSort : optional boolean to enable the facet depth sort computation
  38757. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38758. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38759. */
  38760. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38761. // temporary scalar variables
  38762. var index = 0; // facet index
  38763. var p1p2x = 0.0; // p1p2 vector x coordinate
  38764. var p1p2y = 0.0; // p1p2 vector y coordinate
  38765. var p1p2z = 0.0; // p1p2 vector z coordinate
  38766. var p3p2x = 0.0; // p3p2 vector x coordinate
  38767. var p3p2y = 0.0; // p3p2 vector y coordinate
  38768. var p3p2z = 0.0; // p3p2 vector z coordinate
  38769. var faceNormalx = 0.0; // facet normal x coordinate
  38770. var faceNormaly = 0.0; // facet normal y coordinate
  38771. var faceNormalz = 0.0; // facet normal z coordinate
  38772. var length = 0.0; // facet normal length before normalization
  38773. var v1x = 0; // vector1 x index in the positions array
  38774. var v1y = 0; // vector1 y index in the positions array
  38775. var v1z = 0; // vector1 z index in the positions array
  38776. var v2x = 0; // vector2 x index in the positions array
  38777. var v2y = 0; // vector2 y index in the positions array
  38778. var v2z = 0; // vector2 z index in the positions array
  38779. var v3x = 0; // vector3 x index in the positions array
  38780. var v3y = 0; // vector3 y index in the positions array
  38781. var v3z = 0; // vector3 z index in the positions array
  38782. var computeFacetNormals = false;
  38783. var computeFacetPositions = false;
  38784. var computeFacetPartitioning = false;
  38785. var computeDepthSort = false;
  38786. var faceNormalSign = 1;
  38787. var ratio = 0;
  38788. var distanceTo = null;
  38789. if (options) {
  38790. computeFacetNormals = (options.facetNormals) ? true : false;
  38791. computeFacetPositions = (options.facetPositions) ? true : false;
  38792. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38793. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38794. ratio = options.ratio || 0;
  38795. computeDepthSort = (options.depthSort) ? true : false;
  38796. distanceTo = (options.distanceTo);
  38797. if (computeDepthSort) {
  38798. if (distanceTo === undefined) {
  38799. distanceTo = BABYLON.Vector3.Zero();
  38800. }
  38801. var depthSortedFacets = options.depthSortedFacets;
  38802. }
  38803. }
  38804. // facetPartitioning reinit if needed
  38805. var xSubRatio = 0;
  38806. var ySubRatio = 0;
  38807. var zSubRatio = 0;
  38808. var subSq = 0;
  38809. if (computeFacetPartitioning && options && options.bbSize) {
  38810. var ox = 0; // X partitioning index for facet position
  38811. var oy = 0; // Y partinioning index for facet position
  38812. var oz = 0; // Z partinioning index for facet position
  38813. var b1x = 0; // X partitioning index for facet v1 vertex
  38814. var b1y = 0; // Y partitioning index for facet v1 vertex
  38815. var b1z = 0; // z partitioning index for facet v1 vertex
  38816. var b2x = 0; // X partitioning index for facet v2 vertex
  38817. var b2y = 0; // Y partitioning index for facet v2 vertex
  38818. var b2z = 0; // Z partitioning index for facet v2 vertex
  38819. var b3x = 0; // X partitioning index for facet v3 vertex
  38820. var b3y = 0; // Y partitioning index for facet v3 vertex
  38821. var b3z = 0; // Z partitioning index for facet v3 vertex
  38822. var block_idx_o = 0; // facet barycenter block index
  38823. var block_idx_v1 = 0; // v1 vertex block index
  38824. var block_idx_v2 = 0; // v2 vertex block index
  38825. var block_idx_v3 = 0; // v3 vertex block index
  38826. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38827. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38828. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38829. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38830. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38831. subSq = options.subDiv.max * options.subDiv.max;
  38832. options.facetPartitioning.length = 0;
  38833. }
  38834. // reset the normals
  38835. for (index = 0; index < positions.length; index++) {
  38836. normals[index] = 0.0;
  38837. }
  38838. // Loop : 1 indice triplet = 1 facet
  38839. var nbFaces = (indices.length / 3) | 0;
  38840. for (index = 0; index < nbFaces; index++) {
  38841. // get the indexes of the coordinates of each vertex of the facet
  38842. v1x = indices[index * 3] * 3;
  38843. v1y = v1x + 1;
  38844. v1z = v1x + 2;
  38845. v2x = indices[index * 3 + 1] * 3;
  38846. v2y = v2x + 1;
  38847. v2z = v2x + 2;
  38848. v3x = indices[index * 3 + 2] * 3;
  38849. v3y = v3x + 1;
  38850. v3z = v3x + 2;
  38851. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38852. p1p2y = positions[v1y] - positions[v2y];
  38853. p1p2z = positions[v1z] - positions[v2z];
  38854. p3p2x = positions[v3x] - positions[v2x];
  38855. p3p2y = positions[v3y] - positions[v2y];
  38856. p3p2z = positions[v3z] - positions[v2z];
  38857. // compute the face normal with the cross product
  38858. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38859. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38860. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38861. // normalize this normal and store it in the array facetData
  38862. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38863. length = (length === 0) ? 1.0 : length;
  38864. faceNormalx /= length;
  38865. faceNormaly /= length;
  38866. faceNormalz /= length;
  38867. if (computeFacetNormals && options) {
  38868. options.facetNormals[index].x = faceNormalx;
  38869. options.facetNormals[index].y = faceNormaly;
  38870. options.facetNormals[index].z = faceNormalz;
  38871. }
  38872. if (computeFacetPositions && options) {
  38873. // compute and the facet barycenter coordinates in the array facetPositions
  38874. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38875. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38876. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38877. }
  38878. if (computeFacetPartitioning && options) {
  38879. // store the facet indexes in arrays in the main facetPartitioning array :
  38880. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38881. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38882. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38883. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38884. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38885. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38886. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38887. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38888. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38889. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38890. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38891. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38892. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38893. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38894. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38895. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38896. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38897. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38898. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38899. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38900. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38901. // push each facet index in each block containing the vertex
  38902. options.facetPartitioning[block_idx_v1].push(index);
  38903. if (block_idx_v2 != block_idx_v1) {
  38904. options.facetPartitioning[block_idx_v2].push(index);
  38905. }
  38906. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38907. options.facetPartitioning[block_idx_v3].push(index);
  38908. }
  38909. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38910. options.facetPartitioning[block_idx_o].push(index);
  38911. }
  38912. }
  38913. if (computeDepthSort && options && options.facetPositions) {
  38914. var dsf = depthSortedFacets[index];
  38915. dsf.ind = index * 3;
  38916. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38917. }
  38918. // compute the normals anyway
  38919. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38920. normals[v1y] += faceNormaly;
  38921. normals[v1z] += faceNormalz;
  38922. normals[v2x] += faceNormalx;
  38923. normals[v2y] += faceNormaly;
  38924. normals[v2z] += faceNormalz;
  38925. normals[v3x] += faceNormalx;
  38926. normals[v3y] += faceNormaly;
  38927. normals[v3z] += faceNormalz;
  38928. }
  38929. // last normalization of each normal
  38930. for (index = 0; index < normals.length / 3; index++) {
  38931. faceNormalx = normals[index * 3];
  38932. faceNormaly = normals[index * 3 + 1];
  38933. faceNormalz = normals[index * 3 + 2];
  38934. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38935. length = (length === 0) ? 1.0 : length;
  38936. faceNormalx /= length;
  38937. faceNormaly /= length;
  38938. faceNormalz /= length;
  38939. normals[index * 3] = faceNormalx;
  38940. normals[index * 3 + 1] = faceNormaly;
  38941. normals[index * 3 + 2] = faceNormalz;
  38942. }
  38943. };
  38944. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38945. var li = indices.length;
  38946. var ln = normals.length;
  38947. var i;
  38948. var n;
  38949. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38950. switch (sideOrientation) {
  38951. case BABYLON.Mesh.FRONTSIDE:
  38952. // nothing changed
  38953. break;
  38954. case BABYLON.Mesh.BACKSIDE:
  38955. var tmp;
  38956. // indices
  38957. for (i = 0; i < li; i += 3) {
  38958. tmp = indices[i];
  38959. indices[i] = indices[i + 2];
  38960. indices[i + 2] = tmp;
  38961. }
  38962. // normals
  38963. for (n = 0; n < ln; n++) {
  38964. normals[n] = -normals[n];
  38965. }
  38966. break;
  38967. case BABYLON.Mesh.DOUBLESIDE:
  38968. // positions
  38969. var lp = positions.length;
  38970. var l = lp / 3;
  38971. for (var p = 0; p < lp; p++) {
  38972. positions[lp + p] = positions[p];
  38973. }
  38974. // indices
  38975. for (i = 0; i < li; i += 3) {
  38976. indices[i + li] = indices[i + 2] + l;
  38977. indices[i + 1 + li] = indices[i + 1] + l;
  38978. indices[i + 2 + li] = indices[i] + l;
  38979. }
  38980. // normals
  38981. for (n = 0; n < ln; n++) {
  38982. normals[ln + n] = -normals[n];
  38983. }
  38984. // uvs
  38985. var lu = uvs.length;
  38986. var u = 0;
  38987. for (u = 0; u < lu; u++) {
  38988. uvs[u + lu] = uvs[u];
  38989. }
  38990. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38991. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38992. u = 0;
  38993. for (i = 0; i < lu / 2; i++) {
  38994. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38995. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38996. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38997. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38998. u += 2;
  38999. }
  39000. break;
  39001. }
  39002. };
  39003. /**
  39004. * Applies VertexData created from the imported parameters to the geometry
  39005. * @param parsedVertexData the parsed data from an imported file
  39006. * @param geometry the geometry to apply the VertexData to
  39007. */
  39008. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39009. var vertexData = new VertexData();
  39010. // positions
  39011. var positions = parsedVertexData.positions;
  39012. if (positions) {
  39013. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39014. }
  39015. // normals
  39016. var normals = parsedVertexData.normals;
  39017. if (normals) {
  39018. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39019. }
  39020. // tangents
  39021. var tangents = parsedVertexData.tangents;
  39022. if (tangents) {
  39023. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39024. }
  39025. // uvs
  39026. var uvs = parsedVertexData.uvs;
  39027. if (uvs) {
  39028. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39029. }
  39030. // uv2s
  39031. var uv2s = parsedVertexData.uv2s;
  39032. if (uv2s) {
  39033. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39034. }
  39035. // uv3s
  39036. var uv3s = parsedVertexData.uv3s;
  39037. if (uv3s) {
  39038. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39039. }
  39040. // uv4s
  39041. var uv4s = parsedVertexData.uv4s;
  39042. if (uv4s) {
  39043. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39044. }
  39045. // uv5s
  39046. var uv5s = parsedVertexData.uv5s;
  39047. if (uv5s) {
  39048. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39049. }
  39050. // uv6s
  39051. var uv6s = parsedVertexData.uv6s;
  39052. if (uv6s) {
  39053. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39054. }
  39055. // colors
  39056. var colors = parsedVertexData.colors;
  39057. if (colors) {
  39058. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39059. }
  39060. // matricesIndices
  39061. var matricesIndices = parsedVertexData.matricesIndices;
  39062. if (matricesIndices) {
  39063. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39064. }
  39065. // matricesWeights
  39066. var matricesWeights = parsedVertexData.matricesWeights;
  39067. if (matricesWeights) {
  39068. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39069. }
  39070. // indices
  39071. var indices = parsedVertexData.indices;
  39072. if (indices) {
  39073. vertexData.indices = indices;
  39074. }
  39075. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39076. };
  39077. return VertexData;
  39078. }());
  39079. BABYLON.VertexData = VertexData;
  39080. })(BABYLON || (BABYLON = {}));
  39081. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39082. var BABYLON;
  39083. (function (BABYLON) {
  39084. /**
  39085. * Class used to store geometry data (vertex buffers + index buffer)
  39086. */
  39087. var Geometry = /** @class */ (function () {
  39088. /**
  39089. * Creates a new geometry
  39090. * @param id defines the unique ID
  39091. * @param scene defines the hosting scene
  39092. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39093. * @param updatable defines if geometry must be updatable (false by default)
  39094. * @param mesh defines the mesh that will be associated with the geometry
  39095. */
  39096. function Geometry(id, scene, vertexData, updatable, mesh) {
  39097. if (updatable === void 0) { updatable = false; }
  39098. if (mesh === void 0) { mesh = null; }
  39099. /**
  39100. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39101. */
  39102. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39103. this._totalVertices = 0;
  39104. this._isDisposed = false;
  39105. this._indexBufferIsUpdatable = false;
  39106. this.id = id;
  39107. this._engine = scene.getEngine();
  39108. this._meshes = [];
  39109. this._scene = scene;
  39110. //Init vertex buffer cache
  39111. this._vertexBuffers = {};
  39112. this._indices = [];
  39113. this._updatable = updatable;
  39114. // vertexData
  39115. if (vertexData) {
  39116. this.setAllVerticesData(vertexData, updatable);
  39117. }
  39118. else {
  39119. this._totalVertices = 0;
  39120. this._indices = [];
  39121. }
  39122. if (this._engine.getCaps().vertexArrayObject) {
  39123. this._vertexArrayObjects = {};
  39124. }
  39125. // applyToMesh
  39126. if (mesh) {
  39127. if (mesh.getClassName() === "LinesMesh") {
  39128. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39129. this._updateExtend();
  39130. }
  39131. this.applyToMesh(mesh);
  39132. mesh.computeWorldMatrix(true);
  39133. }
  39134. }
  39135. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39136. /**
  39137. * 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
  39138. */
  39139. get: function () {
  39140. return this._boundingBias;
  39141. },
  39142. /**
  39143. * 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
  39144. */
  39145. set: function (value) {
  39146. if (this._boundingBias && this._boundingBias.equals(value)) {
  39147. return;
  39148. }
  39149. this._boundingBias = value.clone();
  39150. this._updateBoundingInfo(true, null);
  39151. },
  39152. enumerable: true,
  39153. configurable: true
  39154. });
  39155. /**
  39156. * Static function used to attach a new empty geometry to a mesh
  39157. * @param mesh defines the mesh to attach the geometry to
  39158. * @returns the new {BABYLON.Geometry}
  39159. */
  39160. Geometry.CreateGeometryForMesh = function (mesh) {
  39161. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39162. geometry.applyToMesh(mesh);
  39163. return geometry;
  39164. };
  39165. Object.defineProperty(Geometry.prototype, "extend", {
  39166. /**
  39167. * Gets the current extend of the geometry
  39168. */
  39169. get: function () {
  39170. return this._extend;
  39171. },
  39172. enumerable: true,
  39173. configurable: true
  39174. });
  39175. /**
  39176. * Gets the hosting scene
  39177. * @returns the hosting {BABYLON.Scene}
  39178. */
  39179. Geometry.prototype.getScene = function () {
  39180. return this._scene;
  39181. };
  39182. /**
  39183. * Gets the hosting engine
  39184. * @returns the hosting {BABYLON.Engine}
  39185. */
  39186. Geometry.prototype.getEngine = function () {
  39187. return this._engine;
  39188. };
  39189. /**
  39190. * Defines if the geometry is ready to use
  39191. * @returns true if the geometry is ready to be used
  39192. */
  39193. Geometry.prototype.isReady = function () {
  39194. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39195. };
  39196. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39197. /**
  39198. * Gets a value indicating that the geometry should not be serialized
  39199. */
  39200. get: function () {
  39201. for (var index = 0; index < this._meshes.length; index++) {
  39202. if (!this._meshes[index].doNotSerialize) {
  39203. return false;
  39204. }
  39205. }
  39206. return true;
  39207. },
  39208. enumerable: true,
  39209. configurable: true
  39210. });
  39211. /** @hidden */
  39212. Geometry.prototype._rebuild = function () {
  39213. if (this._vertexArrayObjects) {
  39214. this._vertexArrayObjects = {};
  39215. }
  39216. // Index buffer
  39217. if (this._meshes.length !== 0 && this._indices) {
  39218. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39219. }
  39220. // Vertex buffers
  39221. for (var key in this._vertexBuffers) {
  39222. var vertexBuffer = this._vertexBuffers[key];
  39223. vertexBuffer._rebuild();
  39224. }
  39225. };
  39226. /**
  39227. * Affects all geometry data in one call
  39228. * @param vertexData defines the geometry data
  39229. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39230. */
  39231. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39232. vertexData.applyToGeometry(this, updatable);
  39233. this.notifyUpdate();
  39234. };
  39235. /**
  39236. * Set specific vertex data
  39237. * @param kind defines the data kind (Position, normal, etc...)
  39238. * @param data defines the vertex data to use
  39239. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39240. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39241. */
  39242. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39243. if (updatable === void 0) { updatable = false; }
  39244. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39245. this.setVerticesBuffer(buffer);
  39246. };
  39247. /**
  39248. * Removes a specific vertex data
  39249. * @param kind defines the data kind (Position, normal, etc...)
  39250. */
  39251. Geometry.prototype.removeVerticesData = function (kind) {
  39252. if (this._vertexBuffers[kind]) {
  39253. this._vertexBuffers[kind].dispose();
  39254. delete this._vertexBuffers[kind];
  39255. }
  39256. };
  39257. /**
  39258. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39259. * @param buffer defines the vertex buffer to use
  39260. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39261. */
  39262. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39263. if (totalVertices === void 0) { totalVertices = null; }
  39264. var kind = buffer.getKind();
  39265. if (this._vertexBuffers[kind]) {
  39266. this._vertexBuffers[kind].dispose();
  39267. }
  39268. this._vertexBuffers[kind] = buffer;
  39269. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39270. var data = buffer.getData();
  39271. if (totalVertices != null) {
  39272. this._totalVertices = totalVertices;
  39273. }
  39274. else {
  39275. if (data != null) {
  39276. this._totalVertices = data.length / (buffer.byteStride / 4);
  39277. }
  39278. }
  39279. this._updateExtend(data);
  39280. this._resetPointsArrayCache();
  39281. var meshes = this._meshes;
  39282. var numOfMeshes = meshes.length;
  39283. for (var index = 0; index < numOfMeshes; index++) {
  39284. var mesh = meshes[index];
  39285. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39286. mesh._createGlobalSubMesh(false);
  39287. mesh.computeWorldMatrix(true);
  39288. }
  39289. }
  39290. this.notifyUpdate(kind);
  39291. if (this._vertexArrayObjects) {
  39292. this._disposeVertexArrayObjects();
  39293. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39294. }
  39295. };
  39296. /**
  39297. * Update a specific vertex buffer
  39298. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39299. * It will do nothing if the buffer is not updatable
  39300. * @param kind defines the data kind (Position, normal, etc...)
  39301. * @param data defines the data to use
  39302. * @param offset defines the offset in the target buffer where to store the data
  39303. * @param useBytes set to true if the offset is in bytes
  39304. */
  39305. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39306. if (useBytes === void 0) { useBytes = false; }
  39307. var vertexBuffer = this.getVertexBuffer(kind);
  39308. if (!vertexBuffer) {
  39309. return;
  39310. }
  39311. vertexBuffer.updateDirectly(data, offset, useBytes);
  39312. this.notifyUpdate(kind);
  39313. };
  39314. /**
  39315. * Update a specific vertex buffer
  39316. * This function will create a new buffer if the current one is not updatable
  39317. * @param kind defines the data kind (Position, normal, etc...)
  39318. * @param data defines the data to use
  39319. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39320. */
  39321. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39322. if (updateExtends === void 0) { updateExtends = false; }
  39323. var vertexBuffer = this.getVertexBuffer(kind);
  39324. if (!vertexBuffer) {
  39325. return;
  39326. }
  39327. vertexBuffer.update(data);
  39328. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39329. this._updateBoundingInfo(updateExtends, data);
  39330. }
  39331. this.notifyUpdate(kind);
  39332. };
  39333. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39334. if (updateExtends) {
  39335. this._updateExtend(data);
  39336. }
  39337. var meshes = this._meshes;
  39338. var numOfMeshes = meshes.length;
  39339. this._resetPointsArrayCache();
  39340. for (var index = 0; index < numOfMeshes; index++) {
  39341. var mesh = meshes[index];
  39342. if (updateExtends) {
  39343. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39344. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39345. var subMesh = mesh.subMeshes[subIndex];
  39346. subMesh.refreshBoundingInfo();
  39347. }
  39348. }
  39349. }
  39350. };
  39351. /** @hidden */
  39352. Geometry.prototype._bind = function (effect, indexToBind) {
  39353. if (!effect) {
  39354. return;
  39355. }
  39356. if (indexToBind === undefined) {
  39357. indexToBind = this._indexBuffer;
  39358. }
  39359. var vbs = this.getVertexBuffers();
  39360. if (!vbs) {
  39361. return;
  39362. }
  39363. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39364. this._engine.bindBuffers(vbs, indexToBind, effect);
  39365. return;
  39366. }
  39367. // Using VAO
  39368. if (!this._vertexArrayObjects[effect.key]) {
  39369. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39370. }
  39371. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39372. };
  39373. /**
  39374. * Gets total number of vertices
  39375. * @returns the total number of vertices
  39376. */
  39377. Geometry.prototype.getTotalVertices = function () {
  39378. if (!this.isReady()) {
  39379. return 0;
  39380. }
  39381. return this._totalVertices;
  39382. };
  39383. /**
  39384. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39385. * @param kind defines the data kind (Position, normal, etc...)
  39386. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39387. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39388. * @returns a float array containing vertex data
  39389. */
  39390. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39391. var vertexBuffer = this.getVertexBuffer(kind);
  39392. if (!vertexBuffer) {
  39393. return null;
  39394. }
  39395. var data = vertexBuffer.getData();
  39396. if (!data) {
  39397. return null;
  39398. }
  39399. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39400. var count = this._totalVertices * vertexBuffer.getSize();
  39401. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39402. var copy_1 = new Array(count);
  39403. vertexBuffer.forEach(count, function (value, index) {
  39404. copy_1[index] = value;
  39405. });
  39406. return copy_1;
  39407. }
  39408. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39409. if (data instanceof Array) {
  39410. var offset = vertexBuffer.byteOffset / 4;
  39411. return BABYLON.Tools.Slice(data, offset, offset + count);
  39412. }
  39413. else if (data instanceof ArrayBuffer) {
  39414. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39415. }
  39416. else {
  39417. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39418. }
  39419. }
  39420. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39421. return BABYLON.Tools.Slice(data);
  39422. }
  39423. return data;
  39424. };
  39425. /**
  39426. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39427. * @param kind defines the data kind (Position, normal, etc...)
  39428. * @returns true if the vertex buffer with the specified kind is updatable
  39429. */
  39430. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39431. var vb = this._vertexBuffers[kind];
  39432. if (!vb) {
  39433. return false;
  39434. }
  39435. return vb.isUpdatable();
  39436. };
  39437. /**
  39438. * Gets a specific vertex buffer
  39439. * @param kind defines the data kind (Position, normal, etc...)
  39440. * @returns a {BABYLON.VertexBuffer}
  39441. */
  39442. Geometry.prototype.getVertexBuffer = function (kind) {
  39443. if (!this.isReady()) {
  39444. return null;
  39445. }
  39446. return this._vertexBuffers[kind];
  39447. };
  39448. /**
  39449. * Returns all vertex buffers
  39450. * @return an object holding all vertex buffers indexed by kind
  39451. */
  39452. Geometry.prototype.getVertexBuffers = function () {
  39453. if (!this.isReady()) {
  39454. return null;
  39455. }
  39456. return this._vertexBuffers;
  39457. };
  39458. /**
  39459. * Gets a boolean indicating if specific vertex buffer is present
  39460. * @param kind defines the data kind (Position, normal, etc...)
  39461. * @returns true if data is present
  39462. */
  39463. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39464. if (!this._vertexBuffers) {
  39465. if (this._delayInfo) {
  39466. return this._delayInfo.indexOf(kind) !== -1;
  39467. }
  39468. return false;
  39469. }
  39470. return this._vertexBuffers[kind] !== undefined;
  39471. };
  39472. /**
  39473. * Gets a list of all attached data kinds (Position, normal, etc...)
  39474. * @returns a list of string containing all kinds
  39475. */
  39476. Geometry.prototype.getVerticesDataKinds = function () {
  39477. var result = [];
  39478. var kind;
  39479. if (!this._vertexBuffers && this._delayInfo) {
  39480. for (kind in this._delayInfo) {
  39481. result.push(kind);
  39482. }
  39483. }
  39484. else {
  39485. for (kind in this._vertexBuffers) {
  39486. result.push(kind);
  39487. }
  39488. }
  39489. return result;
  39490. };
  39491. /**
  39492. * Update index buffer
  39493. * @param indices defines the indices to store in the index buffer
  39494. * @param offset defines the offset in the target buffer where to store the data
  39495. */
  39496. Geometry.prototype.updateIndices = function (indices, offset) {
  39497. if (!this._indexBuffer) {
  39498. return;
  39499. }
  39500. if (!this._indexBufferIsUpdatable) {
  39501. this.setIndices(indices, null, true);
  39502. }
  39503. else {
  39504. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39505. }
  39506. };
  39507. /**
  39508. * Creates a new index buffer
  39509. * @param indices defines the indices to store in the index buffer
  39510. * @param totalVertices defines the total number of vertices (could be null)
  39511. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39512. */
  39513. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39514. if (totalVertices === void 0) { totalVertices = null; }
  39515. if (updatable === void 0) { updatable = false; }
  39516. if (this._indexBuffer) {
  39517. this._engine._releaseBuffer(this._indexBuffer);
  39518. }
  39519. this._disposeVertexArrayObjects();
  39520. this._indices = indices;
  39521. this._indexBufferIsUpdatable = updatable;
  39522. if (this._meshes.length !== 0 && this._indices) {
  39523. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39524. }
  39525. if (totalVertices != undefined) { // including null and undefined
  39526. this._totalVertices = totalVertices;
  39527. }
  39528. var meshes = this._meshes;
  39529. var numOfMeshes = meshes.length;
  39530. for (var index = 0; index < numOfMeshes; index++) {
  39531. meshes[index]._createGlobalSubMesh(true);
  39532. }
  39533. this.notifyUpdate();
  39534. };
  39535. /**
  39536. * Return the total number of indices
  39537. * @returns the total number of indices
  39538. */
  39539. Geometry.prototype.getTotalIndices = function () {
  39540. if (!this.isReady()) {
  39541. return 0;
  39542. }
  39543. return this._indices.length;
  39544. };
  39545. /**
  39546. * Gets the index buffer array
  39547. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39548. * @returns the index buffer array
  39549. */
  39550. Geometry.prototype.getIndices = function (copyWhenShared) {
  39551. if (!this.isReady()) {
  39552. return null;
  39553. }
  39554. var orig = this._indices;
  39555. if (!copyWhenShared || this._meshes.length === 1) {
  39556. return orig;
  39557. }
  39558. else {
  39559. var len = orig.length;
  39560. var copy = [];
  39561. for (var i = 0; i < len; i++) {
  39562. copy.push(orig[i]);
  39563. }
  39564. return copy;
  39565. }
  39566. };
  39567. /**
  39568. * Gets the index buffer
  39569. * @return the index buffer
  39570. */
  39571. Geometry.prototype.getIndexBuffer = function () {
  39572. if (!this.isReady()) {
  39573. return null;
  39574. }
  39575. return this._indexBuffer;
  39576. };
  39577. /** @hidden */
  39578. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39579. if (effect === void 0) { effect = null; }
  39580. if (!effect || !this._vertexArrayObjects) {
  39581. return;
  39582. }
  39583. if (this._vertexArrayObjects[effect.key]) {
  39584. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39585. delete this._vertexArrayObjects[effect.key];
  39586. }
  39587. };
  39588. /**
  39589. * Release the associated resources for a specific mesh
  39590. * @param mesh defines the source mesh
  39591. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39592. */
  39593. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39594. var meshes = this._meshes;
  39595. var index = meshes.indexOf(mesh);
  39596. if (index === -1) {
  39597. return;
  39598. }
  39599. meshes.splice(index, 1);
  39600. mesh._geometry = null;
  39601. if (meshes.length === 0 && shouldDispose) {
  39602. this.dispose();
  39603. }
  39604. };
  39605. /**
  39606. * Apply current geometry to a given mesh
  39607. * @param mesh defines the mesh to apply geometry to
  39608. */
  39609. Geometry.prototype.applyToMesh = function (mesh) {
  39610. if (mesh._geometry === this) {
  39611. return;
  39612. }
  39613. var previousGeometry = mesh._geometry;
  39614. if (previousGeometry) {
  39615. previousGeometry.releaseForMesh(mesh);
  39616. }
  39617. var meshes = this._meshes;
  39618. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39619. mesh._geometry = this;
  39620. this._scene.pushGeometry(this);
  39621. meshes.push(mesh);
  39622. if (this.isReady()) {
  39623. this._applyToMesh(mesh);
  39624. }
  39625. else {
  39626. mesh._boundingInfo = this._boundingInfo;
  39627. }
  39628. };
  39629. Geometry.prototype._updateExtend = function (data) {
  39630. if (data === void 0) { data = null; }
  39631. if (!data) {
  39632. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39633. }
  39634. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39635. };
  39636. Geometry.prototype._applyToMesh = function (mesh) {
  39637. var numOfMeshes = this._meshes.length;
  39638. // vertexBuffers
  39639. for (var kind in this._vertexBuffers) {
  39640. if (numOfMeshes === 1) {
  39641. this._vertexBuffers[kind].create();
  39642. }
  39643. var buffer = this._vertexBuffers[kind].getBuffer();
  39644. if (buffer)
  39645. buffer.references = numOfMeshes;
  39646. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39647. if (!this._extend) {
  39648. this._updateExtend();
  39649. }
  39650. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39651. mesh._createGlobalSubMesh(false);
  39652. //bounding info was just created again, world matrix should be applied again.
  39653. mesh._updateBoundingInfo();
  39654. }
  39655. }
  39656. // indexBuffer
  39657. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39658. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39659. }
  39660. if (this._indexBuffer) {
  39661. this._indexBuffer.references = numOfMeshes;
  39662. }
  39663. };
  39664. Geometry.prototype.notifyUpdate = function (kind) {
  39665. if (this.onGeometryUpdated) {
  39666. this.onGeometryUpdated(this, kind);
  39667. }
  39668. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39669. var mesh = _a[_i];
  39670. mesh._markSubMeshesAsAttributesDirty();
  39671. }
  39672. };
  39673. /**
  39674. * Load the geometry if it was flagged as delay loaded
  39675. * @param scene defines the hosting scene
  39676. * @param onLoaded defines a callback called when the geometry is loaded
  39677. */
  39678. Geometry.prototype.load = function (scene, onLoaded) {
  39679. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39680. return;
  39681. }
  39682. if (this.isReady()) {
  39683. if (onLoaded) {
  39684. onLoaded();
  39685. }
  39686. return;
  39687. }
  39688. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39689. this._queueLoad(scene, onLoaded);
  39690. };
  39691. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39692. var _this = this;
  39693. if (!this.delayLoadingFile) {
  39694. return;
  39695. }
  39696. scene._addPendingData(this);
  39697. scene._loadFile(this.delayLoadingFile, function (data) {
  39698. if (!_this._delayLoadingFunction) {
  39699. return;
  39700. }
  39701. _this._delayLoadingFunction(JSON.parse(data), _this);
  39702. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39703. _this._delayInfo = [];
  39704. scene._removePendingData(_this);
  39705. var meshes = _this._meshes;
  39706. var numOfMeshes = meshes.length;
  39707. for (var index = 0; index < numOfMeshes; index++) {
  39708. _this._applyToMesh(meshes[index]);
  39709. }
  39710. if (onLoaded) {
  39711. onLoaded();
  39712. }
  39713. }, undefined, true);
  39714. };
  39715. /**
  39716. * Invert the geometry to move from a right handed system to a left handed one.
  39717. */
  39718. Geometry.prototype.toLeftHanded = function () {
  39719. // Flip faces
  39720. var tIndices = this.getIndices(false);
  39721. if (tIndices != null && tIndices.length > 0) {
  39722. for (var i = 0; i < tIndices.length; i += 3) {
  39723. var tTemp = tIndices[i + 0];
  39724. tIndices[i + 0] = tIndices[i + 2];
  39725. tIndices[i + 2] = tTemp;
  39726. }
  39727. this.setIndices(tIndices);
  39728. }
  39729. // Negate position.z
  39730. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39731. if (tPositions != null && tPositions.length > 0) {
  39732. for (var i = 0; i < tPositions.length; i += 3) {
  39733. tPositions[i + 2] = -tPositions[i + 2];
  39734. }
  39735. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39736. }
  39737. // Negate normal.z
  39738. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39739. if (tNormals != null && tNormals.length > 0) {
  39740. for (var i = 0; i < tNormals.length; i += 3) {
  39741. tNormals[i + 2] = -tNormals[i + 2];
  39742. }
  39743. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39744. }
  39745. };
  39746. // Cache
  39747. /** @hidden */
  39748. Geometry.prototype._resetPointsArrayCache = function () {
  39749. this._positions = null;
  39750. };
  39751. /** @hidden */
  39752. Geometry.prototype._generatePointsArray = function () {
  39753. if (this._positions)
  39754. return true;
  39755. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39756. if (!data || data.length === 0) {
  39757. return false;
  39758. }
  39759. this._positions = [];
  39760. for (var index = 0; index < data.length; index += 3) {
  39761. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39762. }
  39763. return true;
  39764. };
  39765. /**
  39766. * Gets a value indicating if the geometry is disposed
  39767. * @returns true if the geometry was disposed
  39768. */
  39769. Geometry.prototype.isDisposed = function () {
  39770. return this._isDisposed;
  39771. };
  39772. Geometry.prototype._disposeVertexArrayObjects = function () {
  39773. if (this._vertexArrayObjects) {
  39774. for (var kind in this._vertexArrayObjects) {
  39775. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39776. }
  39777. this._vertexArrayObjects = {};
  39778. }
  39779. };
  39780. /**
  39781. * Free all associated resources
  39782. */
  39783. Geometry.prototype.dispose = function () {
  39784. var meshes = this._meshes;
  39785. var numOfMeshes = meshes.length;
  39786. var index;
  39787. for (index = 0; index < numOfMeshes; index++) {
  39788. this.releaseForMesh(meshes[index]);
  39789. }
  39790. this._meshes = [];
  39791. this._disposeVertexArrayObjects();
  39792. for (var kind in this._vertexBuffers) {
  39793. this._vertexBuffers[kind].dispose();
  39794. }
  39795. this._vertexBuffers = {};
  39796. this._totalVertices = 0;
  39797. if (this._indexBuffer) {
  39798. this._engine._releaseBuffer(this._indexBuffer);
  39799. }
  39800. this._indexBuffer = null;
  39801. this._indices = [];
  39802. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39803. this.delayLoadingFile = null;
  39804. this._delayLoadingFunction = null;
  39805. this._delayInfo = [];
  39806. this._boundingInfo = null;
  39807. this._scene.removeGeometry(this);
  39808. this._isDisposed = true;
  39809. };
  39810. /**
  39811. * Clone the current geometry into a new geometry
  39812. * @param id defines the unique ID of the new geometry
  39813. * @returns a new geometry object
  39814. */
  39815. Geometry.prototype.copy = function (id) {
  39816. var vertexData = new BABYLON.VertexData();
  39817. vertexData.indices = [];
  39818. var indices = this.getIndices();
  39819. if (indices) {
  39820. for (var index = 0; index < indices.length; index++) {
  39821. vertexData.indices.push(indices[index]);
  39822. }
  39823. }
  39824. var updatable = false;
  39825. var stopChecking = false;
  39826. var kind;
  39827. for (kind in this._vertexBuffers) {
  39828. // using slice() to make a copy of the array and not just reference it
  39829. var data = this.getVerticesData(kind);
  39830. if (data instanceof Float32Array) {
  39831. vertexData.set(new Float32Array(data), kind);
  39832. }
  39833. else {
  39834. vertexData.set(data.slice(0), kind);
  39835. }
  39836. if (!stopChecking) {
  39837. var vb = this.getVertexBuffer(kind);
  39838. if (vb) {
  39839. updatable = vb.isUpdatable();
  39840. stopChecking = !updatable;
  39841. }
  39842. }
  39843. }
  39844. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39845. geometry.delayLoadState = this.delayLoadState;
  39846. geometry.delayLoadingFile = this.delayLoadingFile;
  39847. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39848. for (kind in this._delayInfo) {
  39849. geometry._delayInfo = geometry._delayInfo || [];
  39850. geometry._delayInfo.push(kind);
  39851. }
  39852. // Bounding info
  39853. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39854. return geometry;
  39855. };
  39856. /**
  39857. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39858. * @return a JSON representation of the current geometry data (without the vertices data)
  39859. */
  39860. Geometry.prototype.serialize = function () {
  39861. var serializationObject = {};
  39862. serializationObject.id = this.id;
  39863. serializationObject.updatable = this._updatable;
  39864. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39865. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39866. }
  39867. return serializationObject;
  39868. };
  39869. Geometry.prototype.toNumberArray = function (origin) {
  39870. if (Array.isArray(origin)) {
  39871. return origin;
  39872. }
  39873. else {
  39874. return Array.prototype.slice.call(origin);
  39875. }
  39876. };
  39877. /**
  39878. * Serialize all vertices data into a JSON oject
  39879. * @returns a JSON representation of the current geometry data
  39880. */
  39881. Geometry.prototype.serializeVerticeData = function () {
  39882. var serializationObject = this.serialize();
  39883. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39884. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39885. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39886. serializationObject.positions._updatable = true;
  39887. }
  39888. }
  39889. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39890. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39891. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39892. serializationObject.normals._updatable = true;
  39893. }
  39894. }
  39895. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39896. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39897. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39898. serializationObject.tangets._updatable = true;
  39899. }
  39900. }
  39901. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39902. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39903. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39904. serializationObject.uvs._updatable = true;
  39905. }
  39906. }
  39907. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39908. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39909. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39910. serializationObject.uv2s._updatable = true;
  39911. }
  39912. }
  39913. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39914. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39915. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39916. serializationObject.uv3s._updatable = true;
  39917. }
  39918. }
  39919. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39920. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39921. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39922. serializationObject.uv4s._updatable = true;
  39923. }
  39924. }
  39925. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39926. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39927. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39928. serializationObject.uv5s._updatable = true;
  39929. }
  39930. }
  39931. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39932. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39933. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39934. serializationObject.uv6s._updatable = true;
  39935. }
  39936. }
  39937. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39938. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39939. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39940. serializationObject.colors._updatable = true;
  39941. }
  39942. }
  39943. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39944. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39945. serializationObject.matricesIndices._isExpanded = true;
  39946. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39947. serializationObject.matricesIndices._updatable = true;
  39948. }
  39949. }
  39950. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39951. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39952. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39953. serializationObject.matricesWeights._updatable = true;
  39954. }
  39955. }
  39956. serializationObject.indices = this.toNumberArray(this.getIndices());
  39957. return serializationObject;
  39958. };
  39959. // Statics
  39960. /**
  39961. * Extracts a clone of a mesh geometry
  39962. * @param mesh defines the source mesh
  39963. * @param id defines the unique ID of the new geometry object
  39964. * @returns the new geometry object
  39965. */
  39966. Geometry.ExtractFromMesh = function (mesh, id) {
  39967. var geometry = mesh._geometry;
  39968. if (!geometry) {
  39969. return null;
  39970. }
  39971. return geometry.copy(id);
  39972. };
  39973. /**
  39974. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39975. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39976. * Be aware Math.random() could cause collisions, but:
  39977. * "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"
  39978. * @returns a string containing a new GUID
  39979. */
  39980. Geometry.RandomId = function () {
  39981. return BABYLON.Tools.RandomId();
  39982. };
  39983. /** @hidden */
  39984. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39985. var scene = mesh.getScene();
  39986. // Geometry
  39987. var geometryId = parsedGeometry.geometryId;
  39988. if (geometryId) {
  39989. var geometry = scene.getGeometryByID(geometryId);
  39990. if (geometry) {
  39991. geometry.applyToMesh(mesh);
  39992. }
  39993. }
  39994. else if (parsedGeometry instanceof ArrayBuffer) {
  39995. var binaryInfo = mesh._binaryInfo;
  39996. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39997. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39998. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39999. }
  40000. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40001. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40002. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40003. }
  40004. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40005. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40006. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40007. }
  40008. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40009. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40010. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40011. }
  40012. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40013. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40014. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40015. }
  40016. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40017. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40018. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40019. }
  40020. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40021. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40022. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40023. }
  40024. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40025. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40026. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40027. }
  40028. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40029. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40030. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40031. }
  40032. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40033. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40034. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40035. }
  40036. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40037. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40038. var floatIndices = [];
  40039. for (var i = 0; i < matricesIndicesData.length; i++) {
  40040. var index = matricesIndicesData[i];
  40041. floatIndices.push(index & 0x000000FF);
  40042. floatIndices.push((index & 0x0000FF00) >> 8);
  40043. floatIndices.push((index & 0x00FF0000) >> 16);
  40044. floatIndices.push(index >> 24);
  40045. }
  40046. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  40047. }
  40048. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40049. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40050. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40051. }
  40052. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40053. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40054. mesh.setIndices(indicesData, null);
  40055. }
  40056. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40057. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40058. mesh.subMeshes = [];
  40059. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40060. var materialIndex = subMeshesData[(i * 5) + 0];
  40061. var verticesStart = subMeshesData[(i * 5) + 1];
  40062. var verticesCount = subMeshesData[(i * 5) + 2];
  40063. var indexStart = subMeshesData[(i * 5) + 3];
  40064. var indexCount = subMeshesData[(i * 5) + 4];
  40065. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40066. }
  40067. }
  40068. }
  40069. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40070. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40071. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40072. if (parsedGeometry.tangents) {
  40073. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40074. }
  40075. if (parsedGeometry.uvs) {
  40076. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40077. }
  40078. if (parsedGeometry.uvs2) {
  40079. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40080. }
  40081. if (parsedGeometry.uvs3) {
  40082. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40083. }
  40084. if (parsedGeometry.uvs4) {
  40085. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40086. }
  40087. if (parsedGeometry.uvs5) {
  40088. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40089. }
  40090. if (parsedGeometry.uvs6) {
  40091. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40092. }
  40093. if (parsedGeometry.colors) {
  40094. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40095. }
  40096. if (parsedGeometry.matricesIndices) {
  40097. if (!parsedGeometry.matricesIndices._isExpanded) {
  40098. var floatIndices = [];
  40099. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40100. var matricesIndex = parsedGeometry.matricesIndices[i];
  40101. floatIndices.push(matricesIndex & 0x000000FF);
  40102. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40103. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40104. floatIndices.push(matricesIndex >> 24);
  40105. }
  40106. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40107. }
  40108. else {
  40109. delete parsedGeometry.matricesIndices._isExpanded;
  40110. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40111. }
  40112. }
  40113. if (parsedGeometry.matricesIndicesExtra) {
  40114. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40115. var floatIndices = [];
  40116. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40117. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40118. floatIndices.push(matricesIndex & 0x000000FF);
  40119. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40120. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40121. floatIndices.push(matricesIndex >> 24);
  40122. }
  40123. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40124. }
  40125. else {
  40126. delete parsedGeometry.matricesIndices._isExpanded;
  40127. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40128. }
  40129. }
  40130. if (parsedGeometry.matricesWeights) {
  40131. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40132. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40133. }
  40134. if (parsedGeometry.matricesWeightsExtra) {
  40135. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40136. }
  40137. mesh.setIndices(parsedGeometry.indices, null);
  40138. }
  40139. // SubMeshes
  40140. if (parsedGeometry.subMeshes) {
  40141. mesh.subMeshes = [];
  40142. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40143. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40144. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40145. }
  40146. }
  40147. // Flat shading
  40148. if (mesh._shouldGenerateFlatShading) {
  40149. mesh.convertToFlatShadedMesh();
  40150. delete mesh._shouldGenerateFlatShading;
  40151. }
  40152. // Update
  40153. mesh.computeWorldMatrix(true);
  40154. // Octree
  40155. var sceneOctree = scene.selectionOctree;
  40156. if (sceneOctree !== undefined && sceneOctree !== null) {
  40157. sceneOctree.addMesh(mesh);
  40158. }
  40159. };
  40160. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40161. var epsilon = 1e-3;
  40162. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40163. return;
  40164. }
  40165. var noInfluenceBoneIndex = 0.0;
  40166. if (parsedGeometry.skeletonId > -1) {
  40167. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40168. if (!skeleton) {
  40169. return;
  40170. }
  40171. noInfluenceBoneIndex = skeleton.bones.length;
  40172. }
  40173. else {
  40174. return;
  40175. }
  40176. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40177. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40178. var matricesWeights = parsedGeometry.matricesWeights;
  40179. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40180. var influencers = parsedGeometry.numBoneInfluencer;
  40181. var size = matricesWeights.length;
  40182. for (var i = 0; i < size; i += 4) {
  40183. var weight = 0.0;
  40184. var firstZeroWeight = -1;
  40185. for (var j = 0; j < 4; j++) {
  40186. var w = matricesWeights[i + j];
  40187. weight += w;
  40188. if (w < epsilon && firstZeroWeight < 0) {
  40189. firstZeroWeight = j;
  40190. }
  40191. }
  40192. if (matricesWeightsExtra) {
  40193. for (var j = 0; j < 4; j++) {
  40194. var w = matricesWeightsExtra[i + j];
  40195. weight += w;
  40196. if (w < epsilon && firstZeroWeight < 0) {
  40197. firstZeroWeight = j + 4;
  40198. }
  40199. }
  40200. }
  40201. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40202. firstZeroWeight = influencers - 1;
  40203. }
  40204. if (weight > epsilon) {
  40205. var mweight = 1.0 / weight;
  40206. for (var j = 0; j < 4; j++) {
  40207. matricesWeights[i + j] *= mweight;
  40208. }
  40209. if (matricesWeightsExtra) {
  40210. for (var j = 0; j < 4; j++) {
  40211. matricesWeightsExtra[i + j] *= mweight;
  40212. }
  40213. }
  40214. }
  40215. else {
  40216. if (firstZeroWeight >= 4) {
  40217. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40218. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40219. }
  40220. else {
  40221. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40222. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40223. }
  40224. }
  40225. }
  40226. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40227. if (parsedGeometry.matricesWeightsExtra) {
  40228. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40229. }
  40230. };
  40231. /**
  40232. * Create a new geometry from persisted data (Using .babylon file format)
  40233. * @param parsedVertexData defines the persisted data
  40234. * @param scene defines the hosting scene
  40235. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40236. * @returns the new geometry object
  40237. */
  40238. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40239. if (scene.getGeometryByID(parsedVertexData.id)) {
  40240. return null; // null since geometry could be something else than a box...
  40241. }
  40242. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40243. if (BABYLON.Tags) {
  40244. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40245. }
  40246. if (parsedVertexData.delayLoadingFile) {
  40247. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40248. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40249. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40250. geometry._delayInfo = [];
  40251. if (parsedVertexData.hasUVs) {
  40252. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40253. }
  40254. if (parsedVertexData.hasUVs2) {
  40255. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40256. }
  40257. if (parsedVertexData.hasUVs3) {
  40258. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40259. }
  40260. if (parsedVertexData.hasUVs4) {
  40261. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40262. }
  40263. if (parsedVertexData.hasUVs5) {
  40264. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40265. }
  40266. if (parsedVertexData.hasUVs6) {
  40267. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40268. }
  40269. if (parsedVertexData.hasColors) {
  40270. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40271. }
  40272. if (parsedVertexData.hasMatricesIndices) {
  40273. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40274. }
  40275. if (parsedVertexData.hasMatricesWeights) {
  40276. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40277. }
  40278. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40279. }
  40280. else {
  40281. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40282. }
  40283. scene.pushGeometry(geometry, true);
  40284. return geometry;
  40285. };
  40286. return Geometry;
  40287. }());
  40288. BABYLON.Geometry = Geometry;
  40289. // Primitives
  40290. /// Abstract class
  40291. /**
  40292. * Abstract class used to provide common services for all typed geometries
  40293. * @hidden
  40294. */
  40295. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40296. __extends(_PrimitiveGeometry, _super);
  40297. /**
  40298. * Creates a new typed geometry
  40299. * @param id defines the unique ID of the geometry
  40300. * @param scene defines the hosting scene
  40301. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40302. * @param mesh defines the hosting mesh (can be null)
  40303. */
  40304. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40305. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40306. if (mesh === void 0) { mesh = null; }
  40307. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40308. _this._canBeRegenerated = _canBeRegenerated;
  40309. _this._beingRegenerated = true;
  40310. _this.regenerate();
  40311. _this._beingRegenerated = false;
  40312. return _this;
  40313. }
  40314. /**
  40315. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40316. * @returns true if the geometry can be regenerated
  40317. */
  40318. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40319. return this._canBeRegenerated;
  40320. };
  40321. /**
  40322. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40323. */
  40324. _PrimitiveGeometry.prototype.regenerate = function () {
  40325. if (!this._canBeRegenerated) {
  40326. return;
  40327. }
  40328. this._beingRegenerated = true;
  40329. this.setAllVerticesData(this._regenerateVertexData(), false);
  40330. this._beingRegenerated = false;
  40331. };
  40332. /**
  40333. * Clone the geometry
  40334. * @param id defines the unique ID of the new geometry
  40335. * @returns the new geometry
  40336. */
  40337. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40338. return _super.prototype.copy.call(this, id);
  40339. };
  40340. // overrides
  40341. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40342. if (!this._beingRegenerated) {
  40343. return;
  40344. }
  40345. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40346. };
  40347. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40348. if (!this._beingRegenerated) {
  40349. return;
  40350. }
  40351. _super.prototype.setVerticesData.call(this, kind, data, false);
  40352. };
  40353. // to override
  40354. /** @hidden */
  40355. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40356. throw new Error("Abstract method");
  40357. };
  40358. _PrimitiveGeometry.prototype.copy = function (id) {
  40359. throw new Error("Must be overriden in sub-classes.");
  40360. };
  40361. _PrimitiveGeometry.prototype.serialize = function () {
  40362. var serializationObject = _super.prototype.serialize.call(this);
  40363. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40364. return serializationObject;
  40365. };
  40366. return _PrimitiveGeometry;
  40367. }(Geometry));
  40368. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40369. /**
  40370. * Creates a ribbon geometry
  40371. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40372. */
  40373. var RibbonGeometry = /** @class */ (function (_super) {
  40374. __extends(RibbonGeometry, _super);
  40375. /**
  40376. * Creates a ribbon geometry
  40377. * @param id defines the unique ID of the geometry
  40378. * @param scene defines the hosting scene
  40379. * @param pathArray defines the array of paths to use
  40380. * @param closeArray defines if the last path and the first path must be joined
  40381. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40382. * @param offset defines the offset between points
  40383. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40384. * @param mesh defines the hosting mesh (can be null)
  40385. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40386. */
  40387. function RibbonGeometry(id, scene,
  40388. /**
  40389. * Defines the array of paths to use
  40390. */
  40391. pathArray,
  40392. /**
  40393. * Defines if the last and first points of each path in your pathArray must be joined
  40394. */
  40395. closeArray,
  40396. /**
  40397. * Defines if the last and first points of each path in your pathArray must be joined
  40398. */
  40399. closePath,
  40400. /**
  40401. * Defines the offset between points
  40402. */
  40403. offset, canBeRegenerated, mesh,
  40404. /**
  40405. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40406. */
  40407. side) {
  40408. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40409. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40410. _this.pathArray = pathArray;
  40411. _this.closeArray = closeArray;
  40412. _this.closePath = closePath;
  40413. _this.offset = offset;
  40414. _this.side = side;
  40415. return _this;
  40416. }
  40417. /** @hidden */
  40418. RibbonGeometry.prototype._regenerateVertexData = function () {
  40419. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40420. };
  40421. RibbonGeometry.prototype.copy = function (id) {
  40422. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40423. };
  40424. return RibbonGeometry;
  40425. }(_PrimitiveGeometry));
  40426. BABYLON.RibbonGeometry = RibbonGeometry;
  40427. /**
  40428. * Creates a box geometry
  40429. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40430. */
  40431. var BoxGeometry = /** @class */ (function (_super) {
  40432. __extends(BoxGeometry, _super);
  40433. /**
  40434. * Creates a box geometry
  40435. * @param id defines the unique ID of the geometry
  40436. * @param scene defines the hosting scene
  40437. * @param size defines the zise of the box (width, height and depth are the same)
  40438. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40439. * @param mesh defines the hosting mesh (can be null)
  40440. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40441. */
  40442. function BoxGeometry(id, scene,
  40443. /**
  40444. * Defines the zise of the box (width, height and depth are the same)
  40445. */
  40446. size, canBeRegenerated, mesh,
  40447. /**
  40448. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40449. */
  40450. side) {
  40451. if (mesh === void 0) { mesh = null; }
  40452. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40453. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40454. _this.size = size;
  40455. _this.side = side;
  40456. return _this;
  40457. }
  40458. BoxGeometry.prototype._regenerateVertexData = function () {
  40459. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40460. };
  40461. BoxGeometry.prototype.copy = function (id) {
  40462. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40463. };
  40464. BoxGeometry.prototype.serialize = function () {
  40465. var serializationObject = _super.prototype.serialize.call(this);
  40466. serializationObject.size = this.size;
  40467. return serializationObject;
  40468. };
  40469. BoxGeometry.Parse = function (parsedBox, scene) {
  40470. if (scene.getGeometryByID(parsedBox.id)) {
  40471. return null; // null since geometry could be something else than a box...
  40472. }
  40473. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40474. if (BABYLON.Tags) {
  40475. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40476. }
  40477. scene.pushGeometry(box, true);
  40478. return box;
  40479. };
  40480. return BoxGeometry;
  40481. }(_PrimitiveGeometry));
  40482. BABYLON.BoxGeometry = BoxGeometry;
  40483. /**
  40484. * Creates a sphere geometry
  40485. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40486. */
  40487. var SphereGeometry = /** @class */ (function (_super) {
  40488. __extends(SphereGeometry, _super);
  40489. /**
  40490. * Create a new sphere geometry
  40491. * @param id defines the unique ID of the geometry
  40492. * @param scene defines the hosting scene
  40493. * @param segments defines the number of segments to use to create the sphere
  40494. * @param diameter defines the diameter of the sphere
  40495. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40496. * @param mesh defines the hosting mesh (can be null)
  40497. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40498. */
  40499. function SphereGeometry(id, scene,
  40500. /**
  40501. * Defines the number of segments to use to create the sphere
  40502. */
  40503. segments,
  40504. /**
  40505. * Defines the diameter of the sphere
  40506. */
  40507. diameter, canBeRegenerated, mesh,
  40508. /**
  40509. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40510. */
  40511. side) {
  40512. if (mesh === void 0) { mesh = null; }
  40513. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40514. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40515. _this.segments = segments;
  40516. _this.diameter = diameter;
  40517. _this.side = side;
  40518. return _this;
  40519. }
  40520. SphereGeometry.prototype._regenerateVertexData = function () {
  40521. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40522. };
  40523. SphereGeometry.prototype.copy = function (id) {
  40524. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40525. };
  40526. SphereGeometry.prototype.serialize = function () {
  40527. var serializationObject = _super.prototype.serialize.call(this);
  40528. serializationObject.segments = this.segments;
  40529. serializationObject.diameter = this.diameter;
  40530. return serializationObject;
  40531. };
  40532. SphereGeometry.Parse = function (parsedSphere, scene) {
  40533. if (scene.getGeometryByID(parsedSphere.id)) {
  40534. return null; // null since geometry could be something else than a sphere...
  40535. }
  40536. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40537. if (BABYLON.Tags) {
  40538. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40539. }
  40540. scene.pushGeometry(sphere, true);
  40541. return sphere;
  40542. };
  40543. return SphereGeometry;
  40544. }(_PrimitiveGeometry));
  40545. BABYLON.SphereGeometry = SphereGeometry;
  40546. /**
  40547. * Creates a disc geometry
  40548. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40549. */
  40550. var DiscGeometry = /** @class */ (function (_super) {
  40551. __extends(DiscGeometry, _super);
  40552. /**
  40553. * Creates a new disc geometry
  40554. * @param id defines the unique ID of the geometry
  40555. * @param scene defines the hosting scene
  40556. * @param radius defines the radius of the disc
  40557. * @param tessellation defines the tesselation factor to apply to the disc
  40558. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40559. * @param mesh defines the hosting mesh (can be null)
  40560. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40561. */
  40562. function DiscGeometry(id, scene,
  40563. /**
  40564. * Defines the radius of the disc
  40565. */
  40566. radius,
  40567. /**
  40568. * Defines the tesselation factor to apply to the disc
  40569. */
  40570. tessellation, canBeRegenerated, mesh,
  40571. /**
  40572. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40573. */
  40574. side) {
  40575. if (mesh === void 0) { mesh = null; }
  40576. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40577. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40578. _this.radius = radius;
  40579. _this.tessellation = tessellation;
  40580. _this.side = side;
  40581. return _this;
  40582. }
  40583. DiscGeometry.prototype._regenerateVertexData = function () {
  40584. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40585. };
  40586. DiscGeometry.prototype.copy = function (id) {
  40587. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40588. };
  40589. return DiscGeometry;
  40590. }(_PrimitiveGeometry));
  40591. BABYLON.DiscGeometry = DiscGeometry;
  40592. /**
  40593. * Creates a new cylinder geometry
  40594. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40595. */
  40596. var CylinderGeometry = /** @class */ (function (_super) {
  40597. __extends(CylinderGeometry, _super);
  40598. /**
  40599. * Creates a new cylinder geometry
  40600. * @param id defines the unique ID of the geometry
  40601. * @param scene defines the hosting scene
  40602. * @param height defines the height of the cylinder
  40603. * @param diameterTop defines the diameter of the cylinder's top cap
  40604. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40605. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40606. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40607. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40608. * @param mesh defines the hosting mesh (can be null)
  40609. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40610. */
  40611. function CylinderGeometry(id, scene,
  40612. /**
  40613. * Defines the height of the cylinder
  40614. */
  40615. height,
  40616. /**
  40617. * Defines the diameter of the cylinder's top cap
  40618. */
  40619. diameterTop,
  40620. /**
  40621. * Defines the diameter of the cylinder's bottom cap
  40622. */
  40623. diameterBottom,
  40624. /**
  40625. * Defines the tessellation factor to apply to the cylinder
  40626. */
  40627. tessellation,
  40628. /**
  40629. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40630. */
  40631. subdivisions, canBeRegenerated, mesh,
  40632. /**
  40633. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40634. */
  40635. side) {
  40636. if (subdivisions === void 0) { subdivisions = 1; }
  40637. if (mesh === void 0) { mesh = null; }
  40638. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40639. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40640. _this.height = height;
  40641. _this.diameterTop = diameterTop;
  40642. _this.diameterBottom = diameterBottom;
  40643. _this.tessellation = tessellation;
  40644. _this.subdivisions = subdivisions;
  40645. _this.side = side;
  40646. return _this;
  40647. }
  40648. CylinderGeometry.prototype._regenerateVertexData = function () {
  40649. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40650. };
  40651. CylinderGeometry.prototype.copy = function (id) {
  40652. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40653. };
  40654. CylinderGeometry.prototype.serialize = function () {
  40655. var serializationObject = _super.prototype.serialize.call(this);
  40656. serializationObject.height = this.height;
  40657. serializationObject.diameterTop = this.diameterTop;
  40658. serializationObject.diameterBottom = this.diameterBottom;
  40659. serializationObject.tessellation = this.tessellation;
  40660. return serializationObject;
  40661. };
  40662. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40663. if (scene.getGeometryByID(parsedCylinder.id)) {
  40664. return null; // null since geometry could be something else than a cylinder...
  40665. }
  40666. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40667. if (BABYLON.Tags) {
  40668. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40669. }
  40670. scene.pushGeometry(cylinder, true);
  40671. return cylinder;
  40672. };
  40673. return CylinderGeometry;
  40674. }(_PrimitiveGeometry));
  40675. BABYLON.CylinderGeometry = CylinderGeometry;
  40676. /**
  40677. * Creates a new torus geometry
  40678. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40679. */
  40680. var TorusGeometry = /** @class */ (function (_super) {
  40681. __extends(TorusGeometry, _super);
  40682. /**
  40683. * Creates a new torus geometry
  40684. * @param id defines the unique ID of the geometry
  40685. * @param scene defines the hosting scene
  40686. * @param diameter defines the diameter of the torus
  40687. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40688. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40689. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40690. * @param mesh defines the hosting mesh (can be null)
  40691. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40692. */
  40693. function TorusGeometry(id, scene,
  40694. /**
  40695. * Defines the diameter of the torus
  40696. */
  40697. diameter,
  40698. /**
  40699. * Defines the thickness of the torus (ie. internal diameter)
  40700. */
  40701. thickness,
  40702. /**
  40703. * Defines the tesselation factor to apply to the torus
  40704. */
  40705. tessellation, canBeRegenerated, mesh,
  40706. /**
  40707. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40708. */
  40709. side) {
  40710. if (mesh === void 0) { mesh = null; }
  40711. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40712. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40713. _this.diameter = diameter;
  40714. _this.thickness = thickness;
  40715. _this.tessellation = tessellation;
  40716. _this.side = side;
  40717. return _this;
  40718. }
  40719. TorusGeometry.prototype._regenerateVertexData = function () {
  40720. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40721. };
  40722. TorusGeometry.prototype.copy = function (id) {
  40723. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40724. };
  40725. TorusGeometry.prototype.serialize = function () {
  40726. var serializationObject = _super.prototype.serialize.call(this);
  40727. serializationObject.diameter = this.diameter;
  40728. serializationObject.thickness = this.thickness;
  40729. serializationObject.tessellation = this.tessellation;
  40730. return serializationObject;
  40731. };
  40732. TorusGeometry.Parse = function (parsedTorus, scene) {
  40733. if (scene.getGeometryByID(parsedTorus.id)) {
  40734. return null; // null since geometry could be something else than a torus...
  40735. }
  40736. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40737. if (BABYLON.Tags) {
  40738. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40739. }
  40740. scene.pushGeometry(torus, true);
  40741. return torus;
  40742. };
  40743. return TorusGeometry;
  40744. }(_PrimitiveGeometry));
  40745. BABYLON.TorusGeometry = TorusGeometry;
  40746. /**
  40747. * Creates a new ground geometry
  40748. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40749. */
  40750. var GroundGeometry = /** @class */ (function (_super) {
  40751. __extends(GroundGeometry, _super);
  40752. /**
  40753. * Creates a new ground geometry
  40754. * @param id defines the unique ID of the geometry
  40755. * @param scene defines the hosting scene
  40756. * @param width defines the width of the ground
  40757. * @param height defines the height of the ground
  40758. * @param subdivisions defines the subdivisions to apply to the ground
  40759. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40760. * @param mesh defines the hosting mesh (can be null)
  40761. */
  40762. function GroundGeometry(id, scene,
  40763. /**
  40764. * Defines the width of the ground
  40765. */
  40766. width,
  40767. /**
  40768. * Defines the height of the ground
  40769. */
  40770. height,
  40771. /**
  40772. * Defines the subdivisions to apply to the ground
  40773. */
  40774. subdivisions, canBeRegenerated, mesh) {
  40775. if (mesh === void 0) { mesh = null; }
  40776. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40777. _this.width = width;
  40778. _this.height = height;
  40779. _this.subdivisions = subdivisions;
  40780. return _this;
  40781. }
  40782. GroundGeometry.prototype._regenerateVertexData = function () {
  40783. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40784. };
  40785. GroundGeometry.prototype.copy = function (id) {
  40786. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40787. };
  40788. GroundGeometry.prototype.serialize = function () {
  40789. var serializationObject = _super.prototype.serialize.call(this);
  40790. serializationObject.width = this.width;
  40791. serializationObject.height = this.height;
  40792. serializationObject.subdivisions = this.subdivisions;
  40793. return serializationObject;
  40794. };
  40795. GroundGeometry.Parse = function (parsedGround, scene) {
  40796. if (scene.getGeometryByID(parsedGround.id)) {
  40797. return null; // null since geometry could be something else than a ground...
  40798. }
  40799. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40800. if (BABYLON.Tags) {
  40801. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40802. }
  40803. scene.pushGeometry(ground, true);
  40804. return ground;
  40805. };
  40806. return GroundGeometry;
  40807. }(_PrimitiveGeometry));
  40808. BABYLON.GroundGeometry = GroundGeometry;
  40809. /**
  40810. * Creates a tiled ground geometry
  40811. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40812. */
  40813. var TiledGroundGeometry = /** @class */ (function (_super) {
  40814. __extends(TiledGroundGeometry, _super);
  40815. /**
  40816. * Creates a tiled ground geometry
  40817. * @param id defines the unique ID of the geometry
  40818. * @param scene defines the hosting scene
  40819. * @param xmin defines the minimum value on X axis
  40820. * @param zmin defines the minimum value on Z axis
  40821. * @param xmax defines the maximum value on X axis
  40822. * @param zmax defines the maximum value on Z axis
  40823. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40824. * @param precision defines the precision to use when computing the tiles
  40825. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40826. * @param mesh defines the hosting mesh (can be null)
  40827. */
  40828. function TiledGroundGeometry(id, scene,
  40829. /**
  40830. * Defines the minimum value on X axis
  40831. */
  40832. xmin,
  40833. /**
  40834. * Defines the minimum value on Z axis
  40835. */
  40836. zmin,
  40837. /**
  40838. * Defines the maximum value on X axis
  40839. */
  40840. xmax,
  40841. /**
  40842. * Defines the maximum value on Z axis
  40843. */
  40844. zmax,
  40845. /**
  40846. * Defines the subdivisions to apply to the ground
  40847. */
  40848. subdivisions,
  40849. /**
  40850. * Defines the precision to use when computing the tiles
  40851. */
  40852. precision, canBeRegenerated, mesh) {
  40853. if (mesh === void 0) { mesh = null; }
  40854. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40855. _this.xmin = xmin;
  40856. _this.zmin = zmin;
  40857. _this.xmax = xmax;
  40858. _this.zmax = zmax;
  40859. _this.subdivisions = subdivisions;
  40860. _this.precision = precision;
  40861. return _this;
  40862. }
  40863. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40864. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40865. };
  40866. TiledGroundGeometry.prototype.copy = function (id) {
  40867. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40868. };
  40869. return TiledGroundGeometry;
  40870. }(_PrimitiveGeometry));
  40871. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40872. /**
  40873. * Creates a plane geometry
  40874. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40875. */
  40876. var PlaneGeometry = /** @class */ (function (_super) {
  40877. __extends(PlaneGeometry, _super);
  40878. /**
  40879. * Creates a plane geometry
  40880. * @param id defines the unique ID of the geometry
  40881. * @param scene defines the hosting scene
  40882. * @param size defines the size of the plane (width === height)
  40883. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40884. * @param mesh defines the hosting mesh (can be null)
  40885. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40886. */
  40887. function PlaneGeometry(id, scene,
  40888. /**
  40889. * Defines the size of the plane (width === height)
  40890. */
  40891. size, canBeRegenerated, mesh,
  40892. /**
  40893. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40894. */
  40895. side) {
  40896. if (mesh === void 0) { mesh = null; }
  40897. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40898. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40899. _this.size = size;
  40900. _this.side = side;
  40901. return _this;
  40902. }
  40903. PlaneGeometry.prototype._regenerateVertexData = function () {
  40904. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40905. };
  40906. PlaneGeometry.prototype.copy = function (id) {
  40907. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40908. };
  40909. PlaneGeometry.prototype.serialize = function () {
  40910. var serializationObject = _super.prototype.serialize.call(this);
  40911. serializationObject.size = this.size;
  40912. return serializationObject;
  40913. };
  40914. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40915. if (scene.getGeometryByID(parsedPlane.id)) {
  40916. return null; // null since geometry could be something else than a ground...
  40917. }
  40918. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40919. if (BABYLON.Tags) {
  40920. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40921. }
  40922. scene.pushGeometry(plane, true);
  40923. return plane;
  40924. };
  40925. return PlaneGeometry;
  40926. }(_PrimitiveGeometry));
  40927. BABYLON.PlaneGeometry = PlaneGeometry;
  40928. /**
  40929. * Creates a torus knot geometry
  40930. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40931. */
  40932. var TorusKnotGeometry = /** @class */ (function (_super) {
  40933. __extends(TorusKnotGeometry, _super);
  40934. /**
  40935. * Creates a torus knot geometry
  40936. * @param id defines the unique ID of the geometry
  40937. * @param scene defines the hosting scene
  40938. * @param radius defines the radius of the torus knot
  40939. * @param tube defines the thickness of the torus knot tube
  40940. * @param radialSegments defines the number of radial segments
  40941. * @param tubularSegments defines the number of tubular segments
  40942. * @param p defines the first number of windings
  40943. * @param q defines the second number of windings
  40944. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40945. * @param mesh defines the hosting mesh (can be null)
  40946. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40947. */
  40948. function TorusKnotGeometry(id, scene,
  40949. /**
  40950. * Defines the radius of the torus knot
  40951. */
  40952. radius,
  40953. /**
  40954. * Defines the thickness of the torus knot tube
  40955. */
  40956. tube,
  40957. /**
  40958. * Defines the number of radial segments
  40959. */
  40960. radialSegments,
  40961. /**
  40962. * Defines the number of tubular segments
  40963. */
  40964. tubularSegments,
  40965. /**
  40966. * Defines the first number of windings
  40967. */
  40968. p,
  40969. /**
  40970. * Defines the second number of windings
  40971. */
  40972. q, canBeRegenerated, mesh,
  40973. /**
  40974. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40975. */
  40976. side) {
  40977. if (mesh === void 0) { mesh = null; }
  40978. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40979. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40980. _this.radius = radius;
  40981. _this.tube = tube;
  40982. _this.radialSegments = radialSegments;
  40983. _this.tubularSegments = tubularSegments;
  40984. _this.p = p;
  40985. _this.q = q;
  40986. _this.side = side;
  40987. return _this;
  40988. }
  40989. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40990. 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 });
  40991. };
  40992. TorusKnotGeometry.prototype.copy = function (id) {
  40993. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40994. };
  40995. TorusKnotGeometry.prototype.serialize = function () {
  40996. var serializationObject = _super.prototype.serialize.call(this);
  40997. serializationObject.radius = this.radius;
  40998. serializationObject.tube = this.tube;
  40999. serializationObject.radialSegments = this.radialSegments;
  41000. serializationObject.tubularSegments = this.tubularSegments;
  41001. serializationObject.p = this.p;
  41002. serializationObject.q = this.q;
  41003. return serializationObject;
  41004. };
  41005. ;
  41006. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41007. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41008. return null; // null since geometry could be something else than a ground...
  41009. }
  41010. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41011. if (BABYLON.Tags) {
  41012. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41013. }
  41014. scene.pushGeometry(torusKnot, true);
  41015. return torusKnot;
  41016. };
  41017. return TorusKnotGeometry;
  41018. }(_PrimitiveGeometry));
  41019. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41020. //}
  41021. })(BABYLON || (BABYLON = {}));
  41022. //# sourceMappingURL=babylon.geometry.js.map
  41023. var BABYLON;
  41024. (function (BABYLON) {
  41025. /**
  41026. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41027. */
  41028. var PerformanceMonitor = /** @class */ (function () {
  41029. /**
  41030. * constructor
  41031. * @param frameSampleSize The number of samples required to saturate the sliding window
  41032. */
  41033. function PerformanceMonitor(frameSampleSize) {
  41034. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41035. this._enabled = true;
  41036. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41037. }
  41038. /**
  41039. * Samples current frame
  41040. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41041. */
  41042. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41043. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41044. if (!this._enabled)
  41045. return;
  41046. if (this._lastFrameTimeMs != null) {
  41047. var dt = timeMs - this._lastFrameTimeMs;
  41048. this._rollingFrameTime.add(dt);
  41049. }
  41050. this._lastFrameTimeMs = timeMs;
  41051. };
  41052. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41053. /**
  41054. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41055. * @return Average frame time in milliseconds
  41056. */
  41057. get: function () {
  41058. return this._rollingFrameTime.average;
  41059. },
  41060. enumerable: true,
  41061. configurable: true
  41062. });
  41063. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41064. /**
  41065. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41066. * @return Frame time variance in milliseconds squared
  41067. */
  41068. get: function () {
  41069. return this._rollingFrameTime.variance;
  41070. },
  41071. enumerable: true,
  41072. configurable: true
  41073. });
  41074. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41075. /**
  41076. * Returns the frame time of the most recent frame
  41077. * @return Frame time in milliseconds
  41078. */
  41079. get: function () {
  41080. return this._rollingFrameTime.history(0);
  41081. },
  41082. enumerable: true,
  41083. configurable: true
  41084. });
  41085. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41086. /**
  41087. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41088. * @return Framerate in frames per second
  41089. */
  41090. get: function () {
  41091. return 1000.0 / this._rollingFrameTime.average;
  41092. },
  41093. enumerable: true,
  41094. configurable: true
  41095. });
  41096. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41097. /**
  41098. * Returns the average framerate in frames per second using the most recent frame time
  41099. * @return Framerate in frames per second
  41100. */
  41101. get: function () {
  41102. var history = this._rollingFrameTime.history(0);
  41103. if (history === 0) {
  41104. return 0;
  41105. }
  41106. return 1000.0 / history;
  41107. },
  41108. enumerable: true,
  41109. configurable: true
  41110. });
  41111. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41112. /**
  41113. * Returns true if enough samples have been taken to completely fill the sliding window
  41114. * @return true if saturated
  41115. */
  41116. get: function () {
  41117. return this._rollingFrameTime.isSaturated();
  41118. },
  41119. enumerable: true,
  41120. configurable: true
  41121. });
  41122. /**
  41123. * Enables contributions to the sliding window sample set
  41124. */
  41125. PerformanceMonitor.prototype.enable = function () {
  41126. this._enabled = true;
  41127. };
  41128. /**
  41129. * Disables contributions to the sliding window sample set
  41130. * Samples will not be interpolated over the disabled period
  41131. */
  41132. PerformanceMonitor.prototype.disable = function () {
  41133. this._enabled = false;
  41134. //clear last sample to avoid interpolating over the disabled period when next enabled
  41135. this._lastFrameTimeMs = null;
  41136. };
  41137. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41138. /**
  41139. * Returns true if sampling is enabled
  41140. * @return true if enabled
  41141. */
  41142. get: function () {
  41143. return this._enabled;
  41144. },
  41145. enumerable: true,
  41146. configurable: true
  41147. });
  41148. /**
  41149. * Resets performance monitor
  41150. */
  41151. PerformanceMonitor.prototype.reset = function () {
  41152. //clear last sample to avoid interpolating over the disabled period when next enabled
  41153. this._lastFrameTimeMs = null;
  41154. //wipe record
  41155. this._rollingFrameTime.reset();
  41156. };
  41157. return PerformanceMonitor;
  41158. }());
  41159. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41160. /**
  41161. * RollingAverage
  41162. *
  41163. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41164. */
  41165. var RollingAverage = /** @class */ (function () {
  41166. /**
  41167. * constructor
  41168. * @param length The number of samples required to saturate the sliding window
  41169. */
  41170. function RollingAverage(length) {
  41171. this._samples = new Array(length);
  41172. this.reset();
  41173. }
  41174. /**
  41175. * Adds a sample to the sample set
  41176. * @param v The sample value
  41177. */
  41178. RollingAverage.prototype.add = function (v) {
  41179. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41180. var delta;
  41181. //we need to check if we've already wrapped round
  41182. if (this.isSaturated()) {
  41183. //remove bottom of stack from mean
  41184. var bottomValue = this._samples[this._pos];
  41185. delta = bottomValue - this.average;
  41186. this.average -= delta / (this._sampleCount - 1);
  41187. this._m2 -= delta * (bottomValue - this.average);
  41188. }
  41189. else {
  41190. this._sampleCount++;
  41191. }
  41192. //add new value to mean
  41193. delta = v - this.average;
  41194. this.average += delta / (this._sampleCount);
  41195. this._m2 += delta * (v - this.average);
  41196. //set the new variance
  41197. this.variance = this._m2 / (this._sampleCount - 1);
  41198. this._samples[this._pos] = v;
  41199. this._pos++;
  41200. this._pos %= this._samples.length; //positive wrap around
  41201. };
  41202. /**
  41203. * Returns previously added values or null if outside of history or outside the sliding window domain
  41204. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41205. * @return Value previously recorded with add() or null if outside of range
  41206. */
  41207. RollingAverage.prototype.history = function (i) {
  41208. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41209. return 0;
  41210. }
  41211. var i0 = this._wrapPosition(this._pos - 1.0);
  41212. return this._samples[this._wrapPosition(i0 - i)];
  41213. };
  41214. /**
  41215. * Returns true if enough samples have been taken to completely fill the sliding window
  41216. * @return true if sample-set saturated
  41217. */
  41218. RollingAverage.prototype.isSaturated = function () {
  41219. return this._sampleCount >= this._samples.length;
  41220. };
  41221. /**
  41222. * Resets the rolling average (equivalent to 0 samples taken so far)
  41223. */
  41224. RollingAverage.prototype.reset = function () {
  41225. this.average = 0;
  41226. this.variance = 0;
  41227. this._sampleCount = 0;
  41228. this._pos = 0;
  41229. this._m2 = 0;
  41230. };
  41231. /**
  41232. * Wraps a value around the sample range boundaries
  41233. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41234. * @return Wrapped position in sample range
  41235. */
  41236. RollingAverage.prototype._wrapPosition = function (i) {
  41237. var max = this._samples.length;
  41238. return ((i % max) + max) % max;
  41239. };
  41240. return RollingAverage;
  41241. }());
  41242. BABYLON.RollingAverage = RollingAverage;
  41243. })(BABYLON || (BABYLON = {}));
  41244. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41245. var BABYLON;
  41246. (function (BABYLON) {
  41247. /**
  41248. * "Static Class" containing the most commonly used helper while dealing with material for
  41249. * rendering purpose.
  41250. *
  41251. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41252. *
  41253. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41254. */
  41255. var MaterialHelper = /** @class */ (function () {
  41256. function MaterialHelper() {
  41257. }
  41258. /**
  41259. * Bind the current view position to an effect.
  41260. * @param effect The effect to be bound
  41261. * @param scene The scene the eyes position is used from
  41262. */
  41263. MaterialHelper.BindEyePosition = function (effect, scene) {
  41264. if (scene._forcedViewPosition) {
  41265. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41266. return;
  41267. }
  41268. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41269. };
  41270. /**
  41271. * Helps preparing the defines values about the UVs in used in the effect.
  41272. * UVs are shared as much as we can accross chanels in the shaders.
  41273. * @param texture The texture we are preparing the UVs for
  41274. * @param defines The defines to update
  41275. * @param key The chanel key "diffuse", "specular"... used in the shader
  41276. */
  41277. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41278. defines._needUVs = true;
  41279. defines[key] = true;
  41280. if (texture.getTextureMatrix().isIdentity(true)) {
  41281. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41282. if (texture.coordinatesIndex === 0) {
  41283. defines["MAINUV1"] = true;
  41284. }
  41285. else {
  41286. defines["MAINUV2"] = true;
  41287. }
  41288. }
  41289. else {
  41290. defines[key + "DIRECTUV"] = 0;
  41291. }
  41292. };
  41293. /**
  41294. * Binds a texture matrix value to its corrsponding uniform
  41295. * @param texture The texture to bind the matrix for
  41296. * @param uniformBuffer The uniform buffer receivin the data
  41297. * @param key The chanel key "diffuse", "specular"... used in the shader
  41298. */
  41299. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41300. var matrix = texture.getTextureMatrix();
  41301. if (!matrix.isIdentity(true)) {
  41302. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41303. }
  41304. };
  41305. /**
  41306. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41307. * @param mesh defines the current mesh
  41308. * @param scene defines the current scene
  41309. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41310. * @param pointsCloud defines if point cloud rendering has to be turned on
  41311. * @param fogEnabled defines if fog has to be turned on
  41312. * @param alphaTest defines if alpha testing has to be turned on
  41313. * @param defines defines the current list of defines
  41314. */
  41315. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41316. if (defines._areMiscDirty) {
  41317. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41318. defines["POINTSIZE"] = pointsCloud;
  41319. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41320. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41321. defines["ALPHATEST"] = alphaTest;
  41322. }
  41323. };
  41324. /**
  41325. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41326. * @param scene defines the current scene
  41327. * @param engine defines the current engine
  41328. * @param defines specifies the list of active defines
  41329. * @param useInstances defines if instances have to be turned on
  41330. * @param useClipPlane defines if clip plane have to be turned on
  41331. */
  41332. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41333. if (useClipPlane === void 0) { useClipPlane = null; }
  41334. var changed = false;
  41335. if (useClipPlane == null) {
  41336. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41337. }
  41338. if (defines["CLIPPLANE"] !== useClipPlane) {
  41339. defines["CLIPPLANE"] = useClipPlane;
  41340. changed = true;
  41341. }
  41342. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41343. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41344. changed = true;
  41345. }
  41346. if (defines["INSTANCES"] !== useInstances) {
  41347. defines["INSTANCES"] = useInstances;
  41348. changed = true;
  41349. }
  41350. if (changed) {
  41351. defines.markAsUnprocessed();
  41352. }
  41353. };
  41354. /**
  41355. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41356. * @param mesh The mesh containing the geometry data we will draw
  41357. * @param defines The defines to update
  41358. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41359. * @param useBones Precise whether bones should be used or not (override mesh info)
  41360. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41361. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41362. * @returns false if defines are considered not dirty and have not been checked
  41363. */
  41364. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41365. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41366. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41367. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41368. return false;
  41369. }
  41370. defines._normals = defines._needNormals;
  41371. defines._uvs = defines._needUVs;
  41372. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41373. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41374. defines["TANGENT"] = true;
  41375. }
  41376. if (defines._needUVs) {
  41377. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41378. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41379. }
  41380. else {
  41381. defines["UV1"] = false;
  41382. defines["UV2"] = false;
  41383. }
  41384. if (useVertexColor) {
  41385. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41386. defines["VERTEXCOLOR"] = hasVertexColors;
  41387. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41388. }
  41389. if (useBones) {
  41390. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41391. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41392. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41393. }
  41394. else {
  41395. defines["NUM_BONE_INFLUENCERS"] = 0;
  41396. defines["BonesPerMesh"] = 0;
  41397. }
  41398. }
  41399. if (useMorphTargets) {
  41400. var manager = mesh.morphTargetManager;
  41401. if (manager) {
  41402. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41403. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41404. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41405. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41406. }
  41407. else {
  41408. defines["MORPHTARGETS_TANGENT"] = false;
  41409. defines["MORPHTARGETS_NORMAL"] = false;
  41410. defines["MORPHTARGETS"] = false;
  41411. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41412. }
  41413. }
  41414. return true;
  41415. };
  41416. /**
  41417. * Prepares the defines related to the light information passed in parameter
  41418. * @param scene The scene we are intending to draw
  41419. * @param mesh The mesh the effect is compiling for
  41420. * @param defines The defines to update
  41421. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41422. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41423. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41424. * @returns true if normals will be required for the rest of the effect
  41425. */
  41426. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41427. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41428. if (disableLighting === void 0) { disableLighting = false; }
  41429. if (!defines._areLightsDirty) {
  41430. return defines._needNormals;
  41431. }
  41432. var lightIndex = 0;
  41433. var needNormals = false;
  41434. var needRebuild = false;
  41435. var lightmapMode = false;
  41436. var shadowEnabled = false;
  41437. var specularEnabled = false;
  41438. if (scene.lightsEnabled && !disableLighting) {
  41439. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41440. var light = _a[_i];
  41441. needNormals = true;
  41442. if (defines["LIGHT" + lightIndex] === undefined) {
  41443. needRebuild = true;
  41444. }
  41445. defines["LIGHT" + lightIndex] = true;
  41446. defines["SPOTLIGHT" + lightIndex] = false;
  41447. defines["HEMILIGHT" + lightIndex] = false;
  41448. defines["POINTLIGHT" + lightIndex] = false;
  41449. defines["DIRLIGHT" + lightIndex] = false;
  41450. var type;
  41451. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41452. type = "SPOTLIGHT" + lightIndex;
  41453. var spotLight = light;
  41454. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41455. }
  41456. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41457. type = "HEMILIGHT" + lightIndex;
  41458. }
  41459. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41460. type = "POINTLIGHT" + lightIndex;
  41461. }
  41462. else {
  41463. type = "DIRLIGHT" + lightIndex;
  41464. }
  41465. defines[type] = true;
  41466. // Specular
  41467. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41468. specularEnabled = true;
  41469. }
  41470. // Shadows
  41471. defines["SHADOW" + lightIndex] = false;
  41472. defines["SHADOWPCF" + lightIndex] = false;
  41473. defines["SHADOWPCSS" + lightIndex] = false;
  41474. defines["SHADOWPOISSON" + lightIndex] = false;
  41475. defines["SHADOWESM" + lightIndex] = false;
  41476. defines["SHADOWCUBE" + lightIndex] = false;
  41477. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41478. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41479. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41480. var shadowGenerator = light.getShadowGenerator();
  41481. if (shadowGenerator) {
  41482. shadowEnabled = true;
  41483. shadowGenerator.prepareDefines(defines, lightIndex);
  41484. }
  41485. }
  41486. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41487. lightmapMode = true;
  41488. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41489. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41490. }
  41491. else {
  41492. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41493. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41494. }
  41495. lightIndex++;
  41496. if (lightIndex === maxSimultaneousLights)
  41497. break;
  41498. }
  41499. }
  41500. defines["SPECULARTERM"] = specularEnabled;
  41501. defines["SHADOWS"] = shadowEnabled;
  41502. // Resetting all other lights if any
  41503. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41504. if (defines["LIGHT" + index] !== undefined) {
  41505. defines["LIGHT" + index] = false;
  41506. defines["HEMILIGHT" + lightIndex] = false;
  41507. defines["POINTLIGHT" + lightIndex] = false;
  41508. defines["DIRLIGHT" + lightIndex] = false;
  41509. defines["SPOTLIGHT" + lightIndex] = false;
  41510. defines["SHADOW" + lightIndex] = false;
  41511. }
  41512. }
  41513. var caps = scene.getEngine().getCaps();
  41514. if (defines["SHADOWFLOAT"] === undefined) {
  41515. needRebuild = true;
  41516. }
  41517. defines["SHADOWFLOAT"] = shadowEnabled &&
  41518. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41519. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41520. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41521. if (needRebuild) {
  41522. defines.rebuild();
  41523. }
  41524. return needNormals;
  41525. };
  41526. /**
  41527. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41528. * that won t be acctive due to defines being turned off.
  41529. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41530. * @param samplersList The samplers list
  41531. * @param defines The defines helping in the list generation
  41532. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41533. */
  41534. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41535. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41536. var uniformsList;
  41537. var uniformBuffersList = null;
  41538. if (uniformsListOrOptions.uniformsNames) {
  41539. var options = uniformsListOrOptions;
  41540. uniformsList = options.uniformsNames;
  41541. uniformBuffersList = options.uniformBuffersNames;
  41542. samplersList = options.samplers;
  41543. defines = options.defines;
  41544. maxSimultaneousLights = options.maxSimultaneousLights;
  41545. }
  41546. else {
  41547. uniformsList = uniformsListOrOptions;
  41548. if (!samplersList) {
  41549. samplersList = [];
  41550. }
  41551. }
  41552. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41553. if (!defines["LIGHT" + lightIndex]) {
  41554. break;
  41555. }
  41556. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41557. if (uniformBuffersList) {
  41558. uniformBuffersList.push("Light" + lightIndex);
  41559. }
  41560. samplersList.push("shadowSampler" + lightIndex);
  41561. samplersList.push("depthSampler" + lightIndex);
  41562. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41563. samplersList.push("projectionLightSampler" + lightIndex);
  41564. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41565. }
  41566. }
  41567. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41568. uniformsList.push("morphTargetInfluences");
  41569. }
  41570. };
  41571. /**
  41572. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41573. * @param defines The defines to update while falling back
  41574. * @param fallbacks The authorized effect fallbacks
  41575. * @param maxSimultaneousLights The maximum number of lights allowed
  41576. * @param rank the current rank of the Effect
  41577. * @returns The newly affected rank
  41578. */
  41579. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41580. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41581. if (rank === void 0) { rank = 0; }
  41582. var lightFallbackRank = 0;
  41583. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41584. if (!defines["LIGHT" + lightIndex]) {
  41585. break;
  41586. }
  41587. if (lightIndex > 0) {
  41588. lightFallbackRank = rank + lightIndex;
  41589. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41590. }
  41591. if (!defines["SHADOWS"]) {
  41592. if (defines["SHADOW" + lightIndex]) {
  41593. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41594. }
  41595. if (defines["SHADOWPCF" + lightIndex]) {
  41596. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41597. }
  41598. if (defines["SHADOWPCSS" + lightIndex]) {
  41599. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41600. }
  41601. if (defines["SHADOWPOISSON" + lightIndex]) {
  41602. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41603. }
  41604. if (defines["SHADOWESM" + lightIndex]) {
  41605. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41606. }
  41607. }
  41608. }
  41609. return lightFallbackRank++;
  41610. };
  41611. /**
  41612. * Prepares the list of attributes required for morph targets according to the effect defines.
  41613. * @param attribs The current list of supported attribs
  41614. * @param mesh The mesh to prepare the morph targets attributes for
  41615. * @param defines The current Defines of the effect
  41616. */
  41617. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41618. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41619. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41620. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41621. var manager = mesh.morphTargetManager;
  41622. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41623. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41624. for (var index = 0; index < influencers; index++) {
  41625. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41626. if (normal) {
  41627. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41628. }
  41629. if (tangent) {
  41630. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41631. }
  41632. if (attribs.length > maxAttributesCount) {
  41633. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41634. }
  41635. }
  41636. }
  41637. };
  41638. /**
  41639. * Prepares the list of attributes required for bones according to the effect defines.
  41640. * @param attribs The current list of supported attribs
  41641. * @param mesh The mesh to prepare the bones attributes for
  41642. * @param defines The current Defines of the effect
  41643. * @param fallbacks The current efffect fallback strategy
  41644. */
  41645. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41646. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41647. fallbacks.addCPUSkinningFallback(0, mesh);
  41648. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41649. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41650. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41651. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41652. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41653. }
  41654. }
  41655. };
  41656. /**
  41657. * Prepares the list of attributes required for instances according to the effect defines.
  41658. * @param attribs The current list of supported attribs
  41659. * @param defines The current Defines of the effect
  41660. */
  41661. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41662. if (defines["INSTANCES"]) {
  41663. attribs.push("world0");
  41664. attribs.push("world1");
  41665. attribs.push("world2");
  41666. attribs.push("world3");
  41667. }
  41668. };
  41669. /**
  41670. * Binds the light shadow information to the effect for the given mesh.
  41671. * @param light The light containing the generator
  41672. * @param scene The scene the lights belongs to
  41673. * @param mesh The mesh we are binding the information to render
  41674. * @param lightIndex The light index in the effect used to render the mesh
  41675. * @param effect The effect we are binding the data to
  41676. */
  41677. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41678. if (light.shadowEnabled && mesh.receiveShadows) {
  41679. var shadowGenerator = light.getShadowGenerator();
  41680. if (shadowGenerator) {
  41681. shadowGenerator.bindShadowLight(lightIndex, effect);
  41682. }
  41683. }
  41684. };
  41685. /**
  41686. * Binds the light information to the effect.
  41687. * @param light The light containing the generator
  41688. * @param effect The effect we are binding the data to
  41689. * @param lightIndex The light index in the effect used to render
  41690. */
  41691. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41692. light.transferToEffect(effect, lightIndex + "");
  41693. };
  41694. /**
  41695. * Binds the lights information from the scene to the effect for the given mesh.
  41696. * @param scene The scene the lights belongs to
  41697. * @param mesh The mesh we are binding the information to render
  41698. * @param effect The effect we are binding the data to
  41699. * @param defines The generated defines for the effect
  41700. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41701. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41702. */
  41703. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41704. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41705. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41706. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41707. for (var i = 0; i < len; i++) {
  41708. var light = mesh._lightSources[i];
  41709. var iAsString = i.toString();
  41710. var scaledIntensity = light.getScaledIntensity();
  41711. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41712. MaterialHelper.BindLightProperties(light, effect, i);
  41713. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41714. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41715. if (defines["SPECULARTERM"]) {
  41716. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41717. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41718. }
  41719. // Shadows
  41720. if (scene.shadowsEnabled) {
  41721. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41722. }
  41723. light._uniformBuffer.update();
  41724. }
  41725. };
  41726. /**
  41727. * Binds the fog information from the scene to the effect for the given mesh.
  41728. * @param scene The scene the lights belongs to
  41729. * @param mesh The mesh we are binding the information to render
  41730. * @param effect The effect we are binding the data to
  41731. */
  41732. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41733. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41734. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41735. effect.setColor3("vFogColor", scene.fogColor);
  41736. }
  41737. };
  41738. /**
  41739. * Binds the bones information from the mesh to the effect.
  41740. * @param mesh The mesh we are binding the information to render
  41741. * @param effect The effect we are binding the data to
  41742. */
  41743. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41744. if (!effect || !mesh) {
  41745. return;
  41746. }
  41747. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41748. mesh.computeBonesUsingShaders = false;
  41749. }
  41750. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41751. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41752. if (matrices) {
  41753. effect.setMatrices("mBones", matrices);
  41754. }
  41755. }
  41756. };
  41757. /**
  41758. * Binds the morph targets information from the mesh to the effect.
  41759. * @param abstractMesh The mesh we are binding the information to render
  41760. * @param effect The effect we are binding the data to
  41761. */
  41762. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41763. var manager = abstractMesh.morphTargetManager;
  41764. if (!abstractMesh || !manager) {
  41765. return;
  41766. }
  41767. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41768. };
  41769. /**
  41770. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41771. * @param defines The generated defines used in the effect
  41772. * @param effect The effect we are binding the data to
  41773. * @param scene The scene we are willing to render with logarithmic scale for
  41774. */
  41775. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41776. if (defines["LOGARITHMICDEPTH"]) {
  41777. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41778. }
  41779. };
  41780. /**
  41781. * Binds the clip plane information from the scene to the effect.
  41782. * @param scene The scene the clip plane information are extracted from
  41783. * @param effect The effect we are binding the data to
  41784. */
  41785. MaterialHelper.BindClipPlane = function (effect, scene) {
  41786. if (scene.clipPlane) {
  41787. var clipPlane = scene.clipPlane;
  41788. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41789. }
  41790. };
  41791. return MaterialHelper;
  41792. }());
  41793. BABYLON.MaterialHelper = MaterialHelper;
  41794. })(BABYLON || (BABYLON = {}));
  41795. //# sourceMappingURL=babylon.materialHelper.js.map
  41796. var BABYLON;
  41797. (function (BABYLON) {
  41798. var PushMaterial = /** @class */ (function (_super) {
  41799. __extends(PushMaterial, _super);
  41800. function PushMaterial(name, scene) {
  41801. var _this = _super.call(this, name, scene) || this;
  41802. _this._normalMatrix = new BABYLON.Matrix();
  41803. _this.storeEffectOnSubMeshes = true;
  41804. return _this;
  41805. }
  41806. PushMaterial.prototype.getEffect = function () {
  41807. return this._activeEffect;
  41808. };
  41809. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41810. if (!mesh) {
  41811. return false;
  41812. }
  41813. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41814. return true;
  41815. }
  41816. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41817. };
  41818. /**
  41819. * Binds the given world matrix to the active effect
  41820. *
  41821. * @param world the matrix to bind
  41822. */
  41823. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41824. this._activeEffect.setMatrix("world", world);
  41825. };
  41826. /**
  41827. * Binds the given normal matrix to the active effect
  41828. *
  41829. * @param normalMatrix the matrix to bind
  41830. */
  41831. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41832. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41833. };
  41834. PushMaterial.prototype.bind = function (world, mesh) {
  41835. if (!mesh) {
  41836. return;
  41837. }
  41838. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41839. };
  41840. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41841. if (effect === void 0) { effect = null; }
  41842. _super.prototype._afterBind.call(this, mesh);
  41843. this.getScene()._cachedEffect = effect;
  41844. };
  41845. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41846. if (visibility === void 0) { visibility = 1; }
  41847. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41848. };
  41849. return PushMaterial;
  41850. }(BABYLON.Material));
  41851. BABYLON.PushMaterial = PushMaterial;
  41852. })(BABYLON || (BABYLON = {}));
  41853. //# sourceMappingURL=babylon.pushMaterial.js.map
  41854. var BABYLON;
  41855. (function (BABYLON) {
  41856. /** @hidden */
  41857. var StandardMaterialDefines = /** @class */ (function (_super) {
  41858. __extends(StandardMaterialDefines, _super);
  41859. function StandardMaterialDefines() {
  41860. var _this = _super.call(this) || this;
  41861. _this.MAINUV1 = false;
  41862. _this.MAINUV2 = false;
  41863. _this.DIFFUSE = false;
  41864. _this.DIFFUSEDIRECTUV = 0;
  41865. _this.AMBIENT = false;
  41866. _this.AMBIENTDIRECTUV = 0;
  41867. _this.OPACITY = false;
  41868. _this.OPACITYDIRECTUV = 0;
  41869. _this.OPACITYRGB = false;
  41870. _this.REFLECTION = false;
  41871. _this.EMISSIVE = false;
  41872. _this.EMISSIVEDIRECTUV = 0;
  41873. _this.SPECULAR = false;
  41874. _this.SPECULARDIRECTUV = 0;
  41875. _this.BUMP = false;
  41876. _this.BUMPDIRECTUV = 0;
  41877. _this.PARALLAX = false;
  41878. _this.PARALLAXOCCLUSION = false;
  41879. _this.SPECULAROVERALPHA = false;
  41880. _this.CLIPPLANE = false;
  41881. _this.ALPHATEST = false;
  41882. _this.DEPTHPREPASS = false;
  41883. _this.ALPHAFROMDIFFUSE = false;
  41884. _this.POINTSIZE = false;
  41885. _this.FOG = false;
  41886. _this.SPECULARTERM = false;
  41887. _this.DIFFUSEFRESNEL = false;
  41888. _this.OPACITYFRESNEL = false;
  41889. _this.REFLECTIONFRESNEL = false;
  41890. _this.REFRACTIONFRESNEL = false;
  41891. _this.EMISSIVEFRESNEL = false;
  41892. _this.FRESNEL = false;
  41893. _this.NORMAL = false;
  41894. _this.UV1 = false;
  41895. _this.UV2 = false;
  41896. _this.VERTEXCOLOR = false;
  41897. _this.VERTEXALPHA = false;
  41898. _this.NUM_BONE_INFLUENCERS = 0;
  41899. _this.BonesPerMesh = 0;
  41900. _this.INSTANCES = false;
  41901. _this.GLOSSINESS = false;
  41902. _this.ROUGHNESS = false;
  41903. _this.EMISSIVEASILLUMINATION = false;
  41904. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41905. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41906. _this.LIGHTMAP = false;
  41907. _this.LIGHTMAPDIRECTUV = 0;
  41908. _this.OBJECTSPACE_NORMALMAP = false;
  41909. _this.USELIGHTMAPASSHADOWMAP = false;
  41910. _this.REFLECTIONMAP_3D = false;
  41911. _this.REFLECTIONMAP_SPHERICAL = false;
  41912. _this.REFLECTIONMAP_PLANAR = false;
  41913. _this.REFLECTIONMAP_CUBIC = false;
  41914. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41915. _this.REFLECTIONMAP_PROJECTION = false;
  41916. _this.REFLECTIONMAP_SKYBOX = false;
  41917. _this.REFLECTIONMAP_EXPLICIT = false;
  41918. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41919. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41920. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41921. _this.INVERTCUBICMAP = false;
  41922. _this.LOGARITHMICDEPTH = false;
  41923. _this.REFRACTION = false;
  41924. _this.REFRACTIONMAP_3D = false;
  41925. _this.REFLECTIONOVERALPHA = false;
  41926. _this.TWOSIDEDLIGHTING = false;
  41927. _this.SHADOWFLOAT = false;
  41928. _this.MORPHTARGETS = false;
  41929. _this.MORPHTARGETS_NORMAL = false;
  41930. _this.MORPHTARGETS_TANGENT = false;
  41931. _this.NUM_MORPH_INFLUENCERS = 0;
  41932. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41933. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41934. _this.IMAGEPROCESSING = false;
  41935. _this.VIGNETTE = false;
  41936. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41937. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41938. _this.TONEMAPPING = false;
  41939. _this.CONTRAST = false;
  41940. _this.COLORCURVES = false;
  41941. _this.COLORGRADING = false;
  41942. _this.COLORGRADING3D = false;
  41943. _this.SAMPLER3DGREENDEPTH = false;
  41944. _this.SAMPLER3DBGRMAP = false;
  41945. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41946. /**
  41947. * If the reflection texture on this material is in linear color space
  41948. * @hidden
  41949. */
  41950. _this.IS_REFLECTION_LINEAR = false;
  41951. /**
  41952. * If the refraction texture on this material is in linear color space
  41953. * @hidden
  41954. */
  41955. _this.IS_REFRACTION_LINEAR = false;
  41956. _this.EXPOSURE = false;
  41957. _this.rebuild();
  41958. return _this;
  41959. }
  41960. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41961. var modes = [
  41962. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41963. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41964. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41965. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41966. ];
  41967. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41968. var mode = modes_1[_i];
  41969. this[mode] = (mode === modeToEnable);
  41970. }
  41971. };
  41972. return StandardMaterialDefines;
  41973. }(BABYLON.MaterialDefines));
  41974. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41975. var StandardMaterial = /** @class */ (function (_super) {
  41976. __extends(StandardMaterial, _super);
  41977. function StandardMaterial(name, scene) {
  41978. var _this = _super.call(this, name, scene) || this;
  41979. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41980. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41981. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41982. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41983. _this.specularPower = 64;
  41984. _this._useAlphaFromDiffuseTexture = false;
  41985. _this._useEmissiveAsIllumination = false;
  41986. _this._linkEmissiveWithDiffuse = false;
  41987. _this._useSpecularOverAlpha = false;
  41988. _this._useReflectionOverAlpha = false;
  41989. _this._disableLighting = false;
  41990. _this._useObjectSpaceNormalMap = false;
  41991. _this._useParallax = false;
  41992. _this._useParallaxOcclusion = false;
  41993. _this.parallaxScaleBias = 0.05;
  41994. _this._roughness = 0;
  41995. _this.indexOfRefraction = 0.98;
  41996. _this.invertRefractionY = true;
  41997. /**
  41998. * Defines the alpha limits in alpha test mode
  41999. */
  42000. _this.alphaCutOff = 0.4;
  42001. _this._useLightmapAsShadowmap = false;
  42002. _this._useReflectionFresnelFromSpecular = false;
  42003. _this._useGlossinessFromSpecularMapAlpha = false;
  42004. _this._maxSimultaneousLights = 4;
  42005. /**
  42006. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42007. */
  42008. _this._invertNormalMapX = false;
  42009. /**
  42010. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42011. */
  42012. _this._invertNormalMapY = false;
  42013. /**
  42014. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42015. */
  42016. _this._twoSidedLighting = false;
  42017. _this._renderTargets = new BABYLON.SmartArray(16);
  42018. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42019. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42020. // Setup the default processing configuration to the scene.
  42021. _this._attachImageProcessingConfiguration(null);
  42022. _this.getRenderTargetTextures = function () {
  42023. _this._renderTargets.reset();
  42024. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42025. _this._renderTargets.push(_this._reflectionTexture);
  42026. }
  42027. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42028. _this._renderTargets.push(_this._refractionTexture);
  42029. }
  42030. return _this._renderTargets;
  42031. };
  42032. return _this;
  42033. }
  42034. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42035. /**
  42036. * Gets the image processing configuration used either in this material.
  42037. */
  42038. get: function () {
  42039. return this._imageProcessingConfiguration;
  42040. },
  42041. /**
  42042. * Sets the Default image processing configuration used either in the this material.
  42043. *
  42044. * If sets to null, the scene one is in use.
  42045. */
  42046. set: function (value) {
  42047. this._attachImageProcessingConfiguration(value);
  42048. // Ensure the effect will be rebuilt.
  42049. this._markAllSubMeshesAsTexturesDirty();
  42050. },
  42051. enumerable: true,
  42052. configurable: true
  42053. });
  42054. /**
  42055. * Attaches a new image processing configuration to the Standard Material.
  42056. * @param configuration
  42057. */
  42058. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42059. var _this = this;
  42060. if (configuration === this._imageProcessingConfiguration) {
  42061. return;
  42062. }
  42063. // Detaches observer.
  42064. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42065. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42066. }
  42067. // Pick the scene configuration if needed.
  42068. if (!configuration) {
  42069. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42070. }
  42071. else {
  42072. this._imageProcessingConfiguration = configuration;
  42073. }
  42074. // Attaches observer.
  42075. if (this._imageProcessingConfiguration) {
  42076. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42077. _this._markAllSubMeshesAsImageProcessingDirty();
  42078. });
  42079. }
  42080. };
  42081. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42082. /**
  42083. * Gets wether the color curves effect is enabled.
  42084. */
  42085. get: function () {
  42086. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42087. },
  42088. /**
  42089. * Sets wether the color curves effect is enabled.
  42090. */
  42091. set: function (value) {
  42092. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42093. },
  42094. enumerable: true,
  42095. configurable: true
  42096. });
  42097. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42098. /**
  42099. * Gets wether the color grading effect is enabled.
  42100. */
  42101. get: function () {
  42102. return this.imageProcessingConfiguration.colorGradingEnabled;
  42103. },
  42104. /**
  42105. * Gets wether the color grading effect is enabled.
  42106. */
  42107. set: function (value) {
  42108. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42109. },
  42110. enumerable: true,
  42111. configurable: true
  42112. });
  42113. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42114. /**
  42115. * Gets wether tonemapping is enabled or not.
  42116. */
  42117. get: function () {
  42118. return this._imageProcessingConfiguration.toneMappingEnabled;
  42119. },
  42120. /**
  42121. * Sets wether tonemapping is enabled or not
  42122. */
  42123. set: function (value) {
  42124. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42125. },
  42126. enumerable: true,
  42127. configurable: true
  42128. });
  42129. ;
  42130. ;
  42131. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42132. /**
  42133. * The camera exposure used on this material.
  42134. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42135. * This corresponds to a photographic exposure.
  42136. */
  42137. get: function () {
  42138. return this._imageProcessingConfiguration.exposure;
  42139. },
  42140. /**
  42141. * The camera exposure used on this material.
  42142. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42143. * This corresponds to a photographic exposure.
  42144. */
  42145. set: function (value) {
  42146. this._imageProcessingConfiguration.exposure = value;
  42147. },
  42148. enumerable: true,
  42149. configurable: true
  42150. });
  42151. ;
  42152. ;
  42153. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42154. /**
  42155. * Gets The camera contrast used on this material.
  42156. */
  42157. get: function () {
  42158. return this._imageProcessingConfiguration.contrast;
  42159. },
  42160. /**
  42161. * Sets The camera contrast used on this material.
  42162. */
  42163. set: function (value) {
  42164. this._imageProcessingConfiguration.contrast = value;
  42165. },
  42166. enumerable: true,
  42167. configurable: true
  42168. });
  42169. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42170. /**
  42171. * Gets the Color Grading 2D Lookup Texture.
  42172. */
  42173. get: function () {
  42174. return this._imageProcessingConfiguration.colorGradingTexture;
  42175. },
  42176. /**
  42177. * Sets the Color Grading 2D Lookup Texture.
  42178. */
  42179. set: function (value) {
  42180. this._imageProcessingConfiguration.colorGradingTexture = value;
  42181. },
  42182. enumerable: true,
  42183. configurable: true
  42184. });
  42185. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42186. /**
  42187. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42188. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42189. * 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;
  42190. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42191. */
  42192. get: function () {
  42193. return this._imageProcessingConfiguration.colorCurves;
  42194. },
  42195. /**
  42196. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42197. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42198. * 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;
  42199. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42200. */
  42201. set: function (value) {
  42202. this._imageProcessingConfiguration.colorCurves = value;
  42203. },
  42204. enumerable: true,
  42205. configurable: true
  42206. });
  42207. StandardMaterial.prototype.getClassName = function () {
  42208. return "StandardMaterial";
  42209. };
  42210. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42211. get: function () {
  42212. return this._useLogarithmicDepth;
  42213. },
  42214. set: function (value) {
  42215. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42216. this._markAllSubMeshesAsMiscDirty();
  42217. },
  42218. enumerable: true,
  42219. configurable: true
  42220. });
  42221. StandardMaterial.prototype.needAlphaBlending = function () {
  42222. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42223. };
  42224. StandardMaterial.prototype.needAlphaTesting = function () {
  42225. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42226. };
  42227. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42228. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42229. };
  42230. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42231. return this._diffuseTexture;
  42232. };
  42233. /**
  42234. * Child classes can use it to update shaders
  42235. */
  42236. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42237. if (useInstances === void 0) { useInstances = false; }
  42238. if (subMesh.effect && this.isFrozen) {
  42239. if (this._wasPreviouslyReady && subMesh.effect) {
  42240. return true;
  42241. }
  42242. }
  42243. if (!subMesh._materialDefines) {
  42244. subMesh._materialDefines = new StandardMaterialDefines();
  42245. }
  42246. var scene = this.getScene();
  42247. var defines = subMesh._materialDefines;
  42248. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42249. if (defines._renderId === scene.getRenderId()) {
  42250. return true;
  42251. }
  42252. }
  42253. var engine = scene.getEngine();
  42254. // Lights
  42255. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42256. // Textures
  42257. if (defines._areTexturesDirty) {
  42258. defines._needUVs = false;
  42259. defines.MAINUV1 = false;
  42260. defines.MAINUV2 = false;
  42261. if (scene.texturesEnabled) {
  42262. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42263. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42264. return false;
  42265. }
  42266. else {
  42267. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42268. }
  42269. }
  42270. else {
  42271. defines.DIFFUSE = false;
  42272. }
  42273. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42274. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42275. return false;
  42276. }
  42277. else {
  42278. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42279. }
  42280. }
  42281. else {
  42282. defines.AMBIENT = false;
  42283. }
  42284. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42285. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42286. return false;
  42287. }
  42288. else {
  42289. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42290. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42291. }
  42292. }
  42293. else {
  42294. defines.OPACITY = false;
  42295. }
  42296. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42297. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42298. return false;
  42299. }
  42300. else {
  42301. defines._needNormals = true;
  42302. defines.REFLECTION = true;
  42303. defines.ROUGHNESS = (this._roughness > 0);
  42304. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42305. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42306. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42307. switch (this._reflectionTexture.coordinatesMode) {
  42308. case BABYLON.Texture.EXPLICIT_MODE:
  42309. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42310. break;
  42311. case BABYLON.Texture.PLANAR_MODE:
  42312. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42313. break;
  42314. case BABYLON.Texture.PROJECTION_MODE:
  42315. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42316. break;
  42317. case BABYLON.Texture.SKYBOX_MODE:
  42318. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42319. break;
  42320. case BABYLON.Texture.SPHERICAL_MODE:
  42321. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42322. break;
  42323. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42324. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42325. break;
  42326. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42327. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42328. break;
  42329. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42330. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42331. break;
  42332. case BABYLON.Texture.CUBIC_MODE:
  42333. case BABYLON.Texture.INVCUBIC_MODE:
  42334. default:
  42335. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42336. break;
  42337. }
  42338. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42339. }
  42340. }
  42341. else {
  42342. defines.REFLECTION = false;
  42343. }
  42344. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42345. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42346. return false;
  42347. }
  42348. else {
  42349. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42350. }
  42351. }
  42352. else {
  42353. defines.EMISSIVE = false;
  42354. }
  42355. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42356. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42357. return false;
  42358. }
  42359. else {
  42360. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42361. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42362. }
  42363. }
  42364. else {
  42365. defines.LIGHTMAP = false;
  42366. }
  42367. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42368. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42369. return false;
  42370. }
  42371. else {
  42372. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42373. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42374. }
  42375. }
  42376. else {
  42377. defines.SPECULAR = false;
  42378. }
  42379. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42380. // Bump texure can not be not blocking.
  42381. if (!this._bumpTexture.isReady()) {
  42382. return false;
  42383. }
  42384. else {
  42385. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42386. defines.PARALLAX = this._useParallax;
  42387. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42388. }
  42389. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42390. }
  42391. else {
  42392. defines.BUMP = false;
  42393. }
  42394. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42395. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42396. return false;
  42397. }
  42398. else {
  42399. defines._needUVs = true;
  42400. defines.REFRACTION = true;
  42401. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42402. }
  42403. }
  42404. else {
  42405. defines.REFRACTION = false;
  42406. }
  42407. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42408. }
  42409. else {
  42410. defines.DIFFUSE = false;
  42411. defines.AMBIENT = false;
  42412. defines.OPACITY = false;
  42413. defines.REFLECTION = false;
  42414. defines.EMISSIVE = false;
  42415. defines.LIGHTMAP = false;
  42416. defines.BUMP = false;
  42417. defines.REFRACTION = false;
  42418. }
  42419. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42420. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42421. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42422. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42423. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42424. }
  42425. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42426. if (!this._imageProcessingConfiguration.isReady()) {
  42427. return false;
  42428. }
  42429. this._imageProcessingConfiguration.prepareDefines(defines);
  42430. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42431. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42432. }
  42433. if (defines._areFresnelDirty) {
  42434. if (StandardMaterial.FresnelEnabled) {
  42435. // Fresnel
  42436. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42437. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42438. this._reflectionFresnelParameters) {
  42439. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42440. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42441. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42442. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42443. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42444. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42445. defines._needNormals = true;
  42446. defines.FRESNEL = true;
  42447. }
  42448. }
  42449. else {
  42450. defines.FRESNEL = false;
  42451. }
  42452. }
  42453. // Misc.
  42454. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42455. // Attribs
  42456. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42457. // Values that need to be evaluated on every frame
  42458. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42459. // Get correct effect
  42460. if (defines.isDirty) {
  42461. defines.markAsProcessed();
  42462. scene.resetCachedMaterial();
  42463. // Fallbacks
  42464. var fallbacks = new BABYLON.EffectFallbacks();
  42465. if (defines.REFLECTION) {
  42466. fallbacks.addFallback(0, "REFLECTION");
  42467. }
  42468. if (defines.SPECULAR) {
  42469. fallbacks.addFallback(0, "SPECULAR");
  42470. }
  42471. if (defines.BUMP) {
  42472. fallbacks.addFallback(0, "BUMP");
  42473. }
  42474. if (defines.PARALLAX) {
  42475. fallbacks.addFallback(1, "PARALLAX");
  42476. }
  42477. if (defines.PARALLAXOCCLUSION) {
  42478. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42479. }
  42480. if (defines.SPECULAROVERALPHA) {
  42481. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42482. }
  42483. if (defines.FOG) {
  42484. fallbacks.addFallback(1, "FOG");
  42485. }
  42486. if (defines.POINTSIZE) {
  42487. fallbacks.addFallback(0, "POINTSIZE");
  42488. }
  42489. if (defines.LOGARITHMICDEPTH) {
  42490. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42491. }
  42492. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42493. if (defines.SPECULARTERM) {
  42494. fallbacks.addFallback(0, "SPECULARTERM");
  42495. }
  42496. if (defines.DIFFUSEFRESNEL) {
  42497. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42498. }
  42499. if (defines.OPACITYFRESNEL) {
  42500. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42501. }
  42502. if (defines.REFLECTIONFRESNEL) {
  42503. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42504. }
  42505. if (defines.EMISSIVEFRESNEL) {
  42506. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42507. }
  42508. if (defines.FRESNEL) {
  42509. fallbacks.addFallback(4, "FRESNEL");
  42510. }
  42511. //Attributes
  42512. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42513. if (defines.NORMAL) {
  42514. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42515. }
  42516. if (defines.UV1) {
  42517. attribs.push(BABYLON.VertexBuffer.UVKind);
  42518. }
  42519. if (defines.UV2) {
  42520. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42521. }
  42522. if (defines.VERTEXCOLOR) {
  42523. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42524. }
  42525. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42526. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42527. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42528. var shaderName = "default";
  42529. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42530. "vFogInfos", "vFogColor", "pointSize",
  42531. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42532. "mBones",
  42533. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42534. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42535. "vReflectionPosition", "vReflectionSize",
  42536. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42537. ];
  42538. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42539. var uniformBuffers = ["Material", "Scene"];
  42540. if (BABYLON.ImageProcessingConfiguration) {
  42541. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42542. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42543. }
  42544. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42545. uniformsNames: uniforms,
  42546. uniformBuffersNames: uniformBuffers,
  42547. samplers: samplers,
  42548. defines: defines,
  42549. maxSimultaneousLights: this._maxSimultaneousLights
  42550. });
  42551. if (this.customShaderNameResolve) {
  42552. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42553. }
  42554. var join = defines.toString();
  42555. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42556. attributes: attribs,
  42557. uniformsNames: uniforms,
  42558. uniformBuffersNames: uniformBuffers,
  42559. samplers: samplers,
  42560. defines: join,
  42561. fallbacks: fallbacks,
  42562. onCompiled: this.onCompiled,
  42563. onError: this.onError,
  42564. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42565. }, engine), defines);
  42566. this.buildUniformLayout();
  42567. }
  42568. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42569. return false;
  42570. }
  42571. defines._renderId = scene.getRenderId();
  42572. this._wasPreviouslyReady = true;
  42573. return true;
  42574. };
  42575. StandardMaterial.prototype.buildUniformLayout = function () {
  42576. // Order is important !
  42577. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42578. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42579. this._uniformBuffer.addUniform("opacityParts", 4);
  42580. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42581. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42582. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42583. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42584. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42585. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42586. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42587. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42588. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42589. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42590. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42591. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42592. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42593. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42594. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42595. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42596. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42597. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42598. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42599. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42600. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42601. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42602. this._uniformBuffer.addUniform("specularMatrix", 16);
  42603. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42604. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42605. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42606. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42607. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42608. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42609. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42610. this._uniformBuffer.addUniform("pointSize", 1);
  42611. this._uniformBuffer.create();
  42612. };
  42613. StandardMaterial.prototype.unbind = function () {
  42614. if (this._activeEffect) {
  42615. var needFlag = false;
  42616. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42617. this._activeEffect.setTexture("reflection2DSampler", null);
  42618. needFlag = true;
  42619. }
  42620. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42621. this._activeEffect.setTexture("refraction2DSampler", null);
  42622. needFlag = true;
  42623. }
  42624. if (needFlag) {
  42625. this._markAllSubMeshesAsTexturesDirty();
  42626. }
  42627. }
  42628. _super.prototype.unbind.call(this);
  42629. };
  42630. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42631. var scene = this.getScene();
  42632. var defines = subMesh._materialDefines;
  42633. if (!defines) {
  42634. return;
  42635. }
  42636. var effect = subMesh.effect;
  42637. if (!effect) {
  42638. return;
  42639. }
  42640. this._activeEffect = effect;
  42641. // Matrices
  42642. this.bindOnlyWorldMatrix(world);
  42643. // Normal Matrix
  42644. if (defines.OBJECTSPACE_NORMALMAP) {
  42645. world.toNormalMatrix(this._normalMatrix);
  42646. this.bindOnlyNormalMatrix(this._normalMatrix);
  42647. }
  42648. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42649. // Bones
  42650. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42651. if (mustRebind) {
  42652. this._uniformBuffer.bindToEffect(effect, "Material");
  42653. this.bindViewProjection(effect);
  42654. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42655. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42656. // Fresnel
  42657. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42658. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42659. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42660. }
  42661. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42662. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42663. }
  42664. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42665. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42666. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42667. }
  42668. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42669. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42670. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42671. }
  42672. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42673. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42674. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42675. }
  42676. }
  42677. // Textures
  42678. if (scene.texturesEnabled) {
  42679. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42680. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42681. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42682. if (this._diffuseTexture.hasAlpha) {
  42683. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42684. }
  42685. }
  42686. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42687. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42688. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42689. }
  42690. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42691. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42692. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42693. }
  42694. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42695. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42696. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42697. if (this._reflectionTexture.boundingBoxSize) {
  42698. var cubeTexture = this._reflectionTexture;
  42699. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42700. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42701. }
  42702. }
  42703. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42704. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42705. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42706. }
  42707. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42708. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42709. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42710. }
  42711. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42712. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42713. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42714. }
  42715. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42716. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42717. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42718. if (scene._mirroredCameraPosition) {
  42719. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42720. }
  42721. else {
  42722. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42723. }
  42724. }
  42725. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42726. var depth = 1.0;
  42727. if (!this._refractionTexture.isCube) {
  42728. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42729. if (this._refractionTexture.depth) {
  42730. depth = this._refractionTexture.depth;
  42731. }
  42732. }
  42733. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42734. }
  42735. }
  42736. // Point size
  42737. if (this.pointsCloud) {
  42738. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42739. }
  42740. if (defines.SPECULARTERM) {
  42741. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42742. }
  42743. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42744. // Diffuse
  42745. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42746. }
  42747. // Textures
  42748. if (scene.texturesEnabled) {
  42749. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42750. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42751. }
  42752. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42753. effect.setTexture("ambientSampler", this._ambientTexture);
  42754. }
  42755. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42756. effect.setTexture("opacitySampler", this._opacityTexture);
  42757. }
  42758. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42759. if (this._reflectionTexture.isCube) {
  42760. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42761. }
  42762. else {
  42763. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42764. }
  42765. }
  42766. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42767. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42768. }
  42769. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42770. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42771. }
  42772. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42773. effect.setTexture("specularSampler", this._specularTexture);
  42774. }
  42775. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42776. effect.setTexture("bumpSampler", this._bumpTexture);
  42777. }
  42778. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42779. var depth = 1.0;
  42780. if (this._refractionTexture.isCube) {
  42781. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42782. }
  42783. else {
  42784. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42785. }
  42786. }
  42787. }
  42788. // Clip plane
  42789. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42790. // Colors
  42791. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42792. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42793. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42794. }
  42795. if (mustRebind || !this.isFrozen) {
  42796. // Lights
  42797. if (scene.lightsEnabled && !this._disableLighting) {
  42798. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42799. }
  42800. // View
  42801. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42802. this.bindView(effect);
  42803. }
  42804. // Fog
  42805. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42806. // Morph targets
  42807. if (defines.NUM_MORPH_INFLUENCERS) {
  42808. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42809. }
  42810. // Log. depth
  42811. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42812. // image processing
  42813. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42814. this._imageProcessingConfiguration.bind(this._activeEffect);
  42815. }
  42816. }
  42817. this._uniformBuffer.update();
  42818. this._afterBind(mesh, this._activeEffect);
  42819. };
  42820. StandardMaterial.prototype.getAnimatables = function () {
  42821. var results = [];
  42822. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42823. results.push(this._diffuseTexture);
  42824. }
  42825. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42826. results.push(this._ambientTexture);
  42827. }
  42828. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42829. results.push(this._opacityTexture);
  42830. }
  42831. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42832. results.push(this._reflectionTexture);
  42833. }
  42834. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42835. results.push(this._emissiveTexture);
  42836. }
  42837. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42838. results.push(this._specularTexture);
  42839. }
  42840. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42841. results.push(this._bumpTexture);
  42842. }
  42843. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42844. results.push(this._lightmapTexture);
  42845. }
  42846. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42847. results.push(this._refractionTexture);
  42848. }
  42849. return results;
  42850. };
  42851. StandardMaterial.prototype.getActiveTextures = function () {
  42852. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42853. if (this._diffuseTexture) {
  42854. activeTextures.push(this._diffuseTexture);
  42855. }
  42856. if (this._ambientTexture) {
  42857. activeTextures.push(this._ambientTexture);
  42858. }
  42859. if (this._opacityTexture) {
  42860. activeTextures.push(this._opacityTexture);
  42861. }
  42862. if (this._reflectionTexture) {
  42863. activeTextures.push(this._reflectionTexture);
  42864. }
  42865. if (this._emissiveTexture) {
  42866. activeTextures.push(this._emissiveTexture);
  42867. }
  42868. if (this._specularTexture) {
  42869. activeTextures.push(this._specularTexture);
  42870. }
  42871. if (this._bumpTexture) {
  42872. activeTextures.push(this._bumpTexture);
  42873. }
  42874. if (this._lightmapTexture) {
  42875. activeTextures.push(this._lightmapTexture);
  42876. }
  42877. if (this._refractionTexture) {
  42878. activeTextures.push(this._refractionTexture);
  42879. }
  42880. return activeTextures;
  42881. };
  42882. StandardMaterial.prototype.hasTexture = function (texture) {
  42883. if (_super.prototype.hasTexture.call(this, texture)) {
  42884. return true;
  42885. }
  42886. if (this._diffuseTexture === texture) {
  42887. return true;
  42888. }
  42889. if (this._ambientTexture === texture) {
  42890. return true;
  42891. }
  42892. if (this._opacityTexture === texture) {
  42893. return true;
  42894. }
  42895. if (this._reflectionTexture === texture) {
  42896. return true;
  42897. }
  42898. if (this._emissiveTexture === texture) {
  42899. return true;
  42900. }
  42901. if (this._specularTexture === texture) {
  42902. return true;
  42903. }
  42904. if (this._bumpTexture === texture) {
  42905. return true;
  42906. }
  42907. if (this._lightmapTexture === texture) {
  42908. return true;
  42909. }
  42910. if (this._refractionTexture === texture) {
  42911. return true;
  42912. }
  42913. return false;
  42914. };
  42915. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42916. if (forceDisposeTextures) {
  42917. if (this._diffuseTexture) {
  42918. this._diffuseTexture.dispose();
  42919. }
  42920. if (this._ambientTexture) {
  42921. this._ambientTexture.dispose();
  42922. }
  42923. if (this._opacityTexture) {
  42924. this._opacityTexture.dispose();
  42925. }
  42926. if (this._reflectionTexture) {
  42927. this._reflectionTexture.dispose();
  42928. }
  42929. if (this._emissiveTexture) {
  42930. this._emissiveTexture.dispose();
  42931. }
  42932. if (this._specularTexture) {
  42933. this._specularTexture.dispose();
  42934. }
  42935. if (this._bumpTexture) {
  42936. this._bumpTexture.dispose();
  42937. }
  42938. if (this._lightmapTexture) {
  42939. this._lightmapTexture.dispose();
  42940. }
  42941. if (this._refractionTexture) {
  42942. this._refractionTexture.dispose();
  42943. }
  42944. }
  42945. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42946. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42947. }
  42948. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42949. };
  42950. StandardMaterial.prototype.clone = function (name) {
  42951. var _this = this;
  42952. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42953. result.name = name;
  42954. result.id = name;
  42955. return result;
  42956. };
  42957. StandardMaterial.prototype.serialize = function () {
  42958. return BABYLON.SerializationHelper.Serialize(this);
  42959. };
  42960. // Statics
  42961. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42962. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42963. };
  42964. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42965. get: function () {
  42966. return StandardMaterial._DiffuseTextureEnabled;
  42967. },
  42968. set: function (value) {
  42969. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42970. return;
  42971. }
  42972. StandardMaterial._DiffuseTextureEnabled = value;
  42973. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42974. },
  42975. enumerable: true,
  42976. configurable: true
  42977. });
  42978. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42979. get: function () {
  42980. return StandardMaterial._AmbientTextureEnabled;
  42981. },
  42982. set: function (value) {
  42983. if (StandardMaterial._AmbientTextureEnabled === value) {
  42984. return;
  42985. }
  42986. StandardMaterial._AmbientTextureEnabled = value;
  42987. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42988. },
  42989. enumerable: true,
  42990. configurable: true
  42991. });
  42992. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42993. get: function () {
  42994. return StandardMaterial._OpacityTextureEnabled;
  42995. },
  42996. set: function (value) {
  42997. if (StandardMaterial._OpacityTextureEnabled === value) {
  42998. return;
  42999. }
  43000. StandardMaterial._OpacityTextureEnabled = value;
  43001. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43002. },
  43003. enumerable: true,
  43004. configurable: true
  43005. });
  43006. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43007. get: function () {
  43008. return StandardMaterial._ReflectionTextureEnabled;
  43009. },
  43010. set: function (value) {
  43011. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43012. return;
  43013. }
  43014. StandardMaterial._ReflectionTextureEnabled = value;
  43015. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43016. },
  43017. enumerable: true,
  43018. configurable: true
  43019. });
  43020. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43021. get: function () {
  43022. return StandardMaterial._EmissiveTextureEnabled;
  43023. },
  43024. set: function (value) {
  43025. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43026. return;
  43027. }
  43028. StandardMaterial._EmissiveTextureEnabled = value;
  43029. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43030. },
  43031. enumerable: true,
  43032. configurable: true
  43033. });
  43034. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43035. get: function () {
  43036. return StandardMaterial._SpecularTextureEnabled;
  43037. },
  43038. set: function (value) {
  43039. if (StandardMaterial._SpecularTextureEnabled === value) {
  43040. return;
  43041. }
  43042. StandardMaterial._SpecularTextureEnabled = value;
  43043. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43044. },
  43045. enumerable: true,
  43046. configurable: true
  43047. });
  43048. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43049. get: function () {
  43050. return StandardMaterial._BumpTextureEnabled;
  43051. },
  43052. set: function (value) {
  43053. if (StandardMaterial._BumpTextureEnabled === value) {
  43054. return;
  43055. }
  43056. StandardMaterial._BumpTextureEnabled = value;
  43057. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43058. },
  43059. enumerable: true,
  43060. configurable: true
  43061. });
  43062. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43063. get: function () {
  43064. return StandardMaterial._LightmapTextureEnabled;
  43065. },
  43066. set: function (value) {
  43067. if (StandardMaterial._LightmapTextureEnabled === value) {
  43068. return;
  43069. }
  43070. StandardMaterial._LightmapTextureEnabled = value;
  43071. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43072. },
  43073. enumerable: true,
  43074. configurable: true
  43075. });
  43076. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43077. get: function () {
  43078. return StandardMaterial._RefractionTextureEnabled;
  43079. },
  43080. set: function (value) {
  43081. if (StandardMaterial._RefractionTextureEnabled === value) {
  43082. return;
  43083. }
  43084. StandardMaterial._RefractionTextureEnabled = value;
  43085. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43086. },
  43087. enumerable: true,
  43088. configurable: true
  43089. });
  43090. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43091. get: function () {
  43092. return StandardMaterial._ColorGradingTextureEnabled;
  43093. },
  43094. set: function (value) {
  43095. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43096. return;
  43097. }
  43098. StandardMaterial._ColorGradingTextureEnabled = value;
  43099. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43100. },
  43101. enumerable: true,
  43102. configurable: true
  43103. });
  43104. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43105. get: function () {
  43106. return StandardMaterial._FresnelEnabled;
  43107. },
  43108. set: function (value) {
  43109. if (StandardMaterial._FresnelEnabled === value) {
  43110. return;
  43111. }
  43112. StandardMaterial._FresnelEnabled = value;
  43113. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43114. },
  43115. enumerable: true,
  43116. configurable: true
  43117. });
  43118. // Flags used to enable or disable a type of texture for all Standard Materials
  43119. StandardMaterial._DiffuseTextureEnabled = true;
  43120. StandardMaterial._AmbientTextureEnabled = true;
  43121. StandardMaterial._OpacityTextureEnabled = true;
  43122. StandardMaterial._ReflectionTextureEnabled = true;
  43123. StandardMaterial._EmissiveTextureEnabled = true;
  43124. StandardMaterial._SpecularTextureEnabled = true;
  43125. StandardMaterial._BumpTextureEnabled = true;
  43126. StandardMaterial._LightmapTextureEnabled = true;
  43127. StandardMaterial._RefractionTextureEnabled = true;
  43128. StandardMaterial._ColorGradingTextureEnabled = true;
  43129. StandardMaterial._FresnelEnabled = true;
  43130. __decorate([
  43131. BABYLON.serializeAsTexture("diffuseTexture")
  43132. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43133. __decorate([
  43134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43135. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43136. __decorate([
  43137. BABYLON.serializeAsTexture("ambientTexture")
  43138. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43139. __decorate([
  43140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43141. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43142. __decorate([
  43143. BABYLON.serializeAsTexture("opacityTexture")
  43144. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43145. __decorate([
  43146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43147. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43148. __decorate([
  43149. BABYLON.serializeAsTexture("reflectionTexture")
  43150. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43151. __decorate([
  43152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43153. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43154. __decorate([
  43155. BABYLON.serializeAsTexture("emissiveTexture")
  43156. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43157. __decorate([
  43158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43159. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43160. __decorate([
  43161. BABYLON.serializeAsTexture("specularTexture")
  43162. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43163. __decorate([
  43164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43165. ], StandardMaterial.prototype, "specularTexture", void 0);
  43166. __decorate([
  43167. BABYLON.serializeAsTexture("bumpTexture")
  43168. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43169. __decorate([
  43170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43171. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43172. __decorate([
  43173. BABYLON.serializeAsTexture("lightmapTexture")
  43174. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43175. __decorate([
  43176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43177. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43178. __decorate([
  43179. BABYLON.serializeAsTexture("refractionTexture")
  43180. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43181. __decorate([
  43182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43183. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43184. __decorate([
  43185. BABYLON.serializeAsColor3("ambient")
  43186. ], StandardMaterial.prototype, "ambientColor", void 0);
  43187. __decorate([
  43188. BABYLON.serializeAsColor3("diffuse")
  43189. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43190. __decorate([
  43191. BABYLON.serializeAsColor3("specular")
  43192. ], StandardMaterial.prototype, "specularColor", void 0);
  43193. __decorate([
  43194. BABYLON.serializeAsColor3("emissive")
  43195. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43196. __decorate([
  43197. BABYLON.serialize()
  43198. ], StandardMaterial.prototype, "specularPower", void 0);
  43199. __decorate([
  43200. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43201. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43202. __decorate([
  43203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43204. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43205. __decorate([
  43206. BABYLON.serialize("useEmissiveAsIllumination")
  43207. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43208. __decorate([
  43209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43210. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43211. __decorate([
  43212. BABYLON.serialize("linkEmissiveWithDiffuse")
  43213. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43214. __decorate([
  43215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43216. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43217. __decorate([
  43218. BABYLON.serialize("useSpecularOverAlpha")
  43219. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43220. __decorate([
  43221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43222. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43223. __decorate([
  43224. BABYLON.serialize("useReflectionOverAlpha")
  43225. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43226. __decorate([
  43227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43228. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43229. __decorate([
  43230. BABYLON.serialize("disableLighting")
  43231. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43232. __decorate([
  43233. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43234. ], StandardMaterial.prototype, "disableLighting", void 0);
  43235. __decorate([
  43236. BABYLON.serialize("useObjectSpaceNormalMap")
  43237. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43238. __decorate([
  43239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43240. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43241. __decorate([
  43242. BABYLON.serialize("useParallax")
  43243. ], StandardMaterial.prototype, "_useParallax", void 0);
  43244. __decorate([
  43245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43246. ], StandardMaterial.prototype, "useParallax", void 0);
  43247. __decorate([
  43248. BABYLON.serialize("useParallaxOcclusion")
  43249. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43250. __decorate([
  43251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43252. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43253. __decorate([
  43254. BABYLON.serialize()
  43255. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43256. __decorate([
  43257. BABYLON.serialize("roughness")
  43258. ], StandardMaterial.prototype, "_roughness", void 0);
  43259. __decorate([
  43260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43261. ], StandardMaterial.prototype, "roughness", void 0);
  43262. __decorate([
  43263. BABYLON.serialize()
  43264. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43265. __decorate([
  43266. BABYLON.serialize()
  43267. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43268. __decorate([
  43269. BABYLON.serialize()
  43270. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43271. __decorate([
  43272. BABYLON.serialize("useLightmapAsShadowmap")
  43273. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43274. __decorate([
  43275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43276. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43277. __decorate([
  43278. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43279. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43280. __decorate([
  43281. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43282. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43283. __decorate([
  43284. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43285. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43286. __decorate([
  43287. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43288. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43289. __decorate([
  43290. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43291. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43292. __decorate([
  43293. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43294. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43295. __decorate([
  43296. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43297. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43298. __decorate([
  43299. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43300. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43301. __decorate([
  43302. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43303. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43304. __decorate([
  43305. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43306. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43307. __decorate([
  43308. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43309. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43310. __decorate([
  43311. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43312. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43313. __decorate([
  43314. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43315. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43316. __decorate([
  43317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43318. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43319. __decorate([
  43320. BABYLON.serialize("maxSimultaneousLights")
  43321. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43322. __decorate([
  43323. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43324. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43325. __decorate([
  43326. BABYLON.serialize("invertNormalMapX")
  43327. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43328. __decorate([
  43329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43330. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43331. __decorate([
  43332. BABYLON.serialize("invertNormalMapY")
  43333. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43334. __decorate([
  43335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43336. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43337. __decorate([
  43338. BABYLON.serialize("twoSidedLighting")
  43339. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43340. __decorate([
  43341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43342. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43343. __decorate([
  43344. BABYLON.serialize()
  43345. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43346. return StandardMaterial;
  43347. }(BABYLON.PushMaterial));
  43348. BABYLON.StandardMaterial = StandardMaterial;
  43349. })(BABYLON || (BABYLON = {}));
  43350. //# sourceMappingURL=babylon.standardMaterial.js.map
  43351. var BABYLON;
  43352. (function (BABYLON) {
  43353. /**
  43354. * Manages the defines for the PBR Material.
  43355. * @hiddenChildren
  43356. */
  43357. var PBRMaterialDefines = /** @class */ (function (_super) {
  43358. __extends(PBRMaterialDefines, _super);
  43359. /**
  43360. * Initializes the PBR Material defines.
  43361. */
  43362. function PBRMaterialDefines() {
  43363. var _this = _super.call(this) || this;
  43364. _this.PBR = true;
  43365. _this.MAINUV1 = false;
  43366. _this.MAINUV2 = false;
  43367. _this.UV1 = false;
  43368. _this.UV2 = false;
  43369. _this.ALBEDO = false;
  43370. _this.ALBEDODIRECTUV = 0;
  43371. _this.VERTEXCOLOR = false;
  43372. _this.AMBIENT = false;
  43373. _this.AMBIENTDIRECTUV = 0;
  43374. _this.AMBIENTINGRAYSCALE = false;
  43375. _this.OPACITY = false;
  43376. _this.VERTEXALPHA = false;
  43377. _this.OPACITYDIRECTUV = 0;
  43378. _this.OPACITYRGB = false;
  43379. _this.ALPHATEST = false;
  43380. _this.DEPTHPREPASS = false;
  43381. _this.ALPHABLEND = false;
  43382. _this.ALPHAFROMALBEDO = false;
  43383. _this.ALPHATESTVALUE = "0.5";
  43384. _this.SPECULAROVERALPHA = false;
  43385. _this.RADIANCEOVERALPHA = false;
  43386. _this.ALPHAFRESNEL = false;
  43387. _this.LINEARALPHAFRESNEL = false;
  43388. _this.PREMULTIPLYALPHA = false;
  43389. _this.EMISSIVE = false;
  43390. _this.EMISSIVEDIRECTUV = 0;
  43391. _this.REFLECTIVITY = false;
  43392. _this.REFLECTIVITYDIRECTUV = 0;
  43393. _this.SPECULARTERM = false;
  43394. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43395. _this.MICROSURFACEAUTOMATIC = false;
  43396. _this.LODBASEDMICROSFURACE = false;
  43397. _this.MICROSURFACEMAP = false;
  43398. _this.MICROSURFACEMAPDIRECTUV = 0;
  43399. _this.METALLICWORKFLOW = false;
  43400. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43401. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43402. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43403. _this.AOSTOREINMETALMAPRED = false;
  43404. _this.ENVIRONMENTBRDF = false;
  43405. _this.NORMAL = false;
  43406. _this.TANGENT = false;
  43407. _this.BUMP = false;
  43408. _this.BUMPDIRECTUV = 0;
  43409. _this.OBJECTSPACE_NORMALMAP = false;
  43410. _this.PARALLAX = false;
  43411. _this.PARALLAXOCCLUSION = false;
  43412. _this.NORMALXYSCALE = true;
  43413. _this.LIGHTMAP = false;
  43414. _this.LIGHTMAPDIRECTUV = 0;
  43415. _this.USELIGHTMAPASSHADOWMAP = false;
  43416. _this.GAMMALIGHTMAP = false;
  43417. _this.REFLECTION = false;
  43418. _this.REFLECTIONMAP_3D = false;
  43419. _this.REFLECTIONMAP_SPHERICAL = false;
  43420. _this.REFLECTIONMAP_PLANAR = false;
  43421. _this.REFLECTIONMAP_CUBIC = false;
  43422. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43423. _this.REFLECTIONMAP_PROJECTION = false;
  43424. _this.REFLECTIONMAP_SKYBOX = false;
  43425. _this.REFLECTIONMAP_EXPLICIT = false;
  43426. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43427. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43428. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43429. _this.INVERTCUBICMAP = false;
  43430. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43431. _this.USESPHERICALINVERTEX = false;
  43432. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43433. _this.LODINREFLECTIONALPHA = false;
  43434. _this.GAMMAREFLECTION = false;
  43435. _this.RGBDREFLECTION = false;
  43436. _this.RADIANCEOCCLUSION = false;
  43437. _this.HORIZONOCCLUSION = false;
  43438. _this.REFRACTION = false;
  43439. _this.REFRACTIONMAP_3D = false;
  43440. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43441. _this.LODINREFRACTIONALPHA = false;
  43442. _this.GAMMAREFRACTION = false;
  43443. _this.RGBDREFRACTION = false;
  43444. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43445. _this.INSTANCES = false;
  43446. _this.NUM_BONE_INFLUENCERS = 0;
  43447. _this.BonesPerMesh = 0;
  43448. _this.NONUNIFORMSCALING = false;
  43449. _this.MORPHTARGETS = false;
  43450. _this.MORPHTARGETS_NORMAL = false;
  43451. _this.MORPHTARGETS_TANGENT = false;
  43452. _this.NUM_MORPH_INFLUENCERS = 0;
  43453. _this.IMAGEPROCESSING = false;
  43454. _this.VIGNETTE = false;
  43455. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43456. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43457. _this.TONEMAPPING = false;
  43458. _this.CONTRAST = false;
  43459. _this.COLORCURVES = false;
  43460. _this.COLORGRADING = false;
  43461. _this.COLORGRADING3D = false;
  43462. _this.SAMPLER3DGREENDEPTH = false;
  43463. _this.SAMPLER3DBGRMAP = false;
  43464. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43465. _this.EXPOSURE = false;
  43466. _this.USEPHYSICALLIGHTFALLOFF = false;
  43467. _this.TWOSIDEDLIGHTING = false;
  43468. _this.SHADOWFLOAT = false;
  43469. _this.CLIPPLANE = false;
  43470. _this.POINTSIZE = false;
  43471. _this.FOG = false;
  43472. _this.LOGARITHMICDEPTH = false;
  43473. _this.FORCENORMALFORWARD = false;
  43474. _this.SPECULARAA = false;
  43475. _this.UNLIT = false;
  43476. _this.rebuild();
  43477. return _this;
  43478. }
  43479. /**
  43480. * Resets the PBR Material defines.
  43481. */
  43482. PBRMaterialDefines.prototype.reset = function () {
  43483. _super.prototype.reset.call(this);
  43484. this.ALPHATESTVALUE = "0.5";
  43485. this.PBR = true;
  43486. };
  43487. return PBRMaterialDefines;
  43488. }(BABYLON.MaterialDefines));
  43489. /**
  43490. * The Physically based material base class of BJS.
  43491. *
  43492. * This offers the main features of a standard PBR material.
  43493. * For more information, please refer to the documentation :
  43494. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43495. */
  43496. var PBRBaseMaterial = /** @class */ (function (_super) {
  43497. __extends(PBRBaseMaterial, _super);
  43498. /**
  43499. * Instantiates a new PBRMaterial instance.
  43500. *
  43501. * @param name The material name
  43502. * @param scene The scene the material will be use in.
  43503. */
  43504. function PBRBaseMaterial(name, scene) {
  43505. var _this = _super.call(this, name, scene) || this;
  43506. /**
  43507. * Intensity of the direct lights e.g. the four lights available in your scene.
  43508. * This impacts both the direct diffuse and specular highlights.
  43509. */
  43510. _this._directIntensity = 1.0;
  43511. /**
  43512. * Intensity of the emissive part of the material.
  43513. * This helps controlling the emissive effect without modifying the emissive color.
  43514. */
  43515. _this._emissiveIntensity = 1.0;
  43516. /**
  43517. * Intensity of the environment e.g. how much the environment will light the object
  43518. * either through harmonics for rough material or through the refelction for shiny ones.
  43519. */
  43520. _this._environmentIntensity = 1.0;
  43521. /**
  43522. * This is a special control allowing the reduction of the specular highlights coming from the
  43523. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43524. */
  43525. _this._specularIntensity = 1.0;
  43526. /**
  43527. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43528. */
  43529. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43530. /**
  43531. * Debug Control allowing disabling the bump map on this material.
  43532. */
  43533. _this._disableBumpMap = false;
  43534. /**
  43535. * AKA Occlusion Texture Intensity in other nomenclature.
  43536. */
  43537. _this._ambientTextureStrength = 1.0;
  43538. /**
  43539. * The color of a material in ambient lighting.
  43540. */
  43541. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43542. /**
  43543. * AKA Diffuse Color in other nomenclature.
  43544. */
  43545. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43546. /**
  43547. * AKA Specular Color in other nomenclature.
  43548. */
  43549. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43550. /**
  43551. * The color applied when light is reflected from a material.
  43552. */
  43553. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43554. /**
  43555. * The color applied when light is emitted from a material.
  43556. */
  43557. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43558. /**
  43559. * AKA Glossiness in other nomenclature.
  43560. */
  43561. _this._microSurface = 0.9;
  43562. /**
  43563. * source material index of refraction (IOR)' / 'destination material IOR.
  43564. */
  43565. _this._indexOfRefraction = 0.66;
  43566. /**
  43567. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43568. */
  43569. _this._invertRefractionY = false;
  43570. /**
  43571. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43572. * Materials half opaque for instance using refraction could benefit from this control.
  43573. */
  43574. _this._linkRefractionWithTransparency = false;
  43575. /**
  43576. * Specifies that the material will use the light map as a show map.
  43577. */
  43578. _this._useLightmapAsShadowmap = false;
  43579. /**
  43580. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43581. * makes the reflect vector face the model (under horizon).
  43582. */
  43583. _this._useHorizonOcclusion = true;
  43584. /**
  43585. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43586. * too much the area relying on ambient texture to define their ambient occlusion.
  43587. */
  43588. _this._useRadianceOcclusion = true;
  43589. /**
  43590. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43591. */
  43592. _this._useAlphaFromAlbedoTexture = false;
  43593. /**
  43594. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43595. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43596. */
  43597. _this._useSpecularOverAlpha = true;
  43598. /**
  43599. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43600. */
  43601. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43602. /**
  43603. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43604. */
  43605. _this._useRoughnessFromMetallicTextureAlpha = true;
  43606. /**
  43607. * Specifies if the metallic texture contains the roughness information in its green channel.
  43608. */
  43609. _this._useRoughnessFromMetallicTextureGreen = false;
  43610. /**
  43611. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43612. */
  43613. _this._useMetallnessFromMetallicTextureBlue = false;
  43614. /**
  43615. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43616. */
  43617. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43618. /**
  43619. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43620. */
  43621. _this._useAmbientInGrayScale = false;
  43622. /**
  43623. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43624. * The material will try to infer what glossiness each pixel should be.
  43625. */
  43626. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43627. /**
  43628. * BJS is using an harcoded light falloff based on a manually sets up range.
  43629. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43630. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43631. */
  43632. _this._usePhysicalLightFalloff = true;
  43633. /**
  43634. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43635. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43636. */
  43637. _this._useRadianceOverAlpha = true;
  43638. /**
  43639. * Allows using an object space normal map (instead of tangent space).
  43640. */
  43641. _this._useObjectSpaceNormalMap = false;
  43642. /**
  43643. * Allows using the bump map in parallax mode.
  43644. */
  43645. _this._useParallax = false;
  43646. /**
  43647. * Allows using the bump map in parallax occlusion mode.
  43648. */
  43649. _this._useParallaxOcclusion = false;
  43650. /**
  43651. * Controls the scale bias of the parallax mode.
  43652. */
  43653. _this._parallaxScaleBias = 0.05;
  43654. /**
  43655. * If sets to true, disables all the lights affecting the material.
  43656. */
  43657. _this._disableLighting = false;
  43658. /**
  43659. * Number of Simultaneous lights allowed on the material.
  43660. */
  43661. _this._maxSimultaneousLights = 4;
  43662. /**
  43663. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43664. */
  43665. _this._invertNormalMapX = false;
  43666. /**
  43667. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43668. */
  43669. _this._invertNormalMapY = false;
  43670. /**
  43671. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43672. */
  43673. _this._twoSidedLighting = false;
  43674. /**
  43675. * Defines the alpha limits in alpha test mode.
  43676. */
  43677. _this._alphaCutOff = 0.4;
  43678. /**
  43679. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43680. */
  43681. _this._forceAlphaTest = false;
  43682. /**
  43683. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43684. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43685. */
  43686. _this._useAlphaFresnel = false;
  43687. /**
  43688. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43689. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43690. */
  43691. _this._useLinearAlphaFresnel = false;
  43692. /**
  43693. * The transparency mode of the material.
  43694. */
  43695. _this._transparencyMode = null;
  43696. /**
  43697. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43698. * from cos thetav and roughness:
  43699. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43700. */
  43701. _this._environmentBRDFTexture = null;
  43702. /**
  43703. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43704. */
  43705. _this._forceIrradianceInFragment = false;
  43706. /**
  43707. * Force normal to face away from face.
  43708. */
  43709. _this._forceNormalForward = false;
  43710. /**
  43711. * Enables specular anti aliasing in the PBR shader.
  43712. * It will both interacts on the Geometry for analytical and IBL lighting.
  43713. * It also prefilter the roughness map based on the bump values.
  43714. */
  43715. _this._enableSpecularAntiAliasing = false;
  43716. /**
  43717. * Stores the available render targets.
  43718. */
  43719. _this._renderTargets = new BABYLON.SmartArray(16);
  43720. /**
  43721. * Sets the global ambient color for the material used in lighting calculations.
  43722. */
  43723. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43724. /**
  43725. * If set to true, no lighting calculations will be applied.
  43726. */
  43727. _this._unlit = false;
  43728. // Setup the default processing configuration to the scene.
  43729. _this._attachImageProcessingConfiguration(null);
  43730. _this.getRenderTargetTextures = function () {
  43731. _this._renderTargets.reset();
  43732. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43733. _this._renderTargets.push(_this._reflectionTexture);
  43734. }
  43735. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43736. _this._renderTargets.push(_this._refractionTexture);
  43737. }
  43738. return _this._renderTargets;
  43739. };
  43740. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43741. return _this;
  43742. }
  43743. /**
  43744. * Attaches a new image processing configuration to the PBR Material.
  43745. * @param configuration
  43746. */
  43747. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43748. var _this = this;
  43749. if (configuration === this._imageProcessingConfiguration) {
  43750. return;
  43751. }
  43752. // Detaches observer.
  43753. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43754. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43755. }
  43756. // Pick the scene configuration if needed.
  43757. if (!configuration) {
  43758. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43759. }
  43760. else {
  43761. this._imageProcessingConfiguration = configuration;
  43762. }
  43763. // Attaches observer.
  43764. if (this._imageProcessingConfiguration) {
  43765. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43766. _this._markAllSubMeshesAsImageProcessingDirty();
  43767. });
  43768. }
  43769. };
  43770. /**
  43771. * Gets the name of the material class.
  43772. */
  43773. PBRBaseMaterial.prototype.getClassName = function () {
  43774. return "PBRBaseMaterial";
  43775. };
  43776. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43777. /**
  43778. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43779. */
  43780. get: function () {
  43781. return this._useLogarithmicDepth;
  43782. },
  43783. /**
  43784. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43785. */
  43786. set: function (value) {
  43787. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43788. },
  43789. enumerable: true,
  43790. configurable: true
  43791. });
  43792. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43793. /**
  43794. * Gets the current transparency mode.
  43795. */
  43796. get: function () {
  43797. return this._transparencyMode;
  43798. },
  43799. /**
  43800. * Sets the transparency mode of the material.
  43801. *
  43802. * | Value | Type | Description |
  43803. * | ----- | ----------------------------------- | ----------- |
  43804. * | 0 | OPAQUE | |
  43805. * | 1 | ALPHATEST | |
  43806. * | 2 | ALPHABLEND | |
  43807. * | 3 | ALPHATESTANDBLEND | |
  43808. *
  43809. */
  43810. set: function (value) {
  43811. if (this._transparencyMode === value) {
  43812. return;
  43813. }
  43814. this._transparencyMode = value;
  43815. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43816. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43817. },
  43818. enumerable: true,
  43819. configurable: true
  43820. });
  43821. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43822. /**
  43823. * Returns true if alpha blending should be disabled.
  43824. */
  43825. get: function () {
  43826. return (this._linkRefractionWithTransparency ||
  43827. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43828. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43829. },
  43830. enumerable: true,
  43831. configurable: true
  43832. });
  43833. /**
  43834. * Specifies whether or not this material should be rendered in alpha blend mode.
  43835. */
  43836. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43837. if (this._disableAlphaBlending) {
  43838. return false;
  43839. }
  43840. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43841. };
  43842. /**
  43843. * Specifies if the mesh will require alpha blending.
  43844. * @param mesh - BJS mesh.
  43845. */
  43846. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43847. if (this._disableAlphaBlending) {
  43848. return false;
  43849. }
  43850. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43851. };
  43852. /**
  43853. * Specifies whether or not this material should be rendered in alpha test mode.
  43854. */
  43855. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43856. if (this._forceAlphaTest) {
  43857. return true;
  43858. }
  43859. if (this._linkRefractionWithTransparency) {
  43860. return false;
  43861. }
  43862. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43863. };
  43864. /**
  43865. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43866. */
  43867. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43868. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43869. };
  43870. /**
  43871. * Gets the texture used for the alpha test.
  43872. */
  43873. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43874. return this._albedoTexture;
  43875. };
  43876. /**
  43877. * Specifies that the submesh is ready to be used.
  43878. * @param mesh - BJS mesh.
  43879. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43880. * @param useInstances - Specifies that instances should be used.
  43881. * @returns - boolean indicating that the submesh is ready or not.
  43882. */
  43883. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43884. if (subMesh.effect && this.isFrozen) {
  43885. if (this._wasPreviouslyReady) {
  43886. return true;
  43887. }
  43888. }
  43889. if (!subMesh._materialDefines) {
  43890. subMesh._materialDefines = new PBRMaterialDefines();
  43891. }
  43892. var defines = subMesh._materialDefines;
  43893. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43894. if (defines._renderId === this.getScene().getRenderId()) {
  43895. return true;
  43896. }
  43897. }
  43898. var scene = this.getScene();
  43899. var engine = scene.getEngine();
  43900. if (defines._areTexturesDirty) {
  43901. if (scene.texturesEnabled) {
  43902. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43903. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43904. return false;
  43905. }
  43906. }
  43907. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43908. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43909. return false;
  43910. }
  43911. }
  43912. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43913. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43914. return false;
  43915. }
  43916. }
  43917. var reflectionTexture = this._getReflectionTexture();
  43918. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43919. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43920. return false;
  43921. }
  43922. }
  43923. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43924. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43925. return false;
  43926. }
  43927. }
  43928. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43929. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43930. return false;
  43931. }
  43932. }
  43933. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43934. if (this._metallicTexture) {
  43935. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43936. return false;
  43937. }
  43938. }
  43939. else if (this._reflectivityTexture) {
  43940. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43941. return false;
  43942. }
  43943. }
  43944. if (this._microSurfaceTexture) {
  43945. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43946. return false;
  43947. }
  43948. }
  43949. }
  43950. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43951. // Bump texture cannot be not blocking.
  43952. if (!this._bumpTexture.isReady()) {
  43953. return false;
  43954. }
  43955. }
  43956. var refractionTexture = this._getRefractionTexture();
  43957. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43958. if (!refractionTexture.isReadyOrNotBlocking()) {
  43959. return false;
  43960. }
  43961. }
  43962. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43963. // This is blocking.
  43964. if (!this._environmentBRDFTexture.isReady()) {
  43965. return false;
  43966. }
  43967. }
  43968. }
  43969. }
  43970. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43971. if (!this._imageProcessingConfiguration.isReady()) {
  43972. return false;
  43973. }
  43974. }
  43975. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43976. mesh.createNormals(true);
  43977. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43978. }
  43979. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43980. if (effect) {
  43981. scene.resetCachedMaterial();
  43982. subMesh.setEffect(effect, defines);
  43983. this.buildUniformLayout();
  43984. }
  43985. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43986. return false;
  43987. }
  43988. defines._renderId = scene.getRenderId();
  43989. this._wasPreviouslyReady = true;
  43990. return true;
  43991. };
  43992. /**
  43993. * Specifies if the material uses metallic roughness workflow.
  43994. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43995. */
  43996. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43997. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43998. return true;
  43999. }
  44000. return false;
  44001. };
  44002. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44003. if (onCompiled === void 0) { onCompiled = null; }
  44004. if (onError === void 0) { onError = null; }
  44005. if (useInstances === void 0) { useInstances = null; }
  44006. if (useClipPlane === void 0) { useClipPlane = null; }
  44007. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44008. if (!defines.isDirty) {
  44009. return null;
  44010. }
  44011. defines.markAsProcessed();
  44012. var scene = this.getScene();
  44013. var engine = scene.getEngine();
  44014. // Fallbacks
  44015. var fallbacks = new BABYLON.EffectFallbacks();
  44016. var fallbackRank = 0;
  44017. if (defines.USESPHERICALINVERTEX) {
  44018. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44019. }
  44020. if (defines.FOG) {
  44021. fallbacks.addFallback(fallbackRank, "FOG");
  44022. }
  44023. if (defines.SPECULARAA) {
  44024. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44025. }
  44026. if (defines.POINTSIZE) {
  44027. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44028. }
  44029. if (defines.LOGARITHMICDEPTH) {
  44030. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44031. }
  44032. if (defines.PARALLAX) {
  44033. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44034. }
  44035. if (defines.PARALLAXOCCLUSION) {
  44036. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44037. }
  44038. if (defines.ENVIRONMENTBRDF) {
  44039. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44040. }
  44041. if (defines.TANGENT) {
  44042. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44043. }
  44044. if (defines.BUMP) {
  44045. fallbacks.addFallback(fallbackRank++, "BUMP");
  44046. }
  44047. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44048. if (defines.SPECULARTERM) {
  44049. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44050. }
  44051. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44052. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44053. }
  44054. if (defines.LIGHTMAP) {
  44055. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44056. }
  44057. if (defines.NORMAL) {
  44058. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44059. }
  44060. if (defines.AMBIENT) {
  44061. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44062. }
  44063. if (defines.EMISSIVE) {
  44064. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44065. }
  44066. if (defines.VERTEXCOLOR) {
  44067. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44068. }
  44069. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44070. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44071. }
  44072. if (defines.MORPHTARGETS) {
  44073. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44074. }
  44075. //Attributes
  44076. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44077. if (defines.NORMAL) {
  44078. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44079. }
  44080. if (defines.TANGENT) {
  44081. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44082. }
  44083. if (defines.UV1) {
  44084. attribs.push(BABYLON.VertexBuffer.UVKind);
  44085. }
  44086. if (defines.UV2) {
  44087. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44088. }
  44089. if (defines.VERTEXCOLOR) {
  44090. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44091. }
  44092. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44093. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44094. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44095. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44096. "vFogInfos", "vFogColor", "pointSize",
  44097. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44098. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44099. "mBones",
  44100. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44101. "vLightingIntensity",
  44102. "logarithmicDepthConstant",
  44103. "vSphericalX", "vSphericalY", "vSphericalZ",
  44104. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44105. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44106. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44107. "vTangentSpaceParams"
  44108. ];
  44109. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44110. "bumpSampler", "lightmapSampler", "opacitySampler",
  44111. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44112. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44113. "microSurfaceSampler", "environmentBrdfSampler"];
  44114. var uniformBuffers = ["Material", "Scene"];
  44115. if (BABYLON.ImageProcessingConfiguration) {
  44116. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44117. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44118. }
  44119. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44120. uniformsNames: uniforms,
  44121. uniformBuffersNames: uniformBuffers,
  44122. samplers: samplers,
  44123. defines: defines,
  44124. maxSimultaneousLights: this._maxSimultaneousLights
  44125. });
  44126. var join = defines.toString();
  44127. return engine.createEffect("pbr", {
  44128. attributes: attribs,
  44129. uniformsNames: uniforms,
  44130. uniformBuffersNames: uniformBuffers,
  44131. samplers: samplers,
  44132. defines: join,
  44133. fallbacks: fallbacks,
  44134. onCompiled: onCompiled,
  44135. onError: onError,
  44136. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44137. }, engine);
  44138. };
  44139. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44140. if (useInstances === void 0) { useInstances = null; }
  44141. if (useClipPlane === void 0) { useClipPlane = null; }
  44142. var scene = this.getScene();
  44143. var engine = scene.getEngine();
  44144. // Lights
  44145. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44146. defines._needNormals = true;
  44147. // Textures
  44148. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44149. if (defines._areTexturesDirty) {
  44150. defines._needUVs = false;
  44151. if (scene.texturesEnabled) {
  44152. if (scene.getEngine().getCaps().textureLOD) {
  44153. defines.LODBASEDMICROSFURACE = true;
  44154. }
  44155. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44156. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44157. }
  44158. else {
  44159. defines.ALBEDO = false;
  44160. }
  44161. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44162. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44163. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44164. }
  44165. else {
  44166. defines.AMBIENT = false;
  44167. }
  44168. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44169. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44170. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44171. }
  44172. else {
  44173. defines.OPACITY = false;
  44174. }
  44175. var reflectionTexture = this._getReflectionTexture();
  44176. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44177. defines.REFLECTION = true;
  44178. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44179. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44180. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44181. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44182. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44183. defines.INVERTCUBICMAP = true;
  44184. }
  44185. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44186. switch (reflectionTexture.coordinatesMode) {
  44187. case BABYLON.Texture.EXPLICIT_MODE:
  44188. defines.REFLECTIONMAP_EXPLICIT = true;
  44189. break;
  44190. case BABYLON.Texture.PLANAR_MODE:
  44191. defines.REFLECTIONMAP_PLANAR = true;
  44192. break;
  44193. case BABYLON.Texture.PROJECTION_MODE:
  44194. defines.REFLECTIONMAP_PROJECTION = true;
  44195. break;
  44196. case BABYLON.Texture.SKYBOX_MODE:
  44197. defines.REFLECTIONMAP_SKYBOX = true;
  44198. break;
  44199. case BABYLON.Texture.SPHERICAL_MODE:
  44200. defines.REFLECTIONMAP_SPHERICAL = true;
  44201. break;
  44202. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44203. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44204. break;
  44205. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44206. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44207. break;
  44208. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44209. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44210. break;
  44211. case BABYLON.Texture.CUBIC_MODE:
  44212. case BABYLON.Texture.INVCUBIC_MODE:
  44213. default:
  44214. defines.REFLECTIONMAP_CUBIC = true;
  44215. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44216. break;
  44217. }
  44218. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44219. if (reflectionTexture.sphericalPolynomial) {
  44220. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44221. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44222. defines.USESPHERICALINVERTEX = false;
  44223. }
  44224. else {
  44225. defines.USESPHERICALINVERTEX = true;
  44226. }
  44227. }
  44228. }
  44229. }
  44230. else {
  44231. defines.REFLECTION = false;
  44232. defines.REFLECTIONMAP_3D = false;
  44233. defines.REFLECTIONMAP_SPHERICAL = false;
  44234. defines.REFLECTIONMAP_PLANAR = false;
  44235. defines.REFLECTIONMAP_CUBIC = false;
  44236. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44237. defines.REFLECTIONMAP_PROJECTION = false;
  44238. defines.REFLECTIONMAP_SKYBOX = false;
  44239. defines.REFLECTIONMAP_EXPLICIT = false;
  44240. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44241. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44242. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44243. defines.INVERTCUBICMAP = false;
  44244. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44245. defines.USESPHERICALINVERTEX = false;
  44246. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44247. defines.LODINREFLECTIONALPHA = false;
  44248. defines.GAMMAREFLECTION = false;
  44249. defines.RGBDREFLECTION = false;
  44250. }
  44251. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44252. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44253. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44254. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44255. }
  44256. else {
  44257. defines.LIGHTMAP = false;
  44258. }
  44259. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44260. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44261. }
  44262. else {
  44263. defines.EMISSIVE = false;
  44264. }
  44265. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44266. if (this._metallicTexture) {
  44267. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44268. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44269. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44270. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44271. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44272. }
  44273. else if (this._reflectivityTexture) {
  44274. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44275. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44276. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44277. }
  44278. else {
  44279. defines.REFLECTIVITY = false;
  44280. }
  44281. if (this._microSurfaceTexture) {
  44282. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44283. }
  44284. else {
  44285. defines.MICROSURFACEMAP = false;
  44286. }
  44287. }
  44288. else {
  44289. defines.REFLECTIVITY = false;
  44290. defines.MICROSURFACEMAP = false;
  44291. }
  44292. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44293. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44294. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44295. defines.PARALLAX = true;
  44296. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44297. }
  44298. else {
  44299. defines.PARALLAX = false;
  44300. }
  44301. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44302. }
  44303. else {
  44304. defines.BUMP = false;
  44305. }
  44306. var refractionTexture = this._getRefractionTexture();
  44307. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44308. defines.REFRACTION = true;
  44309. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44310. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44311. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44312. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44313. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44314. if (this._linkRefractionWithTransparency) {
  44315. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44316. }
  44317. }
  44318. else {
  44319. defines.REFRACTION = false;
  44320. }
  44321. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44322. defines.ENVIRONMENTBRDF = true;
  44323. }
  44324. else {
  44325. defines.ENVIRONMENTBRDF = false;
  44326. }
  44327. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44328. defines.ALPHAFROMALBEDO = true;
  44329. }
  44330. else {
  44331. defines.ALPHAFROMALBEDO = false;
  44332. }
  44333. }
  44334. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44335. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44336. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44337. if (!this.backFaceCulling && this._twoSidedLighting) {
  44338. defines.TWOSIDEDLIGHTING = true;
  44339. }
  44340. else {
  44341. defines.TWOSIDEDLIGHTING = false;
  44342. }
  44343. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44344. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44345. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44346. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44347. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44348. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44349. }
  44350. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44351. this._imageProcessingConfiguration.prepareDefines(defines);
  44352. }
  44353. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44354. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44355. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44356. // Misc.
  44357. if (defines._areMiscDirty) {
  44358. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44359. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44360. }
  44361. // Values that need to be evaluated on every frame
  44362. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44363. // Attribs
  44364. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44365. };
  44366. /**
  44367. * Force shader compilation
  44368. */
  44369. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44370. var _this = this;
  44371. var localOptions = __assign({ clipPlane: false }, options);
  44372. var defines = new PBRMaterialDefines();
  44373. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44374. if (effect.isReady()) {
  44375. if (onCompiled) {
  44376. onCompiled(this);
  44377. }
  44378. }
  44379. else {
  44380. effect.onCompileObservable.add(function () {
  44381. if (onCompiled) {
  44382. onCompiled(_this);
  44383. }
  44384. });
  44385. }
  44386. };
  44387. /**
  44388. * Initializes the uniform buffer layout for the shader.
  44389. */
  44390. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44391. // Order is important !
  44392. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44393. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44394. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44395. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44396. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44397. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44398. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44399. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44400. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44401. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44402. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44403. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44404. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44405. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44406. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44407. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44408. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44409. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44410. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44411. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44412. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44413. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44414. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44415. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44416. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44417. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44418. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44419. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44420. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44421. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44422. this._uniformBuffer.addUniform("pointSize", 1);
  44423. this._uniformBuffer.create();
  44424. };
  44425. /**
  44426. * Unbinds the textures.
  44427. */
  44428. PBRBaseMaterial.prototype.unbind = function () {
  44429. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44430. this._uniformBuffer.setTexture("reflectionSampler", null);
  44431. }
  44432. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44433. this._uniformBuffer.setTexture("refractionSampler", null);
  44434. }
  44435. _super.prototype.unbind.call(this);
  44436. };
  44437. /**
  44438. * Binds the submesh data.
  44439. * @param world - The world matrix.
  44440. * @param mesh - The BJS mesh.
  44441. * @param subMesh - A submesh of the BJS mesh.
  44442. */
  44443. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44444. var scene = this.getScene();
  44445. var defines = subMesh._materialDefines;
  44446. if (!defines) {
  44447. return;
  44448. }
  44449. var effect = subMesh.effect;
  44450. if (!effect) {
  44451. return;
  44452. }
  44453. this._activeEffect = effect;
  44454. // Matrices
  44455. this.bindOnlyWorldMatrix(world);
  44456. // Normal Matrix
  44457. if (defines.OBJECTSPACE_NORMALMAP) {
  44458. world.toNormalMatrix(this._normalMatrix);
  44459. this.bindOnlyNormalMatrix(this._normalMatrix);
  44460. }
  44461. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44462. // Bones
  44463. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44464. var reflectionTexture = null;
  44465. if (mustRebind) {
  44466. this._uniformBuffer.bindToEffect(effect, "Material");
  44467. this.bindViewProjection(effect);
  44468. reflectionTexture = this._getReflectionTexture();
  44469. var refractionTexture = this._getRefractionTexture();
  44470. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44471. // Texture uniforms
  44472. if (scene.texturesEnabled) {
  44473. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44474. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44475. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44476. }
  44477. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44478. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44479. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44480. }
  44481. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44482. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44483. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44484. }
  44485. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44486. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44487. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44488. if (reflectionTexture.boundingBoxSize) {
  44489. var cubeTexture = reflectionTexture;
  44490. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44491. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44492. }
  44493. var polynomials = reflectionTexture.sphericalPolynomial;
  44494. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44495. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44496. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44497. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44498. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44499. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44500. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44501. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44502. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44503. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44504. }
  44505. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44506. }
  44507. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44508. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44509. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44510. }
  44511. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44512. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44513. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44514. }
  44515. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44516. if (this._metallicTexture) {
  44517. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44518. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44519. }
  44520. else if (this._reflectivityTexture) {
  44521. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44522. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44523. }
  44524. if (this._microSurfaceTexture) {
  44525. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44526. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44527. }
  44528. }
  44529. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44530. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44531. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44532. if (scene._mirroredCameraPosition) {
  44533. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44534. }
  44535. else {
  44536. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44537. }
  44538. }
  44539. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44540. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44541. var depth = 1.0;
  44542. if (!refractionTexture.isCube) {
  44543. if (refractionTexture.depth) {
  44544. depth = refractionTexture.depth;
  44545. }
  44546. }
  44547. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44548. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44549. }
  44550. }
  44551. // Point size
  44552. if (this.pointsCloud) {
  44553. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44554. }
  44555. // Colors
  44556. if (defines.METALLICWORKFLOW) {
  44557. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44558. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44559. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44560. }
  44561. else {
  44562. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44563. }
  44564. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44565. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44566. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44567. // Misc
  44568. this._lightingInfos.x = this._directIntensity;
  44569. this._lightingInfos.y = this._emissiveIntensity;
  44570. this._lightingInfos.z = this._environmentIntensity;
  44571. this._lightingInfos.w = this._specularIntensity;
  44572. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44573. }
  44574. // Textures
  44575. if (scene.texturesEnabled) {
  44576. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44577. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44578. }
  44579. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44580. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44581. }
  44582. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44583. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44584. }
  44585. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44586. if (defines.LODBASEDMICROSFURACE) {
  44587. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44588. }
  44589. else {
  44590. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44591. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44592. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44593. }
  44594. }
  44595. if (defines.ENVIRONMENTBRDF) {
  44596. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44597. }
  44598. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44599. if (defines.LODBASEDMICROSFURACE) {
  44600. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44601. }
  44602. else {
  44603. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44604. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44605. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44606. }
  44607. }
  44608. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44609. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44610. }
  44611. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44612. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44613. }
  44614. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44615. if (this._metallicTexture) {
  44616. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44617. }
  44618. else if (this._reflectivityTexture) {
  44619. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44620. }
  44621. if (this._microSurfaceTexture) {
  44622. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44623. }
  44624. }
  44625. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44626. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44627. }
  44628. }
  44629. // Clip plane
  44630. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44631. // Colors
  44632. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44633. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44634. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44635. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44636. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44637. }
  44638. if (mustRebind || !this.isFrozen) {
  44639. // Lights
  44640. if (scene.lightsEnabled && !this._disableLighting) {
  44641. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44642. }
  44643. // View
  44644. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44645. this.bindView(effect);
  44646. }
  44647. // Fog
  44648. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44649. // Morph targets
  44650. if (defines.NUM_MORPH_INFLUENCERS) {
  44651. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44652. }
  44653. // image processing
  44654. this._imageProcessingConfiguration.bind(this._activeEffect);
  44655. // Log. depth
  44656. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44657. }
  44658. this._uniformBuffer.update();
  44659. this._afterBind(mesh, this._activeEffect);
  44660. };
  44661. /**
  44662. * Returns the animatable textures.
  44663. * @returns - Array of animatable textures.
  44664. */
  44665. PBRBaseMaterial.prototype.getAnimatables = function () {
  44666. var results = [];
  44667. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44668. results.push(this._albedoTexture);
  44669. }
  44670. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44671. results.push(this._ambientTexture);
  44672. }
  44673. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44674. results.push(this._opacityTexture);
  44675. }
  44676. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44677. results.push(this._reflectionTexture);
  44678. }
  44679. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44680. results.push(this._emissiveTexture);
  44681. }
  44682. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44683. results.push(this._metallicTexture);
  44684. }
  44685. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44686. results.push(this._reflectivityTexture);
  44687. }
  44688. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44689. results.push(this._bumpTexture);
  44690. }
  44691. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44692. results.push(this._lightmapTexture);
  44693. }
  44694. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44695. results.push(this._refractionTexture);
  44696. }
  44697. return results;
  44698. };
  44699. /**
  44700. * Returns the texture used for reflections.
  44701. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44702. */
  44703. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44704. if (this._reflectionTexture) {
  44705. return this._reflectionTexture;
  44706. }
  44707. return this.getScene().environmentTexture;
  44708. };
  44709. /**
  44710. * Returns the texture used for refraction or null if none is used.
  44711. * @returns - Refection texture if present. If no refraction texture and refraction
  44712. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44713. */
  44714. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44715. if (this._refractionTexture) {
  44716. return this._refractionTexture;
  44717. }
  44718. if (this._linkRefractionWithTransparency) {
  44719. return this.getScene().environmentTexture;
  44720. }
  44721. return null;
  44722. };
  44723. /**
  44724. * Disposes the resources of the material.
  44725. * @param forceDisposeEffect - Forces the disposal of effects.
  44726. * @param forceDisposeTextures - Forces the disposal of all textures.
  44727. */
  44728. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44729. if (forceDisposeTextures) {
  44730. if (this._albedoTexture) {
  44731. this._albedoTexture.dispose();
  44732. }
  44733. if (this._ambientTexture) {
  44734. this._ambientTexture.dispose();
  44735. }
  44736. if (this._opacityTexture) {
  44737. this._opacityTexture.dispose();
  44738. }
  44739. if (this._reflectionTexture) {
  44740. this._reflectionTexture.dispose();
  44741. }
  44742. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44743. this._environmentBRDFTexture.dispose();
  44744. }
  44745. if (this._emissiveTexture) {
  44746. this._emissiveTexture.dispose();
  44747. }
  44748. if (this._metallicTexture) {
  44749. this._metallicTexture.dispose();
  44750. }
  44751. if (this._reflectivityTexture) {
  44752. this._reflectivityTexture.dispose();
  44753. }
  44754. if (this._bumpTexture) {
  44755. this._bumpTexture.dispose();
  44756. }
  44757. if (this._lightmapTexture) {
  44758. this._lightmapTexture.dispose();
  44759. }
  44760. if (this._refractionTexture) {
  44761. this._refractionTexture.dispose();
  44762. }
  44763. }
  44764. this._renderTargets.dispose();
  44765. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44766. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44767. }
  44768. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44769. };
  44770. /**
  44771. * Stores the reflectivity values based on metallic roughness workflow.
  44772. */
  44773. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44774. __decorate([
  44775. BABYLON.serializeAsImageProcessingConfiguration()
  44776. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44777. __decorate([
  44778. BABYLON.serialize()
  44779. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44780. __decorate([
  44781. BABYLON.serialize()
  44782. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44783. return PBRBaseMaterial;
  44784. }(BABYLON.PushMaterial));
  44785. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44786. })(BABYLON || (BABYLON = {}));
  44787. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44788. var BABYLON;
  44789. (function (BABYLON) {
  44790. /**
  44791. * The Physically based simple base material of BJS.
  44792. *
  44793. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44794. * It is used as the base class for both the specGloss and metalRough conventions.
  44795. */
  44796. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44797. __extends(PBRBaseSimpleMaterial, _super);
  44798. /**
  44799. * Instantiates a new PBRMaterial instance.
  44800. *
  44801. * @param name The material name
  44802. * @param scene The scene the material will be use in.
  44803. */
  44804. function PBRBaseSimpleMaterial(name, scene) {
  44805. var _this = _super.call(this, name, scene) || this;
  44806. /**
  44807. * Number of Simultaneous lights allowed on the material.
  44808. */
  44809. _this.maxSimultaneousLights = 4;
  44810. /**
  44811. * If sets to true, disables all the lights affecting the material.
  44812. */
  44813. _this.disableLighting = false;
  44814. /**
  44815. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44816. */
  44817. _this.invertNormalMapX = false;
  44818. /**
  44819. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44820. */
  44821. _this.invertNormalMapY = false;
  44822. /**
  44823. * Emissivie color used to self-illuminate the model.
  44824. */
  44825. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44826. /**
  44827. * Occlusion Channel Strenght.
  44828. */
  44829. _this.occlusionStrength = 1.0;
  44830. _this.useLightmapAsShadowmap = false;
  44831. _this._useAlphaFromAlbedoTexture = true;
  44832. _this._useAmbientInGrayScale = true;
  44833. return _this;
  44834. }
  44835. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44836. /**
  44837. * Gets the current double sided mode.
  44838. */
  44839. get: function () {
  44840. return this._twoSidedLighting;
  44841. },
  44842. /**
  44843. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44844. */
  44845. set: function (value) {
  44846. if (this._twoSidedLighting === value) {
  44847. return;
  44848. }
  44849. this._twoSidedLighting = value;
  44850. this.backFaceCulling = !value;
  44851. this._markAllSubMeshesAsTexturesDirty();
  44852. },
  44853. enumerable: true,
  44854. configurable: true
  44855. });
  44856. /**
  44857. * Return the active textures of the material.
  44858. */
  44859. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44860. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44861. if (this.environmentTexture) {
  44862. activeTextures.push(this.environmentTexture);
  44863. }
  44864. if (this.normalTexture) {
  44865. activeTextures.push(this.normalTexture);
  44866. }
  44867. if (this.emissiveTexture) {
  44868. activeTextures.push(this.emissiveTexture);
  44869. }
  44870. if (this.occlusionTexture) {
  44871. activeTextures.push(this.occlusionTexture);
  44872. }
  44873. if (this.lightmapTexture) {
  44874. activeTextures.push(this.lightmapTexture);
  44875. }
  44876. return activeTextures;
  44877. };
  44878. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44879. if (_super.prototype.hasTexture.call(this, texture)) {
  44880. return true;
  44881. }
  44882. if (this.lightmapTexture === texture) {
  44883. return true;
  44884. }
  44885. return false;
  44886. };
  44887. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44888. return "PBRBaseSimpleMaterial";
  44889. };
  44890. __decorate([
  44891. BABYLON.serialize(),
  44892. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44893. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44894. __decorate([
  44895. BABYLON.serialize(),
  44896. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44897. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44898. __decorate([
  44899. BABYLON.serializeAsTexture(),
  44900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44901. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44902. __decorate([
  44903. BABYLON.serialize(),
  44904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44905. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44906. __decorate([
  44907. BABYLON.serialize(),
  44908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44909. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44910. __decorate([
  44911. BABYLON.serializeAsTexture(),
  44912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44913. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44914. __decorate([
  44915. BABYLON.serializeAsColor3("emissive"),
  44916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44917. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44918. __decorate([
  44919. BABYLON.serializeAsTexture(),
  44920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44921. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44922. __decorate([
  44923. BABYLON.serialize(),
  44924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44925. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44926. __decorate([
  44927. BABYLON.serializeAsTexture(),
  44928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44929. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44930. __decorate([
  44931. BABYLON.serialize(),
  44932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44933. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44934. __decorate([
  44935. BABYLON.serialize()
  44936. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44937. __decorate([
  44938. BABYLON.serializeAsTexture(),
  44939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44940. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44941. __decorate([
  44942. BABYLON.serialize(),
  44943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44944. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44945. return PBRBaseSimpleMaterial;
  44946. }(BABYLON.PBRBaseMaterial));
  44947. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44948. })(BABYLON || (BABYLON = {}));
  44949. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44950. var BABYLON;
  44951. (function (BABYLON) {
  44952. /**
  44953. * The Physically based material of BJS.
  44954. *
  44955. * This offers the main features of a standard PBR material.
  44956. * For more information, please refer to the documentation :
  44957. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44958. */
  44959. var PBRMaterial = /** @class */ (function (_super) {
  44960. __extends(PBRMaterial, _super);
  44961. /**
  44962. * Instantiates a new PBRMaterial instance.
  44963. *
  44964. * @param name The material name
  44965. * @param scene The scene the material will be use in.
  44966. */
  44967. function PBRMaterial(name, scene) {
  44968. var _this = _super.call(this, name, scene) || this;
  44969. /**
  44970. * Intensity of the direct lights e.g. the four lights available in your scene.
  44971. * This impacts both the direct diffuse and specular highlights.
  44972. */
  44973. _this.directIntensity = 1.0;
  44974. /**
  44975. * Intensity of the emissive part of the material.
  44976. * This helps controlling the emissive effect without modifying the emissive color.
  44977. */
  44978. _this.emissiveIntensity = 1.0;
  44979. /**
  44980. * Intensity of the environment e.g. how much the environment will light the object
  44981. * either through harmonics for rough material or through the refelction for shiny ones.
  44982. */
  44983. _this.environmentIntensity = 1.0;
  44984. /**
  44985. * This is a special control allowing the reduction of the specular highlights coming from the
  44986. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44987. */
  44988. _this.specularIntensity = 1.0;
  44989. /**
  44990. * Debug Control allowing disabling the bump map on this material.
  44991. */
  44992. _this.disableBumpMap = false;
  44993. /**
  44994. * AKA Occlusion Texture Intensity in other nomenclature.
  44995. */
  44996. _this.ambientTextureStrength = 1.0;
  44997. /**
  44998. * The color of a material in ambient lighting.
  44999. */
  45000. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45001. /**
  45002. * AKA Diffuse Color in other nomenclature.
  45003. */
  45004. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45005. /**
  45006. * AKA Specular Color in other nomenclature.
  45007. */
  45008. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45009. /**
  45010. * The color reflected from the material.
  45011. */
  45012. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45013. /**
  45014. * The color emitted from the material.
  45015. */
  45016. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45017. /**
  45018. * AKA Glossiness in other nomenclature.
  45019. */
  45020. _this.microSurface = 1.0;
  45021. /**
  45022. * source material index of refraction (IOR)' / 'destination material IOR.
  45023. */
  45024. _this.indexOfRefraction = 0.66;
  45025. /**
  45026. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45027. */
  45028. _this.invertRefractionY = false;
  45029. /**
  45030. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45031. * Materials half opaque for instance using refraction could benefit from this control.
  45032. */
  45033. _this.linkRefractionWithTransparency = false;
  45034. _this.useLightmapAsShadowmap = false;
  45035. /**
  45036. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45037. */
  45038. _this.useAlphaFromAlbedoTexture = false;
  45039. /**
  45040. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45041. */
  45042. _this.forceAlphaTest = false;
  45043. /**
  45044. * Defines the alpha limits in alpha test mode.
  45045. */
  45046. _this.alphaCutOff = 0.4;
  45047. /**
  45048. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45049. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45050. */
  45051. _this.useSpecularOverAlpha = true;
  45052. /**
  45053. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45054. */
  45055. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45056. /**
  45057. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45058. */
  45059. _this.useRoughnessFromMetallicTextureAlpha = true;
  45060. /**
  45061. * Specifies if the metallic texture contains the roughness information in its green channel.
  45062. */
  45063. _this.useRoughnessFromMetallicTextureGreen = false;
  45064. /**
  45065. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45066. */
  45067. _this.useMetallnessFromMetallicTextureBlue = false;
  45068. /**
  45069. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45070. */
  45071. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45072. /**
  45073. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45074. */
  45075. _this.useAmbientInGrayScale = false;
  45076. /**
  45077. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45078. * The material will try to infer what glossiness each pixel should be.
  45079. */
  45080. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45081. /**
  45082. * BJS is using an harcoded light falloff based on a manually sets up range.
  45083. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45084. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45085. */
  45086. _this.usePhysicalLightFalloff = true;
  45087. /**
  45088. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45089. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45090. */
  45091. _this.useRadianceOverAlpha = true;
  45092. /**
  45093. * Allows using an object space normal map (instead of tangent space).
  45094. */
  45095. _this.useObjectSpaceNormalMap = false;
  45096. /**
  45097. * Allows using the bump map in parallax mode.
  45098. */
  45099. _this.useParallax = false;
  45100. /**
  45101. * Allows using the bump map in parallax occlusion mode.
  45102. */
  45103. _this.useParallaxOcclusion = false;
  45104. /**
  45105. * Controls the scale bias of the parallax mode.
  45106. */
  45107. _this.parallaxScaleBias = 0.05;
  45108. /**
  45109. * If sets to true, disables all the lights affecting the material.
  45110. */
  45111. _this.disableLighting = false;
  45112. /**
  45113. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45114. */
  45115. _this.forceIrradianceInFragment = false;
  45116. /**
  45117. * Number of Simultaneous lights allowed on the material.
  45118. */
  45119. _this.maxSimultaneousLights = 4;
  45120. /**
  45121. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45122. */
  45123. _this.invertNormalMapX = false;
  45124. /**
  45125. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45126. */
  45127. _this.invertNormalMapY = false;
  45128. /**
  45129. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45130. */
  45131. _this.twoSidedLighting = false;
  45132. /**
  45133. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45134. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45135. */
  45136. _this.useAlphaFresnel = false;
  45137. /**
  45138. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45139. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45140. */
  45141. _this.useLinearAlphaFresnel = false;
  45142. /**
  45143. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45144. * And/Or occlude the blended part.
  45145. */
  45146. _this.environmentBRDFTexture = null;
  45147. /**
  45148. * Force normal to face away from face.
  45149. */
  45150. _this.forceNormalForward = false;
  45151. /**
  45152. * Enables specular anti aliasing in the PBR shader.
  45153. * It will both interacts on the Geometry for analytical and IBL lighting.
  45154. * It also prefilter the roughness map based on the bump values.
  45155. */
  45156. _this.enableSpecularAntiAliasing = false;
  45157. /**
  45158. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45159. * makes the reflect vector face the model (under horizon).
  45160. */
  45161. _this.useHorizonOcclusion = true;
  45162. /**
  45163. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45164. * too much the area relying on ambient texture to define their ambient occlusion.
  45165. */
  45166. _this.useRadianceOcclusion = true;
  45167. /**
  45168. * If set to true, no lighting calculations will be applied.
  45169. */
  45170. _this.unlit = false;
  45171. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45172. return _this;
  45173. }
  45174. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45175. /**
  45176. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45177. */
  45178. get: function () {
  45179. return this._PBRMATERIAL_OPAQUE;
  45180. },
  45181. enumerable: true,
  45182. configurable: true
  45183. });
  45184. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45185. /**
  45186. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45187. */
  45188. get: function () {
  45189. return this._PBRMATERIAL_ALPHATEST;
  45190. },
  45191. enumerable: true,
  45192. configurable: true
  45193. });
  45194. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45195. /**
  45196. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45197. */
  45198. get: function () {
  45199. return this._PBRMATERIAL_ALPHABLEND;
  45200. },
  45201. enumerable: true,
  45202. configurable: true
  45203. });
  45204. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45205. /**
  45206. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45207. * They are also discarded below the alpha cutoff threshold to improve performances.
  45208. */
  45209. get: function () {
  45210. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45211. },
  45212. enumerable: true,
  45213. configurable: true
  45214. });
  45215. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45216. /**
  45217. * Gets the image processing configuration used either in this material.
  45218. */
  45219. get: function () {
  45220. return this._imageProcessingConfiguration;
  45221. },
  45222. /**
  45223. * Sets the Default image processing configuration used either in the this material.
  45224. *
  45225. * If sets to null, the scene one is in use.
  45226. */
  45227. set: function (value) {
  45228. this._attachImageProcessingConfiguration(value);
  45229. // Ensure the effect will be rebuilt.
  45230. this._markAllSubMeshesAsTexturesDirty();
  45231. },
  45232. enumerable: true,
  45233. configurable: true
  45234. });
  45235. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45236. /**
  45237. * Gets wether the color curves effect is enabled.
  45238. */
  45239. get: function () {
  45240. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45241. },
  45242. /**
  45243. * Sets wether the color curves effect is enabled.
  45244. */
  45245. set: function (value) {
  45246. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45247. },
  45248. enumerable: true,
  45249. configurable: true
  45250. });
  45251. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45252. /**
  45253. * Gets wether the color grading effect is enabled.
  45254. */
  45255. get: function () {
  45256. return this.imageProcessingConfiguration.colorGradingEnabled;
  45257. },
  45258. /**
  45259. * Gets wether the color grading effect is enabled.
  45260. */
  45261. set: function (value) {
  45262. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45263. },
  45264. enumerable: true,
  45265. configurable: true
  45266. });
  45267. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45268. /**
  45269. * Gets wether tonemapping is enabled or not.
  45270. */
  45271. get: function () {
  45272. return this._imageProcessingConfiguration.toneMappingEnabled;
  45273. },
  45274. /**
  45275. * Sets wether tonemapping is enabled or not
  45276. */
  45277. set: function (value) {
  45278. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45279. },
  45280. enumerable: true,
  45281. configurable: true
  45282. });
  45283. ;
  45284. ;
  45285. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45286. /**
  45287. * The camera exposure used on this material.
  45288. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45289. * This corresponds to a photographic exposure.
  45290. */
  45291. get: function () {
  45292. return this._imageProcessingConfiguration.exposure;
  45293. },
  45294. /**
  45295. * The camera exposure used on this material.
  45296. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45297. * This corresponds to a photographic exposure.
  45298. */
  45299. set: function (value) {
  45300. this._imageProcessingConfiguration.exposure = value;
  45301. },
  45302. enumerable: true,
  45303. configurable: true
  45304. });
  45305. ;
  45306. ;
  45307. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45308. /**
  45309. * Gets The camera contrast used on this material.
  45310. */
  45311. get: function () {
  45312. return this._imageProcessingConfiguration.contrast;
  45313. },
  45314. /**
  45315. * Sets The camera contrast used on this material.
  45316. */
  45317. set: function (value) {
  45318. this._imageProcessingConfiguration.contrast = value;
  45319. },
  45320. enumerable: true,
  45321. configurable: true
  45322. });
  45323. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45324. /**
  45325. * Gets the Color Grading 2D Lookup Texture.
  45326. */
  45327. get: function () {
  45328. return this._imageProcessingConfiguration.colorGradingTexture;
  45329. },
  45330. /**
  45331. * Sets the Color Grading 2D Lookup Texture.
  45332. */
  45333. set: function (value) {
  45334. this._imageProcessingConfiguration.colorGradingTexture = value;
  45335. },
  45336. enumerable: true,
  45337. configurable: true
  45338. });
  45339. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45340. /**
  45341. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45342. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45343. * 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;
  45344. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45345. */
  45346. get: function () {
  45347. return this._imageProcessingConfiguration.colorCurves;
  45348. },
  45349. /**
  45350. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45351. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45352. * 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;
  45353. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45354. */
  45355. set: function (value) {
  45356. this._imageProcessingConfiguration.colorCurves = value;
  45357. },
  45358. enumerable: true,
  45359. configurable: true
  45360. });
  45361. /**
  45362. * Returns the name of this material class.
  45363. */
  45364. PBRMaterial.prototype.getClassName = function () {
  45365. return "PBRMaterial";
  45366. };
  45367. /**
  45368. * Returns an array of the actively used textures.
  45369. * @returns - Array of BaseTextures
  45370. */
  45371. PBRMaterial.prototype.getActiveTextures = function () {
  45372. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45373. if (this._albedoTexture) {
  45374. activeTextures.push(this._albedoTexture);
  45375. }
  45376. if (this._ambientTexture) {
  45377. activeTextures.push(this._ambientTexture);
  45378. }
  45379. if (this._opacityTexture) {
  45380. activeTextures.push(this._opacityTexture);
  45381. }
  45382. if (this._reflectionTexture) {
  45383. activeTextures.push(this._reflectionTexture);
  45384. }
  45385. if (this._emissiveTexture) {
  45386. activeTextures.push(this._emissiveTexture);
  45387. }
  45388. if (this._reflectivityTexture) {
  45389. activeTextures.push(this._reflectivityTexture);
  45390. }
  45391. if (this._metallicTexture) {
  45392. activeTextures.push(this._metallicTexture);
  45393. }
  45394. if (this._microSurfaceTexture) {
  45395. activeTextures.push(this._microSurfaceTexture);
  45396. }
  45397. if (this._bumpTexture) {
  45398. activeTextures.push(this._bumpTexture);
  45399. }
  45400. if (this._lightmapTexture) {
  45401. activeTextures.push(this._lightmapTexture);
  45402. }
  45403. if (this._refractionTexture) {
  45404. activeTextures.push(this._refractionTexture);
  45405. }
  45406. return activeTextures;
  45407. };
  45408. /**
  45409. * Checks to see if a texture is used in the material.
  45410. * @param texture - Base texture to use.
  45411. * @returns - Boolean specifying if a texture is used in the material.
  45412. */
  45413. PBRMaterial.prototype.hasTexture = function (texture) {
  45414. if (_super.prototype.hasTexture.call(this, texture)) {
  45415. return true;
  45416. }
  45417. if (this._albedoTexture === texture) {
  45418. return true;
  45419. }
  45420. if (this._ambientTexture === texture) {
  45421. return true;
  45422. }
  45423. if (this._opacityTexture === texture) {
  45424. return true;
  45425. }
  45426. if (this._reflectionTexture === texture) {
  45427. return true;
  45428. }
  45429. if (this._reflectivityTexture === texture) {
  45430. return true;
  45431. }
  45432. if (this._metallicTexture === texture) {
  45433. return true;
  45434. }
  45435. if (this._microSurfaceTexture === texture) {
  45436. return true;
  45437. }
  45438. if (this._bumpTexture === texture) {
  45439. return true;
  45440. }
  45441. if (this._lightmapTexture === texture) {
  45442. return true;
  45443. }
  45444. if (this._refractionTexture === texture) {
  45445. return true;
  45446. }
  45447. return false;
  45448. };
  45449. /**
  45450. * Makes a duplicate of the current material.
  45451. * @param name - name to use for the new material.
  45452. */
  45453. PBRMaterial.prototype.clone = function (name) {
  45454. var _this = this;
  45455. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45456. clone.id = name;
  45457. clone.name = name;
  45458. return clone;
  45459. };
  45460. /**
  45461. * Serializes this PBR Material.
  45462. * @returns - An object with the serialized material.
  45463. */
  45464. PBRMaterial.prototype.serialize = function () {
  45465. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45466. serializationObject.customType = "BABYLON.PBRMaterial";
  45467. return serializationObject;
  45468. };
  45469. // Statics
  45470. /**
  45471. * Parses a PBR Material from a serialized object.
  45472. * @param source - Serialized object.
  45473. * @param scene - BJS scene instance.
  45474. * @param rootUrl - url for the scene object
  45475. * @returns - PBRMaterial
  45476. */
  45477. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45478. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45479. };
  45480. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45481. /**
  45482. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45483. */
  45484. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45485. /**
  45486. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45487. */
  45488. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45489. /**
  45490. * 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.
  45491. * They are also discarded below the alpha cutoff threshold to improve performances.
  45492. */
  45493. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45494. __decorate([
  45495. BABYLON.serialize(),
  45496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45497. ], PBRMaterial.prototype, "directIntensity", void 0);
  45498. __decorate([
  45499. BABYLON.serialize(),
  45500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45501. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45502. __decorate([
  45503. BABYLON.serialize(),
  45504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45505. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45506. __decorate([
  45507. BABYLON.serialize(),
  45508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45509. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45510. __decorate([
  45511. BABYLON.serialize(),
  45512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45513. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45514. __decorate([
  45515. BABYLON.serializeAsTexture(),
  45516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45517. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45518. __decorate([
  45519. BABYLON.serializeAsTexture(),
  45520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45521. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45522. __decorate([
  45523. BABYLON.serialize(),
  45524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45525. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45526. __decorate([
  45527. BABYLON.serializeAsTexture(),
  45528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45529. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45530. __decorate([
  45531. BABYLON.serializeAsTexture(),
  45532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45533. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45534. __decorate([
  45535. BABYLON.serializeAsTexture(),
  45536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45537. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45538. __decorate([
  45539. BABYLON.serializeAsTexture(),
  45540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45541. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45542. __decorate([
  45543. BABYLON.serializeAsTexture(),
  45544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45545. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45546. __decorate([
  45547. BABYLON.serialize(),
  45548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45549. ], PBRMaterial.prototype, "metallic", void 0);
  45550. __decorate([
  45551. BABYLON.serialize(),
  45552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45553. ], PBRMaterial.prototype, "roughness", void 0);
  45554. __decorate([
  45555. BABYLON.serializeAsTexture(),
  45556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45557. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45558. __decorate([
  45559. BABYLON.serializeAsTexture(),
  45560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45561. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45562. __decorate([
  45563. BABYLON.serializeAsTexture(),
  45564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45565. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45566. __decorate([
  45567. BABYLON.serializeAsTexture(),
  45568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45569. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45570. __decorate([
  45571. BABYLON.serializeAsColor3("ambient"),
  45572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45573. ], PBRMaterial.prototype, "ambientColor", void 0);
  45574. __decorate([
  45575. BABYLON.serializeAsColor3("albedo"),
  45576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45577. ], PBRMaterial.prototype, "albedoColor", void 0);
  45578. __decorate([
  45579. BABYLON.serializeAsColor3("reflectivity"),
  45580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45581. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45582. __decorate([
  45583. BABYLON.serializeAsColor3("reflection"),
  45584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45585. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45586. __decorate([
  45587. BABYLON.serializeAsColor3("emissive"),
  45588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45589. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45590. __decorate([
  45591. BABYLON.serialize(),
  45592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45593. ], PBRMaterial.prototype, "microSurface", void 0);
  45594. __decorate([
  45595. BABYLON.serialize(),
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45597. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45598. __decorate([
  45599. BABYLON.serialize(),
  45600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45601. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45602. __decorate([
  45603. BABYLON.serialize(),
  45604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45605. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45606. __decorate([
  45607. BABYLON.serialize(),
  45608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45609. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45610. __decorate([
  45611. BABYLON.serialize(),
  45612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45613. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45614. __decorate([
  45615. BABYLON.serialize(),
  45616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45617. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45618. __decorate([
  45619. BABYLON.serialize(),
  45620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45621. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45622. __decorate([
  45623. BABYLON.serialize(),
  45624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45625. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45626. __decorate([
  45627. BABYLON.serialize(),
  45628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45629. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45630. __decorate([
  45631. BABYLON.serialize(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45633. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45634. __decorate([
  45635. BABYLON.serialize(),
  45636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45637. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45638. __decorate([
  45639. BABYLON.serialize(),
  45640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45641. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45642. __decorate([
  45643. BABYLON.serialize(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45645. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45646. __decorate([
  45647. BABYLON.serialize(),
  45648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45649. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45650. __decorate([
  45651. BABYLON.serialize(),
  45652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45653. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45654. __decorate([
  45655. BABYLON.serialize(),
  45656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45657. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45658. __decorate([
  45659. BABYLON.serialize(),
  45660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45661. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45662. __decorate([
  45663. BABYLON.serialize(),
  45664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45665. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45666. __decorate([
  45667. BABYLON.serialize(),
  45668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45669. ], PBRMaterial.prototype, "useParallax", void 0);
  45670. __decorate([
  45671. BABYLON.serialize(),
  45672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45673. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45674. __decorate([
  45675. BABYLON.serialize(),
  45676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45677. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45678. __decorate([
  45679. BABYLON.serialize(),
  45680. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45681. ], PBRMaterial.prototype, "disableLighting", void 0);
  45682. __decorate([
  45683. BABYLON.serialize(),
  45684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45685. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45686. __decorate([
  45687. BABYLON.serialize(),
  45688. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45689. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45690. __decorate([
  45691. BABYLON.serialize(),
  45692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45693. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45694. __decorate([
  45695. BABYLON.serialize(),
  45696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45697. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45698. __decorate([
  45699. BABYLON.serialize(),
  45700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45701. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45702. __decorate([
  45703. BABYLON.serialize(),
  45704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45705. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45706. __decorate([
  45707. BABYLON.serialize(),
  45708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45709. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45710. __decorate([
  45711. BABYLON.serializeAsTexture(),
  45712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45713. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45714. __decorate([
  45715. BABYLON.serialize(),
  45716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45717. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45718. __decorate([
  45719. BABYLON.serialize(),
  45720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45721. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45722. __decorate([
  45723. BABYLON.serialize(),
  45724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45725. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45726. __decorate([
  45727. BABYLON.serialize(),
  45728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45729. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45730. __decorate([
  45731. BABYLON.serialize(),
  45732. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45733. ], PBRMaterial.prototype, "unlit", void 0);
  45734. return PBRMaterial;
  45735. }(BABYLON.PBRBaseMaterial));
  45736. BABYLON.PBRMaterial = PBRMaterial;
  45737. })(BABYLON || (BABYLON = {}));
  45738. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45739. var BABYLON;
  45740. (function (BABYLON) {
  45741. /**
  45742. * The PBR material of BJS following the metal roughness convention.
  45743. *
  45744. * This fits to the PBR convention in the GLTF definition:
  45745. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45746. */
  45747. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45748. __extends(PBRMetallicRoughnessMaterial, _super);
  45749. /**
  45750. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45751. *
  45752. * @param name The material name
  45753. * @param scene The scene the material will be use in.
  45754. */
  45755. function PBRMetallicRoughnessMaterial(name, scene) {
  45756. var _this = _super.call(this, name, scene) || this;
  45757. _this._useRoughnessFromMetallicTextureAlpha = false;
  45758. _this._useRoughnessFromMetallicTextureGreen = true;
  45759. _this._useMetallnessFromMetallicTextureBlue = true;
  45760. _this.metallic = 1.0;
  45761. _this.roughness = 1.0;
  45762. return _this;
  45763. }
  45764. /**
  45765. * Return the currrent class name of the material.
  45766. */
  45767. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45768. return "PBRMetallicRoughnessMaterial";
  45769. };
  45770. /**
  45771. * Return the active textures of the material.
  45772. */
  45773. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45774. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45775. if (this.baseTexture) {
  45776. activeTextures.push(this.baseTexture);
  45777. }
  45778. if (this.metallicRoughnessTexture) {
  45779. activeTextures.push(this.metallicRoughnessTexture);
  45780. }
  45781. return activeTextures;
  45782. };
  45783. /**
  45784. * Checks to see if a texture is used in the material.
  45785. * @param texture - Base texture to use.
  45786. * @returns - Boolean specifying if a texture is used in the material.
  45787. */
  45788. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45789. if (_super.prototype.hasTexture.call(this, texture)) {
  45790. return true;
  45791. }
  45792. if (this.baseTexture === texture) {
  45793. return true;
  45794. }
  45795. if (this.metallicRoughnessTexture === texture) {
  45796. return true;
  45797. }
  45798. return false;
  45799. };
  45800. /**
  45801. * Makes a duplicate of the current material.
  45802. * @param name - name to use for the new material.
  45803. */
  45804. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45805. var _this = this;
  45806. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45807. clone.id = name;
  45808. clone.name = name;
  45809. return clone;
  45810. };
  45811. /**
  45812. * Serialize the material to a parsable JSON object.
  45813. */
  45814. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45815. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45816. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45817. return serializationObject;
  45818. };
  45819. /**
  45820. * Parses a JSON object correponding to the serialize function.
  45821. */
  45822. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45823. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45824. };
  45825. __decorate([
  45826. BABYLON.serializeAsColor3(),
  45827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45828. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45829. __decorate([
  45830. BABYLON.serializeAsTexture(),
  45831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45832. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45833. __decorate([
  45834. BABYLON.serialize(),
  45835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45836. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45837. __decorate([
  45838. BABYLON.serialize(),
  45839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45840. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45841. __decorate([
  45842. BABYLON.serializeAsTexture(),
  45843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45844. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45845. return PBRMetallicRoughnessMaterial;
  45846. }(BABYLON.PBRBaseSimpleMaterial));
  45847. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45848. })(BABYLON || (BABYLON = {}));
  45849. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45850. var BABYLON;
  45851. (function (BABYLON) {
  45852. /**
  45853. * The PBR material of BJS following the specular glossiness convention.
  45854. *
  45855. * This fits to the PBR convention in the GLTF definition:
  45856. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45857. */
  45858. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45859. __extends(PBRSpecularGlossinessMaterial, _super);
  45860. /**
  45861. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45862. *
  45863. * @param name The material name
  45864. * @param scene The scene the material will be use in.
  45865. */
  45866. function PBRSpecularGlossinessMaterial(name, scene) {
  45867. var _this = _super.call(this, name, scene) || this;
  45868. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45869. return _this;
  45870. }
  45871. /**
  45872. * Return the currrent class name of the material.
  45873. */
  45874. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45875. return "PBRSpecularGlossinessMaterial";
  45876. };
  45877. /**
  45878. * Return the active textures of the material.
  45879. */
  45880. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45881. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45882. if (this.diffuseTexture) {
  45883. activeTextures.push(this.diffuseTexture);
  45884. }
  45885. if (this.specularGlossinessTexture) {
  45886. activeTextures.push(this.specularGlossinessTexture);
  45887. }
  45888. return activeTextures;
  45889. };
  45890. /**
  45891. * Checks to see if a texture is used in the material.
  45892. * @param texture - Base texture to use.
  45893. * @returns - Boolean specifying if a texture is used in the material.
  45894. */
  45895. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45896. if (_super.prototype.hasTexture.call(this, texture)) {
  45897. return true;
  45898. }
  45899. if (this.diffuseTexture === texture) {
  45900. return true;
  45901. }
  45902. if (this.specularGlossinessTexture === texture) {
  45903. return true;
  45904. }
  45905. return false;
  45906. };
  45907. /**
  45908. * Makes a duplicate of the current material.
  45909. * @param name - name to use for the new material.
  45910. */
  45911. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45912. var _this = this;
  45913. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45914. clone.id = name;
  45915. clone.name = name;
  45916. return clone;
  45917. };
  45918. /**
  45919. * Serialize the material to a parsable JSON object.
  45920. */
  45921. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45922. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45923. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45924. return serializationObject;
  45925. };
  45926. /**
  45927. * Parses a JSON object correponding to the serialize function.
  45928. */
  45929. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45930. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45931. };
  45932. __decorate([
  45933. BABYLON.serializeAsColor3("diffuse"),
  45934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45935. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45936. __decorate([
  45937. BABYLON.serializeAsTexture(),
  45938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45939. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45940. __decorate([
  45941. BABYLON.serializeAsColor3("specular"),
  45942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45943. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45944. __decorate([
  45945. BABYLON.serialize(),
  45946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45947. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45948. __decorate([
  45949. BABYLON.serializeAsTexture(),
  45950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45951. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45952. return PBRSpecularGlossinessMaterial;
  45953. }(BABYLON.PBRBaseSimpleMaterial));
  45954. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45955. })(BABYLON || (BABYLON = {}));
  45956. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45957. var BABYLON;
  45958. (function (BABYLON) {
  45959. BABYLON.CameraInputTypes = {};
  45960. var CameraInputsManager = /** @class */ (function () {
  45961. function CameraInputsManager(camera) {
  45962. this.attached = {};
  45963. this.camera = camera;
  45964. this.checkInputs = function () { };
  45965. }
  45966. /**
  45967. * Add an input method to a camera.
  45968. * builtin inputs example: camera.inputs.addGamepad();
  45969. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45970. * @param input camera input method
  45971. */
  45972. CameraInputsManager.prototype.add = function (input) {
  45973. var type = input.getSimpleName();
  45974. if (this.attached[type]) {
  45975. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45976. return;
  45977. }
  45978. this.attached[type] = input;
  45979. input.camera = this.camera;
  45980. //for checkInputs, we are dynamically creating a function
  45981. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45982. if (input.checkInputs) {
  45983. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45984. }
  45985. if (this.attachedElement) {
  45986. input.attachControl(this.attachedElement);
  45987. }
  45988. };
  45989. /**
  45990. * Remove a specific input method from a camera
  45991. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45992. * @param inputToRemove camera input method
  45993. */
  45994. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45995. for (var cam in this.attached) {
  45996. var input = this.attached[cam];
  45997. if (input === inputToRemove) {
  45998. input.detachControl(this.attachedElement);
  45999. input.camera = null;
  46000. delete this.attached[cam];
  46001. this.rebuildInputCheck();
  46002. }
  46003. }
  46004. };
  46005. CameraInputsManager.prototype.removeByType = function (inputType) {
  46006. for (var cam in this.attached) {
  46007. var input = this.attached[cam];
  46008. if (input.getClassName() === inputType) {
  46009. input.detachControl(this.attachedElement);
  46010. input.camera = null;
  46011. delete this.attached[cam];
  46012. this.rebuildInputCheck();
  46013. }
  46014. }
  46015. };
  46016. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46017. var current = this.checkInputs;
  46018. return function () {
  46019. current();
  46020. fn();
  46021. };
  46022. };
  46023. CameraInputsManager.prototype.attachInput = function (input) {
  46024. if (this.attachedElement) {
  46025. input.attachControl(this.attachedElement, this.noPreventDefault);
  46026. }
  46027. };
  46028. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46029. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46030. if (this.attachedElement) {
  46031. return;
  46032. }
  46033. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46034. this.attachedElement = element;
  46035. this.noPreventDefault = noPreventDefault;
  46036. for (var cam in this.attached) {
  46037. this.attached[cam].attachControl(element, noPreventDefault);
  46038. }
  46039. };
  46040. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46041. if (disconnect === void 0) { disconnect = false; }
  46042. if (this.attachedElement !== element) {
  46043. return;
  46044. }
  46045. for (var cam in this.attached) {
  46046. this.attached[cam].detachControl(element);
  46047. if (disconnect) {
  46048. this.attached[cam].camera = null;
  46049. }
  46050. }
  46051. this.attachedElement = null;
  46052. };
  46053. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46054. this.checkInputs = function () { };
  46055. for (var cam in this.attached) {
  46056. var input = this.attached[cam];
  46057. if (input.checkInputs) {
  46058. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46059. }
  46060. }
  46061. };
  46062. /**
  46063. * Remove all attached input methods from a camera
  46064. */
  46065. CameraInputsManager.prototype.clear = function () {
  46066. if (this.attachedElement) {
  46067. this.detachElement(this.attachedElement, true);
  46068. }
  46069. this.attached = {};
  46070. this.attachedElement = null;
  46071. this.checkInputs = function () { };
  46072. };
  46073. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46074. var inputs = {};
  46075. for (var cam in this.attached) {
  46076. var input = this.attached[cam];
  46077. var res = BABYLON.SerializationHelper.Serialize(input);
  46078. inputs[input.getClassName()] = res;
  46079. }
  46080. serializedCamera.inputsmgr = inputs;
  46081. };
  46082. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46083. var parsedInputs = parsedCamera.inputsmgr;
  46084. if (parsedInputs) {
  46085. this.clear();
  46086. for (var n in parsedInputs) {
  46087. var construct = BABYLON.CameraInputTypes[n];
  46088. if (construct) {
  46089. var parsedinput = parsedInputs[n];
  46090. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46091. this.add(input);
  46092. }
  46093. }
  46094. }
  46095. else {
  46096. //2016-03-08 this part is for managing backward compatibility
  46097. for (var n in this.attached) {
  46098. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46099. if (construct) {
  46100. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46101. this.remove(this.attached[n]);
  46102. this.add(input);
  46103. }
  46104. }
  46105. }
  46106. };
  46107. return CameraInputsManager;
  46108. }());
  46109. BABYLON.CameraInputsManager = CameraInputsManager;
  46110. })(BABYLON || (BABYLON = {}));
  46111. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46112. var BABYLON;
  46113. (function (BABYLON) {
  46114. var TargetCamera = /** @class */ (function (_super) {
  46115. __extends(TargetCamera, _super);
  46116. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46117. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46118. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46119. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46120. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46121. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46122. _this.speed = 2.0;
  46123. _this.noRotationConstraint = false;
  46124. _this.lockedTarget = null;
  46125. _this._currentTarget = BABYLON.Vector3.Zero();
  46126. _this._viewMatrix = BABYLON.Matrix.Zero();
  46127. _this._camMatrix = BABYLON.Matrix.Zero();
  46128. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46129. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46130. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46131. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46132. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46133. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46134. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46135. return _this;
  46136. }
  46137. TargetCamera.prototype.getFrontPosition = function (distance) {
  46138. this.getWorldMatrix();
  46139. var direction = this.getTarget().subtract(this.position);
  46140. direction.normalize();
  46141. direction.scaleInPlace(distance);
  46142. return this.globalPosition.add(direction);
  46143. };
  46144. TargetCamera.prototype._getLockedTargetPosition = function () {
  46145. if (!this.lockedTarget) {
  46146. return null;
  46147. }
  46148. if (this.lockedTarget.absolutePosition) {
  46149. this.lockedTarget.computeWorldMatrix();
  46150. }
  46151. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46152. };
  46153. TargetCamera.prototype.storeState = function () {
  46154. this._storedPosition = this.position.clone();
  46155. this._storedRotation = this.rotation.clone();
  46156. if (this.rotationQuaternion) {
  46157. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46158. }
  46159. return _super.prototype.storeState.call(this);
  46160. };
  46161. /**
  46162. * Restored camera state. You must call storeState() first
  46163. */
  46164. TargetCamera.prototype._restoreStateValues = function () {
  46165. if (!_super.prototype._restoreStateValues.call(this)) {
  46166. return false;
  46167. }
  46168. this.position = this._storedPosition.clone();
  46169. this.rotation = this._storedRotation.clone();
  46170. if (this.rotationQuaternion) {
  46171. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46172. }
  46173. this.cameraDirection.copyFromFloats(0, 0, 0);
  46174. this.cameraRotation.copyFromFloats(0, 0);
  46175. return true;
  46176. };
  46177. // Cache
  46178. TargetCamera.prototype._initCache = function () {
  46179. _super.prototype._initCache.call(this);
  46180. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46181. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46182. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46183. };
  46184. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46185. if (!ignoreParentClass) {
  46186. _super.prototype._updateCache.call(this);
  46187. }
  46188. var lockedTargetPosition = this._getLockedTargetPosition();
  46189. if (!lockedTargetPosition) {
  46190. this._cache.lockedTarget = null;
  46191. }
  46192. else {
  46193. if (!this._cache.lockedTarget) {
  46194. this._cache.lockedTarget = lockedTargetPosition.clone();
  46195. }
  46196. else {
  46197. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46198. }
  46199. }
  46200. this._cache.rotation.copyFrom(this.rotation);
  46201. if (this.rotationQuaternion)
  46202. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46203. };
  46204. // Synchronized
  46205. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46206. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46207. return false;
  46208. }
  46209. var lockedTargetPosition = this._getLockedTargetPosition();
  46210. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46211. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46212. };
  46213. // Methods
  46214. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46215. var engine = this.getEngine();
  46216. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46217. };
  46218. // Target
  46219. TargetCamera.prototype.setTarget = function (target) {
  46220. this.upVector.normalize();
  46221. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46222. this._camMatrix.invert();
  46223. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46224. var vDir = target.subtract(this.position);
  46225. if (vDir.x >= 0.0) {
  46226. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46227. }
  46228. else {
  46229. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46230. }
  46231. this.rotation.z = 0;
  46232. if (isNaN(this.rotation.x)) {
  46233. this.rotation.x = 0;
  46234. }
  46235. if (isNaN(this.rotation.y)) {
  46236. this.rotation.y = 0;
  46237. }
  46238. if (isNaN(this.rotation.z)) {
  46239. this.rotation.z = 0;
  46240. }
  46241. if (this.rotationQuaternion) {
  46242. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46243. }
  46244. };
  46245. /**
  46246. * Return the current target position of the camera. This value is expressed in local space.
  46247. */
  46248. TargetCamera.prototype.getTarget = function () {
  46249. return this._currentTarget;
  46250. };
  46251. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46252. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46253. };
  46254. TargetCamera.prototype._updatePosition = function () {
  46255. if (this.parent) {
  46256. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46257. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46258. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46259. return;
  46260. }
  46261. this.position.addInPlace(this.cameraDirection);
  46262. };
  46263. TargetCamera.prototype._checkInputs = function () {
  46264. var needToMove = this._decideIfNeedsToMove();
  46265. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46266. // Move
  46267. if (needToMove) {
  46268. this._updatePosition();
  46269. }
  46270. // Rotate
  46271. if (needToRotate) {
  46272. this.rotation.x += this.cameraRotation.x;
  46273. this.rotation.y += this.cameraRotation.y;
  46274. //rotate, if quaternion is set and rotation was used
  46275. if (this.rotationQuaternion) {
  46276. var len = this.rotation.lengthSquared();
  46277. if (len) {
  46278. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46279. }
  46280. }
  46281. if (!this.noRotationConstraint) {
  46282. var limit = (Math.PI / 2) * 0.95;
  46283. if (this.rotation.x > limit)
  46284. this.rotation.x = limit;
  46285. if (this.rotation.x < -limit)
  46286. this.rotation.x = -limit;
  46287. }
  46288. }
  46289. // Inertia
  46290. if (needToMove) {
  46291. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46292. this.cameraDirection.x = 0;
  46293. }
  46294. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46295. this.cameraDirection.y = 0;
  46296. }
  46297. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46298. this.cameraDirection.z = 0;
  46299. }
  46300. this.cameraDirection.scaleInPlace(this.inertia);
  46301. }
  46302. if (needToRotate) {
  46303. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46304. this.cameraRotation.x = 0;
  46305. }
  46306. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46307. this.cameraRotation.y = 0;
  46308. }
  46309. this.cameraRotation.scaleInPlace(this.inertia);
  46310. }
  46311. _super.prototype._checkInputs.call(this);
  46312. };
  46313. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46314. if (this.rotationQuaternion) {
  46315. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46316. }
  46317. else {
  46318. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46319. }
  46320. //update the up vector!
  46321. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46322. };
  46323. TargetCamera.prototype._getViewMatrix = function () {
  46324. if (this.lockedTarget) {
  46325. this.setTarget(this._getLockedTargetPosition());
  46326. }
  46327. // Compute
  46328. this._updateCameraRotationMatrix();
  46329. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46330. // Computing target and final matrix
  46331. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46332. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46333. return this._viewMatrix;
  46334. };
  46335. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46336. if (this.parent) {
  46337. var parentWorldMatrix = this.parent.getWorldMatrix();
  46338. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46339. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46340. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46341. this._markSyncedWithParent();
  46342. }
  46343. else {
  46344. this._globalPosition.copyFrom(this.position);
  46345. this._globalCurrentTarget.copyFrom(target);
  46346. this._globalCurrentUpVector.copyFrom(up);
  46347. }
  46348. if (this.getScene().useRightHandedSystem) {
  46349. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46350. }
  46351. else {
  46352. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46353. }
  46354. };
  46355. /**
  46356. * @override
  46357. * Override Camera.createRigCamera
  46358. */
  46359. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46360. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46361. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46362. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46363. if (!this.rotationQuaternion) {
  46364. this.rotationQuaternion = new BABYLON.Quaternion();
  46365. }
  46366. rigCamera._cameraRigParams = {};
  46367. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46368. }
  46369. return rigCamera;
  46370. }
  46371. return null;
  46372. };
  46373. /**
  46374. * @override
  46375. * Override Camera._updateRigCameras
  46376. */
  46377. TargetCamera.prototype._updateRigCameras = function () {
  46378. var camLeft = this._rigCameras[0];
  46379. var camRight = this._rigCameras[1];
  46380. switch (this.cameraRigMode) {
  46381. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46382. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46383. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46384. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46385. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46386. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46387. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46388. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46389. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46390. camLeft.setTarget(this.getTarget());
  46391. camRight.setTarget(this.getTarget());
  46392. break;
  46393. case BABYLON.Camera.RIG_MODE_VR:
  46394. if (camLeft.rotationQuaternion) {
  46395. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46396. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46397. }
  46398. else {
  46399. camLeft.rotation.copyFrom(this.rotation);
  46400. camRight.rotation.copyFrom(this.rotation);
  46401. }
  46402. camLeft.position.copyFrom(this.position);
  46403. camRight.position.copyFrom(this.position);
  46404. break;
  46405. }
  46406. _super.prototype._updateRigCameras.call(this);
  46407. };
  46408. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46409. if (!this._rigCamTransformMatrix) {
  46410. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46411. }
  46412. var target = this.getTarget();
  46413. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46414. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46415. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46416. };
  46417. TargetCamera.prototype.getClassName = function () {
  46418. return "TargetCamera";
  46419. };
  46420. __decorate([
  46421. BABYLON.serializeAsVector3()
  46422. ], TargetCamera.prototype, "rotation", void 0);
  46423. __decorate([
  46424. BABYLON.serialize()
  46425. ], TargetCamera.prototype, "speed", void 0);
  46426. __decorate([
  46427. BABYLON.serializeAsMeshReference("lockedTargetId")
  46428. ], TargetCamera.prototype, "lockedTarget", void 0);
  46429. return TargetCamera;
  46430. }(BABYLON.Camera));
  46431. BABYLON.TargetCamera = TargetCamera;
  46432. })(BABYLON || (BABYLON = {}));
  46433. //# sourceMappingURL=babylon.targetCamera.js.map
  46434. var BABYLON;
  46435. (function (BABYLON) {
  46436. var FreeCameraMouseInput = /** @class */ (function () {
  46437. function FreeCameraMouseInput(touchEnabled) {
  46438. if (touchEnabled === void 0) { touchEnabled = true; }
  46439. this.touchEnabled = touchEnabled;
  46440. this.buttons = [0, 1, 2];
  46441. this.angularSensibility = 2000.0;
  46442. this.previousPosition = null;
  46443. }
  46444. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46445. var _this = this;
  46446. var engine = this.camera.getEngine();
  46447. if (!this._pointerInput) {
  46448. this._pointerInput = function (p, s) {
  46449. var evt = p.event;
  46450. if (engine.isInVRExclusivePointerMode) {
  46451. return;
  46452. }
  46453. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46454. return;
  46455. }
  46456. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46457. return;
  46458. }
  46459. var srcElement = (evt.srcElement || evt.target);
  46460. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46461. try {
  46462. srcElement.setPointerCapture(evt.pointerId);
  46463. }
  46464. catch (e) {
  46465. //Nothing to do with the error. Execution will continue.
  46466. }
  46467. _this.previousPosition = {
  46468. x: evt.clientX,
  46469. y: evt.clientY
  46470. };
  46471. if (!noPreventDefault) {
  46472. evt.preventDefault();
  46473. element.focus();
  46474. }
  46475. }
  46476. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46477. try {
  46478. srcElement.releasePointerCapture(evt.pointerId);
  46479. }
  46480. catch (e) {
  46481. //Nothing to do with the error.
  46482. }
  46483. _this.previousPosition = null;
  46484. if (!noPreventDefault) {
  46485. evt.preventDefault();
  46486. }
  46487. }
  46488. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46489. if (!_this.previousPosition || engine.isPointerLock) {
  46490. return;
  46491. }
  46492. var offsetX = evt.clientX - _this.previousPosition.x;
  46493. if (_this.camera.getScene().useRightHandedSystem)
  46494. offsetX *= -1;
  46495. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46496. offsetX *= -1;
  46497. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46498. var offsetY = evt.clientY - _this.previousPosition.y;
  46499. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46500. _this.previousPosition = {
  46501. x: evt.clientX,
  46502. y: evt.clientY
  46503. };
  46504. if (!noPreventDefault) {
  46505. evt.preventDefault();
  46506. }
  46507. }
  46508. };
  46509. }
  46510. this._onMouseMove = function (evt) {
  46511. if (!engine.isPointerLock) {
  46512. return;
  46513. }
  46514. if (engine.isInVRExclusivePointerMode) {
  46515. return;
  46516. }
  46517. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46518. if (_this.camera.getScene().useRightHandedSystem)
  46519. offsetX *= -1;
  46520. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46521. offsetX *= -1;
  46522. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46523. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46524. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46525. _this.previousPosition = null;
  46526. if (!noPreventDefault) {
  46527. evt.preventDefault();
  46528. }
  46529. };
  46530. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46531. element.addEventListener("mousemove", this._onMouseMove, false);
  46532. };
  46533. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46534. if (this._observer && element) {
  46535. this.camera.getScene().onPointerObservable.remove(this._observer);
  46536. if (this._onMouseMove) {
  46537. element.removeEventListener("mousemove", this._onMouseMove);
  46538. }
  46539. this._observer = null;
  46540. this._onMouseMove = null;
  46541. this.previousPosition = null;
  46542. }
  46543. };
  46544. FreeCameraMouseInput.prototype.getClassName = function () {
  46545. return "FreeCameraMouseInput";
  46546. };
  46547. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46548. return "mouse";
  46549. };
  46550. __decorate([
  46551. BABYLON.serialize()
  46552. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46553. __decorate([
  46554. BABYLON.serialize()
  46555. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46556. return FreeCameraMouseInput;
  46557. }());
  46558. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46559. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46560. })(BABYLON || (BABYLON = {}));
  46561. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46562. var BABYLON;
  46563. (function (BABYLON) {
  46564. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46565. function FreeCameraKeyboardMoveInput() {
  46566. this._keys = new Array();
  46567. this.keysUp = [38];
  46568. this.keysDown = [40];
  46569. this.keysLeft = [37];
  46570. this.keysRight = [39];
  46571. }
  46572. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46573. var _this = this;
  46574. if (this._onCanvasBlurObserver) {
  46575. return;
  46576. }
  46577. this._scene = this.camera.getScene();
  46578. this._engine = this._scene.getEngine();
  46579. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46580. _this._keys = [];
  46581. });
  46582. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46583. var evt = info.event;
  46584. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46585. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46586. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46587. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46588. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46589. var index = _this._keys.indexOf(evt.keyCode);
  46590. if (index === -1) {
  46591. _this._keys.push(evt.keyCode);
  46592. }
  46593. if (!noPreventDefault) {
  46594. evt.preventDefault();
  46595. }
  46596. }
  46597. }
  46598. else {
  46599. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46600. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46601. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46602. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46603. var index = _this._keys.indexOf(evt.keyCode);
  46604. if (index >= 0) {
  46605. _this._keys.splice(index, 1);
  46606. }
  46607. if (!noPreventDefault) {
  46608. evt.preventDefault();
  46609. }
  46610. }
  46611. }
  46612. });
  46613. };
  46614. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46615. if (this._scene) {
  46616. if (this._onKeyboardObserver) {
  46617. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46618. }
  46619. if (this._onCanvasBlurObserver) {
  46620. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46621. }
  46622. this._onKeyboardObserver = null;
  46623. this._onCanvasBlurObserver = null;
  46624. }
  46625. this._keys = [];
  46626. };
  46627. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46628. if (this._onKeyboardObserver) {
  46629. var camera = this.camera;
  46630. // Keyboard
  46631. for (var index = 0; index < this._keys.length; index++) {
  46632. var keyCode = this._keys[index];
  46633. var speed = camera._computeLocalCameraSpeed();
  46634. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46635. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46636. }
  46637. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46638. camera._localDirection.copyFromFloats(0, 0, speed);
  46639. }
  46640. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46641. camera._localDirection.copyFromFloats(speed, 0, 0);
  46642. }
  46643. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46644. camera._localDirection.copyFromFloats(0, 0, -speed);
  46645. }
  46646. if (camera.getScene().useRightHandedSystem) {
  46647. camera._localDirection.z *= -1;
  46648. }
  46649. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46650. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46651. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46652. }
  46653. }
  46654. };
  46655. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46656. return "FreeCameraKeyboardMoveInput";
  46657. };
  46658. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46659. this._keys = [];
  46660. };
  46661. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46662. return "keyboard";
  46663. };
  46664. __decorate([
  46665. BABYLON.serialize()
  46666. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46667. __decorate([
  46668. BABYLON.serialize()
  46669. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46670. __decorate([
  46671. BABYLON.serialize()
  46672. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46673. __decorate([
  46674. BABYLON.serialize()
  46675. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46676. return FreeCameraKeyboardMoveInput;
  46677. }());
  46678. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46679. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46680. })(BABYLON || (BABYLON = {}));
  46681. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46682. var BABYLON;
  46683. (function (BABYLON) {
  46684. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46685. __extends(FreeCameraInputsManager, _super);
  46686. function FreeCameraInputsManager(camera) {
  46687. return _super.call(this, camera) || this;
  46688. }
  46689. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46690. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46691. return this;
  46692. };
  46693. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46694. if (touchEnabled === void 0) { touchEnabled = true; }
  46695. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46696. return this;
  46697. };
  46698. FreeCameraInputsManager.prototype.addGamepad = function () {
  46699. this.add(new BABYLON.FreeCameraGamepadInput());
  46700. return this;
  46701. };
  46702. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46703. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46704. return this;
  46705. };
  46706. FreeCameraInputsManager.prototype.addTouch = function () {
  46707. this.add(new BABYLON.FreeCameraTouchInput());
  46708. return this;
  46709. };
  46710. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46711. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46712. return this;
  46713. };
  46714. return FreeCameraInputsManager;
  46715. }(BABYLON.CameraInputsManager));
  46716. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46717. })(BABYLON || (BABYLON = {}));
  46718. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46719. var BABYLON;
  46720. (function (BABYLON) {
  46721. var FreeCamera = /** @class */ (function (_super) {
  46722. __extends(FreeCamera, _super);
  46723. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46724. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46725. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46726. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46727. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46728. _this.checkCollisions = false;
  46729. _this.applyGravity = false;
  46730. _this._needMoveForGravity = false;
  46731. _this._oldPosition = BABYLON.Vector3.Zero();
  46732. _this._diffPosition = BABYLON.Vector3.Zero();
  46733. _this._newPosition = BABYLON.Vector3.Zero();
  46734. // Collisions
  46735. _this._collisionMask = -1;
  46736. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46737. if (collidedMesh === void 0) { collidedMesh = null; }
  46738. //TODO move this to the collision coordinator!
  46739. if (_this.getScene().workerCollisions)
  46740. newPosition.multiplyInPlace(_this._collider._radius);
  46741. var updatePosition = function (newPos) {
  46742. _this._newPosition.copyFrom(newPos);
  46743. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46744. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46745. _this.position.addInPlace(_this._diffPosition);
  46746. if (_this.onCollide && collidedMesh) {
  46747. _this.onCollide(collidedMesh);
  46748. }
  46749. }
  46750. };
  46751. updatePosition(newPosition);
  46752. };
  46753. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46754. _this.inputs.addKeyboard().addMouse();
  46755. return _this;
  46756. }
  46757. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46758. //-- begin properties for backward compatibility for inputs
  46759. /**
  46760. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46761. * Higher values reduce sensitivity.
  46762. */
  46763. get: function () {
  46764. var mouse = this.inputs.attached["mouse"];
  46765. if (mouse)
  46766. return mouse.angularSensibility;
  46767. return 0;
  46768. },
  46769. /**
  46770. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46771. * Higher values reduce sensitivity.
  46772. */
  46773. set: function (value) {
  46774. var mouse = this.inputs.attached["mouse"];
  46775. if (mouse)
  46776. mouse.angularSensibility = value;
  46777. },
  46778. enumerable: true,
  46779. configurable: true
  46780. });
  46781. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46782. get: function () {
  46783. var keyboard = this.inputs.attached["keyboard"];
  46784. if (keyboard)
  46785. return keyboard.keysUp;
  46786. return [];
  46787. },
  46788. set: function (value) {
  46789. var keyboard = this.inputs.attached["keyboard"];
  46790. if (keyboard)
  46791. keyboard.keysUp = value;
  46792. },
  46793. enumerable: true,
  46794. configurable: true
  46795. });
  46796. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46797. get: function () {
  46798. var keyboard = this.inputs.attached["keyboard"];
  46799. if (keyboard)
  46800. return keyboard.keysDown;
  46801. return [];
  46802. },
  46803. set: function (value) {
  46804. var keyboard = this.inputs.attached["keyboard"];
  46805. if (keyboard)
  46806. keyboard.keysDown = value;
  46807. },
  46808. enumerable: true,
  46809. configurable: true
  46810. });
  46811. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46812. get: function () {
  46813. var keyboard = this.inputs.attached["keyboard"];
  46814. if (keyboard)
  46815. return keyboard.keysLeft;
  46816. return [];
  46817. },
  46818. set: function (value) {
  46819. var keyboard = this.inputs.attached["keyboard"];
  46820. if (keyboard)
  46821. keyboard.keysLeft = value;
  46822. },
  46823. enumerable: true,
  46824. configurable: true
  46825. });
  46826. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46827. get: function () {
  46828. var keyboard = this.inputs.attached["keyboard"];
  46829. if (keyboard)
  46830. return keyboard.keysRight;
  46831. return [];
  46832. },
  46833. set: function (value) {
  46834. var keyboard = this.inputs.attached["keyboard"];
  46835. if (keyboard)
  46836. keyboard.keysRight = value;
  46837. },
  46838. enumerable: true,
  46839. configurable: true
  46840. });
  46841. // Controls
  46842. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46843. this.inputs.attachElement(element, noPreventDefault);
  46844. };
  46845. FreeCamera.prototype.detachControl = function (element) {
  46846. this.inputs.detachElement(element);
  46847. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46848. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46849. };
  46850. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46851. get: function () {
  46852. return this._collisionMask;
  46853. },
  46854. set: function (mask) {
  46855. this._collisionMask = !isNaN(mask) ? mask : -1;
  46856. },
  46857. enumerable: true,
  46858. configurable: true
  46859. });
  46860. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46861. var globalPosition;
  46862. if (this.parent) {
  46863. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46864. }
  46865. else {
  46866. globalPosition = this.position;
  46867. }
  46868. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46869. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46870. if (!this._collider) {
  46871. this._collider = new BABYLON.Collider();
  46872. }
  46873. this._collider._radius = this.ellipsoid;
  46874. this._collider.collisionMask = this._collisionMask;
  46875. //no need for clone, as long as gravity is not on.
  46876. var actualDisplacement = displacement;
  46877. //add gravity to the direction to prevent the dual-collision checking
  46878. if (this.applyGravity) {
  46879. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46880. actualDisplacement = displacement.add(this.getScene().gravity);
  46881. }
  46882. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46883. };
  46884. FreeCamera.prototype._checkInputs = function () {
  46885. if (!this._localDirection) {
  46886. this._localDirection = BABYLON.Vector3.Zero();
  46887. this._transformedDirection = BABYLON.Vector3.Zero();
  46888. }
  46889. this.inputs.checkInputs();
  46890. _super.prototype._checkInputs.call(this);
  46891. };
  46892. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46893. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46894. };
  46895. FreeCamera.prototype._updatePosition = function () {
  46896. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46897. this._collideWithWorld(this.cameraDirection);
  46898. }
  46899. else {
  46900. _super.prototype._updatePosition.call(this);
  46901. }
  46902. };
  46903. FreeCamera.prototype.dispose = function () {
  46904. this.inputs.clear();
  46905. _super.prototype.dispose.call(this);
  46906. };
  46907. FreeCamera.prototype.getClassName = function () {
  46908. return "FreeCamera";
  46909. };
  46910. __decorate([
  46911. BABYLON.serializeAsVector3()
  46912. ], FreeCamera.prototype, "ellipsoid", void 0);
  46913. __decorate([
  46914. BABYLON.serializeAsVector3()
  46915. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46916. __decorate([
  46917. BABYLON.serialize()
  46918. ], FreeCamera.prototype, "checkCollisions", void 0);
  46919. __decorate([
  46920. BABYLON.serialize()
  46921. ], FreeCamera.prototype, "applyGravity", void 0);
  46922. return FreeCamera;
  46923. }(BABYLON.TargetCamera));
  46924. BABYLON.FreeCamera = FreeCamera;
  46925. })(BABYLON || (BABYLON = {}));
  46926. //# sourceMappingURL=babylon.freeCamera.js.map
  46927. var BABYLON;
  46928. (function (BABYLON) {
  46929. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46930. function ArcRotateCameraKeyboardMoveInput() {
  46931. this._keys = new Array();
  46932. this.keysUp = [38];
  46933. this.keysDown = [40];
  46934. this.keysLeft = [37];
  46935. this.keysRight = [39];
  46936. this.keysReset = [220];
  46937. this.panningSensibility = 50.0;
  46938. this.zoomingSensibility = 25.0;
  46939. this.useAltToZoom = true;
  46940. }
  46941. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46942. var _this = this;
  46943. if (this._onCanvasBlurObserver) {
  46944. return;
  46945. }
  46946. this._scene = this.camera.getScene();
  46947. this._engine = this._scene.getEngine();
  46948. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46949. _this._keys = [];
  46950. });
  46951. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46952. var evt = info.event;
  46953. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46954. _this._ctrlPressed = evt.ctrlKey;
  46955. _this._altPressed = evt.altKey;
  46956. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46957. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46958. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46959. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46960. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46961. var index = _this._keys.indexOf(evt.keyCode);
  46962. if (index === -1) {
  46963. _this._keys.push(evt.keyCode);
  46964. }
  46965. if (evt.preventDefault) {
  46966. if (!noPreventDefault) {
  46967. evt.preventDefault();
  46968. }
  46969. }
  46970. }
  46971. }
  46972. else {
  46973. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46974. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46975. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46976. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46977. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46978. var index = _this._keys.indexOf(evt.keyCode);
  46979. if (index >= 0) {
  46980. _this._keys.splice(index, 1);
  46981. }
  46982. if (evt.preventDefault) {
  46983. if (!noPreventDefault) {
  46984. evt.preventDefault();
  46985. }
  46986. }
  46987. }
  46988. }
  46989. });
  46990. };
  46991. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46992. if (this._scene) {
  46993. if (this._onKeyboardObserver) {
  46994. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46995. }
  46996. if (this._onCanvasBlurObserver) {
  46997. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46998. }
  46999. this._onKeyboardObserver = null;
  47000. this._onCanvasBlurObserver = null;
  47001. }
  47002. this._keys = [];
  47003. };
  47004. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47005. if (this._onKeyboardObserver) {
  47006. var camera = this.camera;
  47007. for (var index = 0; index < this._keys.length; index++) {
  47008. var keyCode = this._keys[index];
  47009. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47010. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47011. camera.inertialPanningX -= 1 / this.panningSensibility;
  47012. }
  47013. else {
  47014. camera.inertialAlphaOffset -= 0.01;
  47015. }
  47016. }
  47017. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47018. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47019. camera.inertialPanningY += 1 / this.panningSensibility;
  47020. }
  47021. else if (this._altPressed && this.useAltToZoom) {
  47022. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47023. }
  47024. else {
  47025. camera.inertialBetaOffset -= 0.01;
  47026. }
  47027. }
  47028. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47029. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47030. camera.inertialPanningX += 1 / this.panningSensibility;
  47031. }
  47032. else {
  47033. camera.inertialAlphaOffset += 0.01;
  47034. }
  47035. }
  47036. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47037. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47038. camera.inertialPanningY -= 1 / this.panningSensibility;
  47039. }
  47040. else if (this._altPressed && this.useAltToZoom) {
  47041. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47042. }
  47043. else {
  47044. camera.inertialBetaOffset += 0.01;
  47045. }
  47046. }
  47047. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47048. camera.restoreState();
  47049. }
  47050. }
  47051. }
  47052. };
  47053. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47054. return "ArcRotateCameraKeyboardMoveInput";
  47055. };
  47056. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47057. return "keyboard";
  47058. };
  47059. __decorate([
  47060. BABYLON.serialize()
  47061. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47062. __decorate([
  47063. BABYLON.serialize()
  47064. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47065. __decorate([
  47066. BABYLON.serialize()
  47067. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47068. __decorate([
  47069. BABYLON.serialize()
  47070. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47071. __decorate([
  47072. BABYLON.serialize()
  47073. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47074. __decorate([
  47075. BABYLON.serialize()
  47076. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47077. __decorate([
  47078. BABYLON.serialize()
  47079. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47080. __decorate([
  47081. BABYLON.serialize()
  47082. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47083. return ArcRotateCameraKeyboardMoveInput;
  47084. }());
  47085. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47086. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47087. })(BABYLON || (BABYLON = {}));
  47088. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47089. var BABYLON;
  47090. (function (BABYLON) {
  47091. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47092. function ArcRotateCameraMouseWheelInput() {
  47093. this.wheelPrecision = 3.0;
  47094. /**
  47095. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47096. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47097. */
  47098. this.wheelDeltaPercentage = 0;
  47099. }
  47100. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47101. var _this = this;
  47102. this._wheel = function (p, s) {
  47103. //sanity check - this should be a PointerWheel event.
  47104. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47105. return;
  47106. var event = p.event;
  47107. var delta = 0;
  47108. if (event.wheelDelta) {
  47109. if (_this.wheelDeltaPercentage) {
  47110. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47111. if (event.wheelDelta > 0) {
  47112. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47113. }
  47114. else {
  47115. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47116. }
  47117. }
  47118. else {
  47119. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47120. }
  47121. }
  47122. else if (event.detail) {
  47123. delta = -event.detail / _this.wheelPrecision;
  47124. }
  47125. if (delta)
  47126. _this.camera.inertialRadiusOffset += delta;
  47127. if (event.preventDefault) {
  47128. if (!noPreventDefault) {
  47129. event.preventDefault();
  47130. }
  47131. }
  47132. };
  47133. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47134. };
  47135. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47136. if (this._observer && element) {
  47137. this.camera.getScene().onPointerObservable.remove(this._observer);
  47138. this._observer = null;
  47139. this._wheel = null;
  47140. }
  47141. };
  47142. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47143. return "ArcRotateCameraMouseWheelInput";
  47144. };
  47145. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47146. return "mousewheel";
  47147. };
  47148. __decorate([
  47149. BABYLON.serialize()
  47150. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47151. __decorate([
  47152. BABYLON.serialize()
  47153. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47154. return ArcRotateCameraMouseWheelInput;
  47155. }());
  47156. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47157. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47158. })(BABYLON || (BABYLON = {}));
  47159. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47160. var BABYLON;
  47161. (function (BABYLON) {
  47162. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47163. function ArcRotateCameraPointersInput() {
  47164. this.buttons = [0, 1, 2];
  47165. this.angularSensibilityX = 1000.0;
  47166. this.angularSensibilityY = 1000.0;
  47167. this.pinchPrecision = 12.0;
  47168. /**
  47169. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47170. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47171. */
  47172. this.pinchDeltaPercentage = 0;
  47173. this.panningSensibility = 1000.0;
  47174. this.multiTouchPanning = true;
  47175. this.multiTouchPanAndZoom = true;
  47176. this._isPanClick = false;
  47177. this.pinchInwards = true;
  47178. }
  47179. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47180. var _this = this;
  47181. var engine = this.camera.getEngine();
  47182. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47183. var pointA = null;
  47184. var pointB = null;
  47185. var previousPinchSquaredDistance = 0;
  47186. var initialDistance = 0;
  47187. var twoFingerActivityCount = 0;
  47188. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47189. this._pointerInput = function (p, s) {
  47190. var evt = p.event;
  47191. var isTouch = p.event.pointerType === "touch";
  47192. if (engine.isInVRExclusivePointerMode) {
  47193. return;
  47194. }
  47195. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47196. return;
  47197. }
  47198. var srcElement = (evt.srcElement || evt.target);
  47199. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47200. try {
  47201. srcElement.setPointerCapture(evt.pointerId);
  47202. }
  47203. catch (e) {
  47204. //Nothing to do with the error. Execution will continue.
  47205. }
  47206. // Manage panning with pan button click
  47207. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47208. // manage pointers
  47209. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47210. if (pointA === null) {
  47211. pointA = cacheSoloPointer;
  47212. }
  47213. else if (pointB === null) {
  47214. pointB = cacheSoloPointer;
  47215. }
  47216. if (!noPreventDefault) {
  47217. evt.preventDefault();
  47218. element.focus();
  47219. }
  47220. }
  47221. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47222. _this.camera.restoreState();
  47223. }
  47224. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47225. try {
  47226. srcElement.releasePointerCapture(evt.pointerId);
  47227. }
  47228. catch (e) {
  47229. //Nothing to do with the error.
  47230. }
  47231. cacheSoloPointer = null;
  47232. previousPinchSquaredDistance = 0;
  47233. previousMultiTouchPanPosition.isPaning = false;
  47234. previousMultiTouchPanPosition.isPinching = false;
  47235. twoFingerActivityCount = 0;
  47236. initialDistance = 0;
  47237. if (!isTouch) {
  47238. pointB = null; // Mouse and pen are mono pointer
  47239. }
  47240. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47241. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47242. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47243. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47244. if (engine._badOS) {
  47245. pointA = pointB = null;
  47246. }
  47247. else {
  47248. //only remove the impacted pointer in case of multitouch allowing on most
  47249. //platforms switching from rotate to zoom and pan seamlessly.
  47250. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47251. pointA = pointB;
  47252. pointB = null;
  47253. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47254. }
  47255. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47256. pointB = null;
  47257. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47258. }
  47259. else {
  47260. pointA = pointB = null;
  47261. }
  47262. }
  47263. if (!noPreventDefault) {
  47264. evt.preventDefault();
  47265. }
  47266. }
  47267. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47268. if (!noPreventDefault) {
  47269. evt.preventDefault();
  47270. }
  47271. // One button down
  47272. if (pointA && pointB === null && cacheSoloPointer) {
  47273. if (_this.panningSensibility !== 0 &&
  47274. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47275. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47276. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47277. }
  47278. else {
  47279. var offsetX = evt.clientX - cacheSoloPointer.x;
  47280. var offsetY = evt.clientY - cacheSoloPointer.y;
  47281. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47282. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47283. }
  47284. cacheSoloPointer.x = evt.clientX;
  47285. cacheSoloPointer.y = evt.clientY;
  47286. }
  47287. // Two buttons down: pinch/pan
  47288. else if (pointA && pointB) {
  47289. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47290. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47291. ed.x = evt.clientX;
  47292. ed.y = evt.clientY;
  47293. var direction = _this.pinchInwards ? 1 : -1;
  47294. var distX = pointA.x - pointB.x;
  47295. var distY = pointA.y - pointB.y;
  47296. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47297. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47298. if (previousPinchSquaredDistance === 0) {
  47299. initialDistance = pinchDistance;
  47300. previousPinchSquaredDistance = pinchSquaredDistance;
  47301. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47302. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47303. return;
  47304. }
  47305. if (_this.multiTouchPanAndZoom) {
  47306. if (_this.pinchDeltaPercentage) {
  47307. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47308. }
  47309. else {
  47310. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47311. (_this.pinchPrecision *
  47312. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47313. direction);
  47314. }
  47315. if (_this.panningSensibility !== 0) {
  47316. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47317. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47318. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47319. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47320. previousMultiTouchPanPosition.x = pointersCenterX;
  47321. previousMultiTouchPanPosition.y = pointersCenterY;
  47322. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47323. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47324. }
  47325. }
  47326. else {
  47327. twoFingerActivityCount++;
  47328. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47329. if (_this.pinchDeltaPercentage) {
  47330. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47331. }
  47332. else {
  47333. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47334. (_this.pinchPrecision *
  47335. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47336. direction);
  47337. }
  47338. previousMultiTouchPanPosition.isPaning = false;
  47339. previousMultiTouchPanPosition.isPinching = true;
  47340. }
  47341. else {
  47342. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47343. if (!previousMultiTouchPanPosition.isPaning) {
  47344. previousMultiTouchPanPosition.isPaning = true;
  47345. previousMultiTouchPanPosition.isPinching = false;
  47346. previousMultiTouchPanPosition.x = ed.x;
  47347. previousMultiTouchPanPosition.y = ed.y;
  47348. return;
  47349. }
  47350. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47351. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47352. }
  47353. }
  47354. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47355. previousMultiTouchPanPosition.x = ed.x;
  47356. previousMultiTouchPanPosition.y = ed.y;
  47357. }
  47358. }
  47359. previousPinchSquaredDistance = pinchSquaredDistance;
  47360. }
  47361. }
  47362. };
  47363. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47364. this._onContextMenu = function (evt) {
  47365. evt.preventDefault();
  47366. };
  47367. if (!this.camera._useCtrlForPanning) {
  47368. element.addEventListener("contextmenu", this._onContextMenu, false);
  47369. }
  47370. this._onLostFocus = function () {
  47371. //this._keys = [];
  47372. pointA = pointB = null;
  47373. previousPinchSquaredDistance = 0;
  47374. previousMultiTouchPanPosition.isPaning = false;
  47375. previousMultiTouchPanPosition.isPinching = false;
  47376. twoFingerActivityCount = 0;
  47377. cacheSoloPointer = null;
  47378. initialDistance = 0;
  47379. };
  47380. this._onMouseMove = function (evt) {
  47381. if (!engine.isPointerLock) {
  47382. return;
  47383. }
  47384. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47385. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47386. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47387. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47388. if (!noPreventDefault) {
  47389. evt.preventDefault();
  47390. }
  47391. };
  47392. this._onGestureStart = function (e) {
  47393. if (window.MSGesture === undefined) {
  47394. return;
  47395. }
  47396. if (!_this._MSGestureHandler) {
  47397. _this._MSGestureHandler = new MSGesture();
  47398. _this._MSGestureHandler.target = element;
  47399. }
  47400. _this._MSGestureHandler.addPointer(e.pointerId);
  47401. };
  47402. this._onGesture = function (e) {
  47403. _this.camera.radius *= e.scale;
  47404. if (e.preventDefault) {
  47405. if (!noPreventDefault) {
  47406. e.stopPropagation();
  47407. e.preventDefault();
  47408. }
  47409. }
  47410. };
  47411. element.addEventListener("mousemove", this._onMouseMove, false);
  47412. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47413. element.addEventListener("MSGestureChange", this._onGesture, false);
  47414. BABYLON.Tools.RegisterTopRootEvents([
  47415. { name: "blur", handler: this._onLostFocus }
  47416. ]);
  47417. };
  47418. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47419. if (this._onLostFocus) {
  47420. BABYLON.Tools.UnregisterTopRootEvents([
  47421. { name: "blur", handler: this._onLostFocus }
  47422. ]);
  47423. }
  47424. if (element && this._observer) {
  47425. this.camera.getScene().onPointerObservable.remove(this._observer);
  47426. this._observer = null;
  47427. if (this._onContextMenu) {
  47428. element.removeEventListener("contextmenu", this._onContextMenu);
  47429. }
  47430. if (this._onMouseMove) {
  47431. element.removeEventListener("mousemove", this._onMouseMove);
  47432. }
  47433. if (this._onGestureStart) {
  47434. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47435. }
  47436. if (this._onGesture) {
  47437. element.removeEventListener("MSGestureChange", this._onGesture);
  47438. }
  47439. this._isPanClick = false;
  47440. this.pinchInwards = true;
  47441. this._onMouseMove = null;
  47442. this._onGestureStart = null;
  47443. this._onGesture = null;
  47444. this._MSGestureHandler = null;
  47445. this._onLostFocus = null;
  47446. this._onContextMenu = null;
  47447. }
  47448. };
  47449. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47450. return "ArcRotateCameraPointersInput";
  47451. };
  47452. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47453. return "pointers";
  47454. };
  47455. __decorate([
  47456. BABYLON.serialize()
  47457. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47458. __decorate([
  47459. BABYLON.serialize()
  47460. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47461. __decorate([
  47462. BABYLON.serialize()
  47463. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47464. __decorate([
  47465. BABYLON.serialize()
  47466. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47467. __decorate([
  47468. BABYLON.serialize()
  47469. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47470. __decorate([
  47471. BABYLON.serialize()
  47472. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47473. __decorate([
  47474. BABYLON.serialize()
  47475. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47476. __decorate([
  47477. BABYLON.serialize()
  47478. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47479. return ArcRotateCameraPointersInput;
  47480. }());
  47481. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47482. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47483. })(BABYLON || (BABYLON = {}));
  47484. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47485. var BABYLON;
  47486. (function (BABYLON) {
  47487. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47488. __extends(ArcRotateCameraInputsManager, _super);
  47489. function ArcRotateCameraInputsManager(camera) {
  47490. return _super.call(this, camera) || this;
  47491. }
  47492. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47493. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47494. return this;
  47495. };
  47496. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47497. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47498. return this;
  47499. };
  47500. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47501. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47502. return this;
  47503. };
  47504. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47505. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47506. return this;
  47507. };
  47508. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47509. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47510. return this;
  47511. };
  47512. return ArcRotateCameraInputsManager;
  47513. }(BABYLON.CameraInputsManager));
  47514. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47515. })(BABYLON || (BABYLON = {}));
  47516. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47517. var BABYLON;
  47518. (function (BABYLON) {
  47519. var ArcRotateCamera = /** @class */ (function (_super) {
  47520. __extends(ArcRotateCamera, _super);
  47521. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47522. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47523. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47524. _this.inertialAlphaOffset = 0;
  47525. _this.inertialBetaOffset = 0;
  47526. _this.inertialRadiusOffset = 0;
  47527. _this.lowerAlphaLimit = null;
  47528. _this.upperAlphaLimit = null;
  47529. _this.lowerBetaLimit = 0.01;
  47530. _this.upperBetaLimit = Math.PI;
  47531. _this.lowerRadiusLimit = null;
  47532. _this.upperRadiusLimit = null;
  47533. _this.inertialPanningX = 0;
  47534. _this.inertialPanningY = 0;
  47535. _this.pinchToPanMaxDistance = 20;
  47536. _this.panningDistanceLimit = null;
  47537. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47538. _this.panningInertia = 0.9;
  47539. //-- end properties for backward compatibility for inputs
  47540. _this.zoomOnFactor = 1;
  47541. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47542. _this.allowUpsideDown = true;
  47543. _this._viewMatrix = new BABYLON.Matrix();
  47544. // Panning
  47545. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47546. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47547. _this.checkCollisions = false;
  47548. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47549. _this._previousPosition = BABYLON.Vector3.Zero();
  47550. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47551. _this._newPosition = BABYLON.Vector3.Zero();
  47552. _this._computationVector = BABYLON.Vector3.Zero();
  47553. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47554. if (collidedMesh === void 0) { collidedMesh = null; }
  47555. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47556. newPosition.multiplyInPlace(_this._collider._radius);
  47557. }
  47558. if (!collidedMesh) {
  47559. _this._previousPosition.copyFrom(_this.position);
  47560. }
  47561. else {
  47562. _this.setPosition(newPosition);
  47563. if (_this.onCollide) {
  47564. _this.onCollide(collidedMesh);
  47565. }
  47566. }
  47567. // Recompute because of constraints
  47568. var cosa = Math.cos(_this.alpha);
  47569. var sina = Math.sin(_this.alpha);
  47570. var cosb = Math.cos(_this.beta);
  47571. var sinb = Math.sin(_this.beta);
  47572. if (sinb === 0) {
  47573. sinb = 0.0001;
  47574. }
  47575. var target = _this._getTargetPosition();
  47576. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47577. target.addToRef(_this._computationVector, _this._newPosition);
  47578. _this.position.copyFrom(_this._newPosition);
  47579. var up = _this.upVector;
  47580. if (_this.allowUpsideDown && _this.beta < 0) {
  47581. up = up.clone();
  47582. up = up.negate();
  47583. }
  47584. _this._computeViewMatrix(_this.position, target, up);
  47585. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47586. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47587. _this._collisionTriggered = false;
  47588. };
  47589. _this._target = BABYLON.Vector3.Zero();
  47590. if (target) {
  47591. _this.setTarget(target);
  47592. }
  47593. _this.alpha = alpha;
  47594. _this.beta = beta;
  47595. _this.radius = radius;
  47596. _this.getViewMatrix();
  47597. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47598. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47599. return _this;
  47600. }
  47601. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47602. get: function () {
  47603. return this._target;
  47604. },
  47605. set: function (value) {
  47606. this.setTarget(value);
  47607. },
  47608. enumerable: true,
  47609. configurable: true
  47610. });
  47611. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47612. //-- begin properties for backward compatibility for inputs
  47613. get: function () {
  47614. var pointers = this.inputs.attached["pointers"];
  47615. if (pointers)
  47616. return pointers.angularSensibilityX;
  47617. return 0;
  47618. },
  47619. set: function (value) {
  47620. var pointers = this.inputs.attached["pointers"];
  47621. if (pointers) {
  47622. pointers.angularSensibilityX = value;
  47623. }
  47624. },
  47625. enumerable: true,
  47626. configurable: true
  47627. });
  47628. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47629. get: function () {
  47630. var pointers = this.inputs.attached["pointers"];
  47631. if (pointers)
  47632. return pointers.angularSensibilityY;
  47633. return 0;
  47634. },
  47635. set: function (value) {
  47636. var pointers = this.inputs.attached["pointers"];
  47637. if (pointers) {
  47638. pointers.angularSensibilityY = value;
  47639. }
  47640. },
  47641. enumerable: true,
  47642. configurable: true
  47643. });
  47644. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47645. get: function () {
  47646. var pointers = this.inputs.attached["pointers"];
  47647. if (pointers)
  47648. return pointers.pinchPrecision;
  47649. return 0;
  47650. },
  47651. set: function (value) {
  47652. var pointers = this.inputs.attached["pointers"];
  47653. if (pointers) {
  47654. pointers.pinchPrecision = value;
  47655. }
  47656. },
  47657. enumerable: true,
  47658. configurable: true
  47659. });
  47660. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47661. get: function () {
  47662. var pointers = this.inputs.attached["pointers"];
  47663. if (pointers)
  47664. return pointers.pinchDeltaPercentage;
  47665. return 0;
  47666. },
  47667. set: function (value) {
  47668. var pointers = this.inputs.attached["pointers"];
  47669. if (pointers) {
  47670. pointers.pinchDeltaPercentage = value;
  47671. }
  47672. },
  47673. enumerable: true,
  47674. configurable: true
  47675. });
  47676. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47677. get: function () {
  47678. var pointers = this.inputs.attached["pointers"];
  47679. if (pointers)
  47680. return pointers.panningSensibility;
  47681. return 0;
  47682. },
  47683. set: function (value) {
  47684. var pointers = this.inputs.attached["pointers"];
  47685. if (pointers) {
  47686. pointers.panningSensibility = value;
  47687. }
  47688. },
  47689. enumerable: true,
  47690. configurable: true
  47691. });
  47692. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47693. get: function () {
  47694. var keyboard = this.inputs.attached["keyboard"];
  47695. if (keyboard)
  47696. return keyboard.keysUp;
  47697. return [];
  47698. },
  47699. set: function (value) {
  47700. var keyboard = this.inputs.attached["keyboard"];
  47701. if (keyboard)
  47702. keyboard.keysUp = value;
  47703. },
  47704. enumerable: true,
  47705. configurable: true
  47706. });
  47707. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47708. get: function () {
  47709. var keyboard = this.inputs.attached["keyboard"];
  47710. if (keyboard)
  47711. return keyboard.keysDown;
  47712. return [];
  47713. },
  47714. set: function (value) {
  47715. var keyboard = this.inputs.attached["keyboard"];
  47716. if (keyboard)
  47717. keyboard.keysDown = value;
  47718. },
  47719. enumerable: true,
  47720. configurable: true
  47721. });
  47722. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47723. get: function () {
  47724. var keyboard = this.inputs.attached["keyboard"];
  47725. if (keyboard)
  47726. return keyboard.keysLeft;
  47727. return [];
  47728. },
  47729. set: function (value) {
  47730. var keyboard = this.inputs.attached["keyboard"];
  47731. if (keyboard)
  47732. keyboard.keysLeft = value;
  47733. },
  47734. enumerable: true,
  47735. configurable: true
  47736. });
  47737. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47738. get: function () {
  47739. var keyboard = this.inputs.attached["keyboard"];
  47740. if (keyboard)
  47741. return keyboard.keysRight;
  47742. return [];
  47743. },
  47744. set: function (value) {
  47745. var keyboard = this.inputs.attached["keyboard"];
  47746. if (keyboard)
  47747. keyboard.keysRight = value;
  47748. },
  47749. enumerable: true,
  47750. configurable: true
  47751. });
  47752. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47753. get: function () {
  47754. var mousewheel = this.inputs.attached["mousewheel"];
  47755. if (mousewheel)
  47756. return mousewheel.wheelPrecision;
  47757. return 0;
  47758. },
  47759. set: function (value) {
  47760. var mousewheel = this.inputs.attached["mousewheel"];
  47761. if (mousewheel)
  47762. mousewheel.wheelPrecision = value;
  47763. },
  47764. enumerable: true,
  47765. configurable: true
  47766. });
  47767. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47768. get: function () {
  47769. var mousewheel = this.inputs.attached["mousewheel"];
  47770. if (mousewheel)
  47771. return mousewheel.wheelDeltaPercentage;
  47772. return 0;
  47773. },
  47774. set: function (value) {
  47775. var mousewheel = this.inputs.attached["mousewheel"];
  47776. if (mousewheel)
  47777. mousewheel.wheelDeltaPercentage = value;
  47778. },
  47779. enumerable: true,
  47780. configurable: true
  47781. });
  47782. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47783. get: function () {
  47784. return this._bouncingBehavior;
  47785. },
  47786. enumerable: true,
  47787. configurable: true
  47788. });
  47789. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47790. get: function () {
  47791. return this._bouncingBehavior != null;
  47792. },
  47793. set: function (value) {
  47794. if (value === this.useBouncingBehavior) {
  47795. return;
  47796. }
  47797. if (value) {
  47798. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47799. this.addBehavior(this._bouncingBehavior);
  47800. }
  47801. else if (this._bouncingBehavior) {
  47802. this.removeBehavior(this._bouncingBehavior);
  47803. this._bouncingBehavior = null;
  47804. }
  47805. },
  47806. enumerable: true,
  47807. configurable: true
  47808. });
  47809. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47810. get: function () {
  47811. return this._framingBehavior;
  47812. },
  47813. enumerable: true,
  47814. configurable: true
  47815. });
  47816. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47817. get: function () {
  47818. return this._framingBehavior != null;
  47819. },
  47820. set: function (value) {
  47821. if (value === this.useFramingBehavior) {
  47822. return;
  47823. }
  47824. if (value) {
  47825. this._framingBehavior = new BABYLON.FramingBehavior();
  47826. this.addBehavior(this._framingBehavior);
  47827. }
  47828. else if (this._framingBehavior) {
  47829. this.removeBehavior(this._framingBehavior);
  47830. this._framingBehavior = null;
  47831. }
  47832. },
  47833. enumerable: true,
  47834. configurable: true
  47835. });
  47836. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47837. get: function () {
  47838. return this._autoRotationBehavior;
  47839. },
  47840. enumerable: true,
  47841. configurable: true
  47842. });
  47843. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47844. get: function () {
  47845. return this._autoRotationBehavior != null;
  47846. },
  47847. set: function (value) {
  47848. if (value === this.useAutoRotationBehavior) {
  47849. return;
  47850. }
  47851. if (value) {
  47852. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47853. this.addBehavior(this._autoRotationBehavior);
  47854. }
  47855. else if (this._autoRotationBehavior) {
  47856. this.removeBehavior(this._autoRotationBehavior);
  47857. this._autoRotationBehavior = null;
  47858. }
  47859. },
  47860. enumerable: true,
  47861. configurable: true
  47862. });
  47863. // Cache
  47864. ArcRotateCamera.prototype._initCache = function () {
  47865. _super.prototype._initCache.call(this);
  47866. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47867. this._cache.alpha = undefined;
  47868. this._cache.beta = undefined;
  47869. this._cache.radius = undefined;
  47870. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47871. };
  47872. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47873. if (!ignoreParentClass) {
  47874. _super.prototype._updateCache.call(this);
  47875. }
  47876. this._cache._target.copyFrom(this._getTargetPosition());
  47877. this._cache.alpha = this.alpha;
  47878. this._cache.beta = this.beta;
  47879. this._cache.radius = this.radius;
  47880. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47881. };
  47882. ArcRotateCamera.prototype._getTargetPosition = function () {
  47883. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47884. var pos = this._targetHost.getAbsolutePosition();
  47885. if (this._targetBoundingCenter) {
  47886. pos.addToRef(this._targetBoundingCenter, this._target);
  47887. }
  47888. else {
  47889. this._target.copyFrom(pos);
  47890. }
  47891. }
  47892. var lockedTargetPosition = this._getLockedTargetPosition();
  47893. if (lockedTargetPosition) {
  47894. return lockedTargetPosition;
  47895. }
  47896. return this._target;
  47897. };
  47898. ArcRotateCamera.prototype.storeState = function () {
  47899. this._storedAlpha = this.alpha;
  47900. this._storedBeta = this.beta;
  47901. this._storedRadius = this.radius;
  47902. this._storedTarget = this._getTargetPosition().clone();
  47903. return _super.prototype.storeState.call(this);
  47904. };
  47905. /**
  47906. * Restored camera state. You must call storeState() first
  47907. */
  47908. ArcRotateCamera.prototype._restoreStateValues = function () {
  47909. if (!_super.prototype._restoreStateValues.call(this)) {
  47910. return false;
  47911. }
  47912. this.alpha = this._storedAlpha;
  47913. this.beta = this._storedBeta;
  47914. this.radius = this._storedRadius;
  47915. this.setTarget(this._storedTarget.clone());
  47916. this.inertialAlphaOffset = 0;
  47917. this.inertialBetaOffset = 0;
  47918. this.inertialRadiusOffset = 0;
  47919. this.inertialPanningX = 0;
  47920. this.inertialPanningY = 0;
  47921. return true;
  47922. };
  47923. // Synchronized
  47924. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47925. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47926. return false;
  47927. return this._cache._target.equals(this._getTargetPosition())
  47928. && this._cache.alpha === this.alpha
  47929. && this._cache.beta === this.beta
  47930. && this._cache.radius === this.radius
  47931. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47932. };
  47933. // Methods
  47934. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47935. var _this = this;
  47936. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47937. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47938. this._useCtrlForPanning = useCtrlForPanning;
  47939. this._panningMouseButton = panningMouseButton;
  47940. this.inputs.attachElement(element, noPreventDefault);
  47941. this._reset = function () {
  47942. _this.inertialAlphaOffset = 0;
  47943. _this.inertialBetaOffset = 0;
  47944. _this.inertialRadiusOffset = 0;
  47945. _this.inertialPanningX = 0;
  47946. _this.inertialPanningY = 0;
  47947. };
  47948. };
  47949. ArcRotateCamera.prototype.detachControl = function (element) {
  47950. this.inputs.detachElement(element);
  47951. if (this._reset) {
  47952. this._reset();
  47953. }
  47954. };
  47955. ArcRotateCamera.prototype._checkInputs = function () {
  47956. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47957. if (this._collisionTriggered) {
  47958. return;
  47959. }
  47960. this.inputs.checkInputs();
  47961. // Inertia
  47962. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47963. var inertialAlphaOffset = this.inertialAlphaOffset;
  47964. if (this.beta <= 0)
  47965. inertialAlphaOffset *= -1;
  47966. if (this.getScene().useRightHandedSystem)
  47967. inertialAlphaOffset *= -1;
  47968. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47969. inertialAlphaOffset *= -1;
  47970. this.alpha += inertialAlphaOffset;
  47971. this.beta += this.inertialBetaOffset;
  47972. this.radius -= this.inertialRadiusOffset;
  47973. this.inertialAlphaOffset *= this.inertia;
  47974. this.inertialBetaOffset *= this.inertia;
  47975. this.inertialRadiusOffset *= this.inertia;
  47976. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47977. this.inertialAlphaOffset = 0;
  47978. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47979. this.inertialBetaOffset = 0;
  47980. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47981. this.inertialRadiusOffset = 0;
  47982. }
  47983. // Panning inertia
  47984. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47985. if (!this._localDirection) {
  47986. this._localDirection = BABYLON.Vector3.Zero();
  47987. this._transformedDirection = BABYLON.Vector3.Zero();
  47988. }
  47989. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47990. this._localDirection.multiplyInPlace(this.panningAxis);
  47991. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47992. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47993. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47994. if (!this.panningAxis.y) {
  47995. this._transformedDirection.y = 0;
  47996. }
  47997. if (!this._targetHost) {
  47998. if (this.panningDistanceLimit) {
  47999. this._transformedDirection.addInPlace(this._target);
  48000. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48001. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48002. this._target.copyFrom(this._transformedDirection);
  48003. }
  48004. }
  48005. else {
  48006. this._target.addInPlace(this._transformedDirection);
  48007. }
  48008. }
  48009. this.inertialPanningX *= this.panningInertia;
  48010. this.inertialPanningY *= this.panningInertia;
  48011. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48012. this.inertialPanningX = 0;
  48013. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48014. this.inertialPanningY = 0;
  48015. }
  48016. // Limits
  48017. this._checkLimits();
  48018. _super.prototype._checkInputs.call(this);
  48019. };
  48020. ArcRotateCamera.prototype._checkLimits = function () {
  48021. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48022. if (this.allowUpsideDown && this.beta > Math.PI) {
  48023. this.beta = this.beta - (2 * Math.PI);
  48024. }
  48025. }
  48026. else {
  48027. if (this.beta < this.lowerBetaLimit) {
  48028. this.beta = this.lowerBetaLimit;
  48029. }
  48030. }
  48031. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48032. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48033. this.beta = this.beta + (2 * Math.PI);
  48034. }
  48035. }
  48036. else {
  48037. if (this.beta > this.upperBetaLimit) {
  48038. this.beta = this.upperBetaLimit;
  48039. }
  48040. }
  48041. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48042. this.alpha = this.lowerAlphaLimit;
  48043. }
  48044. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48045. this.alpha = this.upperAlphaLimit;
  48046. }
  48047. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48048. this.radius = this.lowerRadiusLimit;
  48049. }
  48050. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48051. this.radius = this.upperRadiusLimit;
  48052. }
  48053. };
  48054. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48055. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48056. this.radius = this._computationVector.length();
  48057. if (this.radius === 0) {
  48058. this.radius = 0.0001; // Just to avoid division by zero
  48059. }
  48060. // Alpha
  48061. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48062. if (this._computationVector.z < 0) {
  48063. this.alpha = 2 * Math.PI - this.alpha;
  48064. }
  48065. // Beta
  48066. this.beta = Math.acos(this._computationVector.y / this.radius);
  48067. this._checkLimits();
  48068. };
  48069. ArcRotateCamera.prototype.setPosition = function (position) {
  48070. if (this.position.equals(position)) {
  48071. return;
  48072. }
  48073. this.position.copyFrom(position);
  48074. this.rebuildAnglesAndRadius();
  48075. };
  48076. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48077. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48078. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48079. if (target.getBoundingInfo) {
  48080. if (toBoundingCenter) {
  48081. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48082. }
  48083. else {
  48084. this._targetBoundingCenter = null;
  48085. }
  48086. this._targetHost = target;
  48087. this._target = this._getTargetPosition();
  48088. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48089. }
  48090. else {
  48091. var newTarget = target;
  48092. var currentTarget = this._getTargetPosition();
  48093. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48094. return;
  48095. }
  48096. this._targetHost = null;
  48097. this._target = newTarget;
  48098. this._targetBoundingCenter = null;
  48099. this.onMeshTargetChangedObservable.notifyObservers(null);
  48100. }
  48101. this.rebuildAnglesAndRadius();
  48102. };
  48103. ArcRotateCamera.prototype._getViewMatrix = function () {
  48104. // Compute
  48105. var cosa = Math.cos(this.alpha);
  48106. var sina = Math.sin(this.alpha);
  48107. var cosb = Math.cos(this.beta);
  48108. var sinb = Math.sin(this.beta);
  48109. if (sinb === 0) {
  48110. sinb = 0.0001;
  48111. }
  48112. var target = this._getTargetPosition();
  48113. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48114. target.addToRef(this._computationVector, this._newPosition);
  48115. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48116. if (!this._collider) {
  48117. this._collider = new BABYLON.Collider();
  48118. }
  48119. this._collider._radius = this.collisionRadius;
  48120. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48121. this._collisionTriggered = true;
  48122. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48123. }
  48124. else {
  48125. this.position.copyFrom(this._newPosition);
  48126. var up = this.upVector;
  48127. if (this.allowUpsideDown && sinb < 0) {
  48128. up = up.clone();
  48129. up = up.negate();
  48130. }
  48131. this._computeViewMatrix(this.position, target, up);
  48132. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48133. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48134. }
  48135. this._currentTarget = target;
  48136. return this._viewMatrix;
  48137. };
  48138. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48139. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48140. meshes = meshes || this.getScene().meshes;
  48141. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48142. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48143. this.radius = distance * this.zoomOnFactor;
  48144. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48145. };
  48146. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48147. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48148. var meshesOrMinMaxVector;
  48149. var distance;
  48150. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48151. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48152. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48153. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48154. }
  48155. else { //minMaxVector and distance
  48156. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48157. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48158. distance = minMaxVectorAndDistance.distance;
  48159. }
  48160. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48161. if (!doNotUpdateMaxZ) {
  48162. this.maxZ = distance * 2;
  48163. }
  48164. };
  48165. /**
  48166. * @override
  48167. * Override Camera.createRigCamera
  48168. */
  48169. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48170. var alphaShift = 0;
  48171. switch (this.cameraRigMode) {
  48172. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48173. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48174. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48175. case BABYLON.Camera.RIG_MODE_VR:
  48176. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48177. break;
  48178. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48179. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48180. break;
  48181. }
  48182. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48183. rigCam._cameraRigParams = {};
  48184. return rigCam;
  48185. };
  48186. /**
  48187. * @override
  48188. * Override Camera._updateRigCameras
  48189. */
  48190. ArcRotateCamera.prototype._updateRigCameras = function () {
  48191. var camLeft = this._rigCameras[0];
  48192. var camRight = this._rigCameras[1];
  48193. camLeft.beta = camRight.beta = this.beta;
  48194. camLeft.radius = camRight.radius = this.radius;
  48195. switch (this.cameraRigMode) {
  48196. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48197. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48198. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48199. case BABYLON.Camera.RIG_MODE_VR:
  48200. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48201. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48202. break;
  48203. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48204. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48205. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48206. break;
  48207. }
  48208. _super.prototype._updateRigCameras.call(this);
  48209. };
  48210. ArcRotateCamera.prototype.dispose = function () {
  48211. this.inputs.clear();
  48212. _super.prototype.dispose.call(this);
  48213. };
  48214. ArcRotateCamera.prototype.getClassName = function () {
  48215. return "ArcRotateCamera";
  48216. };
  48217. __decorate([
  48218. BABYLON.serialize()
  48219. ], ArcRotateCamera.prototype, "alpha", void 0);
  48220. __decorate([
  48221. BABYLON.serialize()
  48222. ], ArcRotateCamera.prototype, "beta", void 0);
  48223. __decorate([
  48224. BABYLON.serialize()
  48225. ], ArcRotateCamera.prototype, "radius", void 0);
  48226. __decorate([
  48227. BABYLON.serializeAsVector3("target")
  48228. ], ArcRotateCamera.prototype, "_target", void 0);
  48229. __decorate([
  48230. BABYLON.serialize()
  48231. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48232. __decorate([
  48233. BABYLON.serialize()
  48234. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48235. __decorate([
  48236. BABYLON.serialize()
  48237. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48238. __decorate([
  48239. BABYLON.serialize()
  48240. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48241. __decorate([
  48242. BABYLON.serialize()
  48243. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48244. __decorate([
  48245. BABYLON.serialize()
  48246. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48247. __decorate([
  48248. BABYLON.serialize()
  48249. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48250. __decorate([
  48251. BABYLON.serialize()
  48252. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48253. __decorate([
  48254. BABYLON.serialize()
  48255. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48256. __decorate([
  48257. BABYLON.serialize()
  48258. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48259. __decorate([
  48260. BABYLON.serialize()
  48261. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48262. __decorate([
  48263. BABYLON.serialize()
  48264. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48265. __decorate([
  48266. BABYLON.serialize()
  48267. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48268. __decorate([
  48269. BABYLON.serializeAsVector3()
  48270. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48271. __decorate([
  48272. BABYLON.serialize()
  48273. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48274. __decorate([
  48275. BABYLON.serialize()
  48276. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48277. __decorate([
  48278. BABYLON.serialize()
  48279. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48280. return ArcRotateCamera;
  48281. }(BABYLON.TargetCamera));
  48282. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48283. })(BABYLON || (BABYLON = {}));
  48284. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48285. var BABYLON;
  48286. (function (BABYLON) {
  48287. /**
  48288. * The HemisphericLight simulates the ambient environment light,
  48289. * so the passed direction is the light reflection direction, not the incoming direction.
  48290. */
  48291. var HemisphericLight = /** @class */ (function (_super) {
  48292. __extends(HemisphericLight, _super);
  48293. /**
  48294. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48295. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48296. * The HemisphericLight can't cast shadows.
  48297. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48298. * @param name The friendly name of the light
  48299. * @param direction The direction of the light reflection
  48300. * @param scene The scene the light belongs to
  48301. */
  48302. function HemisphericLight(name, direction, scene) {
  48303. var _this = _super.call(this, name, scene) || this;
  48304. /**
  48305. * The groundColor is the light in the opposite direction to the one specified during creation.
  48306. * 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.
  48307. */
  48308. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48309. _this.direction = direction || BABYLON.Vector3.Up();
  48310. return _this;
  48311. }
  48312. HemisphericLight.prototype._buildUniformLayout = function () {
  48313. this._uniformBuffer.addUniform("vLightData", 4);
  48314. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48315. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48316. this._uniformBuffer.addUniform("vLightGround", 3);
  48317. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48318. this._uniformBuffer.addUniform("depthValues", 2);
  48319. this._uniformBuffer.create();
  48320. };
  48321. /**
  48322. * Returns the string "HemisphericLight".
  48323. * @return The class name
  48324. */
  48325. HemisphericLight.prototype.getClassName = function () {
  48326. return "HemisphericLight";
  48327. };
  48328. /**
  48329. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48330. * Returns the updated direction.
  48331. * @param target The target the direction should point to
  48332. * @return The computed direction
  48333. */
  48334. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48335. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48336. return this.direction;
  48337. };
  48338. /**
  48339. * Returns the shadow generator associated to the light.
  48340. * @returns Always null for hemispheric lights because it does not support shadows.
  48341. */
  48342. HemisphericLight.prototype.getShadowGenerator = function () {
  48343. return null;
  48344. };
  48345. /**
  48346. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48347. * @param effect The effect to update
  48348. * @param lightIndex The index of the light in the effect to update
  48349. * @returns The hemispheric light
  48350. */
  48351. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48352. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48353. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48354. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48355. return this;
  48356. };
  48357. /**
  48358. * @hidden internal use only.
  48359. */
  48360. HemisphericLight.prototype._getWorldMatrix = function () {
  48361. if (!this._worldMatrix) {
  48362. this._worldMatrix = BABYLON.Matrix.Identity();
  48363. }
  48364. return this._worldMatrix;
  48365. };
  48366. /**
  48367. * Returns the integer 3.
  48368. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48369. */
  48370. HemisphericLight.prototype.getTypeID = function () {
  48371. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48372. };
  48373. __decorate([
  48374. BABYLON.serializeAsColor3()
  48375. ], HemisphericLight.prototype, "groundColor", void 0);
  48376. __decorate([
  48377. BABYLON.serializeAsVector3()
  48378. ], HemisphericLight.prototype, "direction", void 0);
  48379. return HemisphericLight;
  48380. }(BABYLON.Light));
  48381. BABYLON.HemisphericLight = HemisphericLight;
  48382. })(BABYLON || (BABYLON = {}));
  48383. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48384. var BABYLON;
  48385. (function (BABYLON) {
  48386. /**
  48387. * Base implementation IShadowLight
  48388. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48389. */
  48390. var ShadowLight = /** @class */ (function (_super) {
  48391. __extends(ShadowLight, _super);
  48392. function ShadowLight() {
  48393. var _this = _super !== null && _super.apply(this, arguments) || this;
  48394. _this._needProjectionMatrixCompute = true;
  48395. return _this;
  48396. }
  48397. ShadowLight.prototype._setPosition = function (value) {
  48398. this._position = value;
  48399. };
  48400. Object.defineProperty(ShadowLight.prototype, "position", {
  48401. /**
  48402. * Sets the position the shadow will be casted from. Also use as the light position for both
  48403. * point and spot lights.
  48404. */
  48405. get: function () {
  48406. return this._position;
  48407. },
  48408. /**
  48409. * Sets the position the shadow will be casted from. Also use as the light position for both
  48410. * point and spot lights.
  48411. */
  48412. set: function (value) {
  48413. this._setPosition(value);
  48414. },
  48415. enumerable: true,
  48416. configurable: true
  48417. });
  48418. ShadowLight.prototype._setDirection = function (value) {
  48419. this._direction = value;
  48420. };
  48421. Object.defineProperty(ShadowLight.prototype, "direction", {
  48422. /**
  48423. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48424. * Also use as the light direction on spot and directional lights.
  48425. */
  48426. get: function () {
  48427. return this._direction;
  48428. },
  48429. /**
  48430. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48431. * Also use as the light direction on spot and directional lights.
  48432. */
  48433. set: function (value) {
  48434. this._setDirection(value);
  48435. },
  48436. enumerable: true,
  48437. configurable: true
  48438. });
  48439. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48440. /**
  48441. * Gets the shadow projection clipping minimum z value.
  48442. */
  48443. get: function () {
  48444. return this._shadowMinZ;
  48445. },
  48446. /**
  48447. * Sets the shadow projection clipping minimum z value.
  48448. */
  48449. set: function (value) {
  48450. this._shadowMinZ = value;
  48451. this.forceProjectionMatrixCompute();
  48452. },
  48453. enumerable: true,
  48454. configurable: true
  48455. });
  48456. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48457. /**
  48458. * Sets the shadow projection clipping maximum z value.
  48459. */
  48460. get: function () {
  48461. return this._shadowMaxZ;
  48462. },
  48463. /**
  48464. * Gets the shadow projection clipping maximum z value.
  48465. */
  48466. set: function (value) {
  48467. this._shadowMaxZ = value;
  48468. this.forceProjectionMatrixCompute();
  48469. },
  48470. enumerable: true,
  48471. configurable: true
  48472. });
  48473. /**
  48474. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48475. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48476. */
  48477. ShadowLight.prototype.computeTransformedInformation = function () {
  48478. if (this.parent && this.parent.getWorldMatrix) {
  48479. if (!this.transformedPosition) {
  48480. this.transformedPosition = BABYLON.Vector3.Zero();
  48481. }
  48482. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48483. // In case the direction is present.
  48484. if (this.direction) {
  48485. if (!this.transformedDirection) {
  48486. this.transformedDirection = BABYLON.Vector3.Zero();
  48487. }
  48488. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48489. }
  48490. return true;
  48491. }
  48492. return false;
  48493. };
  48494. /**
  48495. * Return the depth scale used for the shadow map.
  48496. * @returns the depth scale.
  48497. */
  48498. ShadowLight.prototype.getDepthScale = function () {
  48499. return 50.0;
  48500. };
  48501. /**
  48502. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48503. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48504. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48505. */
  48506. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48507. return this.transformedDirection ? this.transformedDirection : this.direction;
  48508. };
  48509. /**
  48510. * Returns the ShadowLight absolute position in the World.
  48511. * @returns the position vector in world space
  48512. */
  48513. ShadowLight.prototype.getAbsolutePosition = function () {
  48514. return this.transformedPosition ? this.transformedPosition : this.position;
  48515. };
  48516. /**
  48517. * Sets the ShadowLight direction toward the passed target.
  48518. * @param target The point tot target in local space
  48519. * @returns the updated ShadowLight direction
  48520. */
  48521. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48522. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48523. return this.direction;
  48524. };
  48525. /**
  48526. * Returns the light rotation in euler definition.
  48527. * @returns the x y z rotation in local space.
  48528. */
  48529. ShadowLight.prototype.getRotation = function () {
  48530. this.direction.normalize();
  48531. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48532. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48533. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48534. };
  48535. /**
  48536. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48537. * @returns true if a cube texture needs to be use
  48538. */
  48539. ShadowLight.prototype.needCube = function () {
  48540. return false;
  48541. };
  48542. /**
  48543. * Detects if the projection matrix requires to be recomputed this frame.
  48544. * @returns true if it requires to be recomputed otherwise, false.
  48545. */
  48546. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48547. return this._needProjectionMatrixCompute;
  48548. };
  48549. /**
  48550. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48551. */
  48552. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48553. this._needProjectionMatrixCompute = true;
  48554. };
  48555. /**
  48556. * Get the world matrix of the sahdow lights.
  48557. * @hidden Internal Use Only
  48558. */
  48559. ShadowLight.prototype._getWorldMatrix = function () {
  48560. if (!this._worldMatrix) {
  48561. this._worldMatrix = BABYLON.Matrix.Identity();
  48562. }
  48563. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48564. return this._worldMatrix;
  48565. };
  48566. /**
  48567. * Gets the minZ used for shadow according to both the scene and the light.
  48568. * @param activeCamera The camera we are returning the min for
  48569. * @returns the depth min z
  48570. */
  48571. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48572. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48573. };
  48574. /**
  48575. * Gets the maxZ used for shadow according to both the scene and the light.
  48576. * @param activeCamera The camera we are returning the max for
  48577. * @returns the depth max z
  48578. */
  48579. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48580. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48581. };
  48582. /**
  48583. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48584. * @param matrix The materix to updated with the projection information
  48585. * @param viewMatrix The transform matrix of the light
  48586. * @param renderList The list of mesh to render in the map
  48587. * @returns The current light
  48588. */
  48589. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48590. if (this.customProjectionMatrixBuilder) {
  48591. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48592. }
  48593. else {
  48594. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48595. }
  48596. return this;
  48597. };
  48598. __decorate([
  48599. BABYLON.serializeAsVector3()
  48600. ], ShadowLight.prototype, "position", null);
  48601. __decorate([
  48602. BABYLON.serializeAsVector3()
  48603. ], ShadowLight.prototype, "direction", null);
  48604. __decorate([
  48605. BABYLON.serialize()
  48606. ], ShadowLight.prototype, "shadowMinZ", null);
  48607. __decorate([
  48608. BABYLON.serialize()
  48609. ], ShadowLight.prototype, "shadowMaxZ", null);
  48610. return ShadowLight;
  48611. }(BABYLON.Light));
  48612. BABYLON.ShadowLight = ShadowLight;
  48613. })(BABYLON || (BABYLON = {}));
  48614. //# sourceMappingURL=babylon.shadowLight.js.map
  48615. var BABYLON;
  48616. (function (BABYLON) {
  48617. /**
  48618. * A point light is a light defined by an unique point in world space.
  48619. * The light is emitted in every direction from this point.
  48620. * A good example of a point light is a standard light bulb.
  48621. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48622. */
  48623. var PointLight = /** @class */ (function (_super) {
  48624. __extends(PointLight, _super);
  48625. /**
  48626. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48627. * A PointLight emits the light in every direction.
  48628. * It can cast shadows.
  48629. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48630. * ```javascript
  48631. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48632. * ```
  48633. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48634. * @param name The light friendly name
  48635. * @param position The position of the point light in the scene
  48636. * @param scene The scene the lights belongs to
  48637. */
  48638. function PointLight(name, position, scene) {
  48639. var _this = _super.call(this, name, scene) || this;
  48640. _this._shadowAngle = Math.PI / 2;
  48641. _this.position = position;
  48642. return _this;
  48643. }
  48644. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48645. /**
  48646. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48647. * This specifies what angle the shadow will use to be created.
  48648. *
  48649. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48650. */
  48651. get: function () {
  48652. return this._shadowAngle;
  48653. },
  48654. /**
  48655. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48656. * This specifies what angle the shadow will use to be created.
  48657. *
  48658. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48659. */
  48660. set: function (value) {
  48661. this._shadowAngle = value;
  48662. this.forceProjectionMatrixCompute();
  48663. },
  48664. enumerable: true,
  48665. configurable: true
  48666. });
  48667. Object.defineProperty(PointLight.prototype, "direction", {
  48668. /**
  48669. * Gets the direction if it has been set.
  48670. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48671. */
  48672. get: function () {
  48673. return this._direction;
  48674. },
  48675. /**
  48676. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48677. */
  48678. set: function (value) {
  48679. var previousNeedCube = this.needCube();
  48680. this._direction = value;
  48681. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48682. this._shadowGenerator.recreateShadowMap();
  48683. }
  48684. },
  48685. enumerable: true,
  48686. configurable: true
  48687. });
  48688. /**
  48689. * Returns the string "PointLight"
  48690. * @returns the class name
  48691. */
  48692. PointLight.prototype.getClassName = function () {
  48693. return "PointLight";
  48694. };
  48695. /**
  48696. * Returns the integer 0.
  48697. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48698. */
  48699. PointLight.prototype.getTypeID = function () {
  48700. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48701. };
  48702. /**
  48703. * Specifies wether or not the shadowmap should be a cube texture.
  48704. * @returns true if the shadowmap needs to be a cube texture.
  48705. */
  48706. PointLight.prototype.needCube = function () {
  48707. return !this.direction;
  48708. };
  48709. /**
  48710. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48711. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48712. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48713. */
  48714. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48715. if (this.direction) {
  48716. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48717. }
  48718. else {
  48719. switch (faceIndex) {
  48720. case 0:
  48721. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48722. case 1:
  48723. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48724. case 2:
  48725. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48726. case 3:
  48727. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48728. case 4:
  48729. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48730. case 5:
  48731. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48732. }
  48733. }
  48734. return BABYLON.Vector3.Zero();
  48735. };
  48736. /**
  48737. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48738. * - fov = PI / 2
  48739. * - aspect ratio : 1.0
  48740. * - z-near and far equal to the active camera minZ and maxZ.
  48741. * Returns the PointLight.
  48742. */
  48743. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48744. var activeCamera = this.getScene().activeCamera;
  48745. if (!activeCamera) {
  48746. return;
  48747. }
  48748. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48749. };
  48750. PointLight.prototype._buildUniformLayout = function () {
  48751. this._uniformBuffer.addUniform("vLightData", 4);
  48752. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48753. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48754. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48755. this._uniformBuffer.addUniform("depthValues", 2);
  48756. this._uniformBuffer.create();
  48757. };
  48758. /**
  48759. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48760. * @param effect The effect to update
  48761. * @param lightIndex The index of the light in the effect to update
  48762. * @returns The point light
  48763. */
  48764. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48765. if (this.computeTransformedInformation()) {
  48766. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48767. return this;
  48768. }
  48769. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48770. return this;
  48771. };
  48772. __decorate([
  48773. BABYLON.serialize()
  48774. ], PointLight.prototype, "shadowAngle", null);
  48775. return PointLight;
  48776. }(BABYLON.ShadowLight));
  48777. BABYLON.PointLight = PointLight;
  48778. })(BABYLON || (BABYLON = {}));
  48779. //# sourceMappingURL=babylon.pointLight.js.map
  48780. var BABYLON;
  48781. (function (BABYLON) {
  48782. /**
  48783. * A directional light is defined by a direction (what a surprise!).
  48784. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48785. * 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.
  48786. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48787. */
  48788. var DirectionalLight = /** @class */ (function (_super) {
  48789. __extends(DirectionalLight, _super);
  48790. /**
  48791. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48792. * The directional light is emitted from everywhere in the given direction.
  48793. * It can cast shawdows.
  48794. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48795. * @param name The friendly name of the light
  48796. * @param direction The direction of the light
  48797. * @param scene The scene the light belongs to
  48798. */
  48799. function DirectionalLight(name, direction, scene) {
  48800. var _this = _super.call(this, name, scene) || this;
  48801. _this._shadowFrustumSize = 0;
  48802. _this._shadowOrthoScale = 0.1;
  48803. /**
  48804. * Automatically compute the projection matrix to best fit (including all the casters)
  48805. * on each frame.
  48806. */
  48807. _this.autoUpdateExtends = true;
  48808. // Cache
  48809. _this._orthoLeft = Number.MAX_VALUE;
  48810. _this._orthoRight = Number.MIN_VALUE;
  48811. _this._orthoTop = Number.MIN_VALUE;
  48812. _this._orthoBottom = Number.MAX_VALUE;
  48813. _this.position = direction.scale(-1.0);
  48814. _this.direction = direction;
  48815. return _this;
  48816. }
  48817. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48818. /**
  48819. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48820. */
  48821. get: function () {
  48822. return this._shadowFrustumSize;
  48823. },
  48824. /**
  48825. * Specifies a fix frustum size for the shadow generation.
  48826. */
  48827. set: function (value) {
  48828. this._shadowFrustumSize = value;
  48829. this.forceProjectionMatrixCompute();
  48830. },
  48831. enumerable: true,
  48832. configurable: true
  48833. });
  48834. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48835. /**
  48836. * Gets the shadow projection scale against the optimal computed one.
  48837. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48838. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48839. */
  48840. get: function () {
  48841. return this._shadowOrthoScale;
  48842. },
  48843. /**
  48844. * Sets the shadow projection scale against the optimal computed one.
  48845. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48846. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48847. */
  48848. set: function (value) {
  48849. this._shadowOrthoScale = value;
  48850. this.forceProjectionMatrixCompute();
  48851. },
  48852. enumerable: true,
  48853. configurable: true
  48854. });
  48855. /**
  48856. * Returns the string "DirectionalLight".
  48857. * @return The class name
  48858. */
  48859. DirectionalLight.prototype.getClassName = function () {
  48860. return "DirectionalLight";
  48861. };
  48862. /**
  48863. * Returns the integer 1.
  48864. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48865. */
  48866. DirectionalLight.prototype.getTypeID = function () {
  48867. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48868. };
  48869. /**
  48870. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48871. * Returns the DirectionalLight Shadow projection matrix.
  48872. */
  48873. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48874. if (this.shadowFrustumSize > 0) {
  48875. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48876. }
  48877. else {
  48878. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48879. }
  48880. };
  48881. /**
  48882. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48883. * Returns the DirectionalLight Shadow projection matrix.
  48884. */
  48885. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48886. var activeCamera = this.getScene().activeCamera;
  48887. if (!activeCamera) {
  48888. return;
  48889. }
  48890. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48891. };
  48892. /**
  48893. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48894. * Returns the DirectionalLight Shadow projection matrix.
  48895. */
  48896. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48897. var activeCamera = this.getScene().activeCamera;
  48898. if (!activeCamera) {
  48899. return;
  48900. }
  48901. // Check extends
  48902. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48903. var tempVector3 = BABYLON.Vector3.Zero();
  48904. this._orthoLeft = Number.MAX_VALUE;
  48905. this._orthoRight = Number.MIN_VALUE;
  48906. this._orthoTop = Number.MIN_VALUE;
  48907. this._orthoBottom = Number.MAX_VALUE;
  48908. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48909. var mesh = renderList[meshIndex];
  48910. if (!mesh) {
  48911. continue;
  48912. }
  48913. var boundingInfo = mesh.getBoundingInfo();
  48914. var boundingBox = boundingInfo.boundingBox;
  48915. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48916. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48917. if (tempVector3.x < this._orthoLeft)
  48918. this._orthoLeft = tempVector3.x;
  48919. if (tempVector3.y < this._orthoBottom)
  48920. this._orthoBottom = tempVector3.y;
  48921. if (tempVector3.x > this._orthoRight)
  48922. this._orthoRight = tempVector3.x;
  48923. if (tempVector3.y > this._orthoTop)
  48924. this._orthoTop = tempVector3.y;
  48925. }
  48926. }
  48927. }
  48928. var xOffset = this._orthoRight - this._orthoLeft;
  48929. var yOffset = this._orthoTop - this._orthoBottom;
  48930. 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);
  48931. };
  48932. DirectionalLight.prototype._buildUniformLayout = function () {
  48933. this._uniformBuffer.addUniform("vLightData", 4);
  48934. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48935. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48936. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48937. this._uniformBuffer.addUniform("depthValues", 2);
  48938. this._uniformBuffer.create();
  48939. };
  48940. /**
  48941. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48942. * @param effect The effect to update
  48943. * @param lightIndex The index of the light in the effect to update
  48944. * @returns The directional light
  48945. */
  48946. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48947. if (this.computeTransformedInformation()) {
  48948. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48949. return this;
  48950. }
  48951. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48952. return this;
  48953. };
  48954. /**
  48955. * Gets the minZ used for shadow according to both the scene and the light.
  48956. *
  48957. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48958. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48959. * @param activeCamera The camera we are returning the min for
  48960. * @returns the depth min z
  48961. */
  48962. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48963. return 1;
  48964. };
  48965. /**
  48966. * Gets the maxZ used for shadow according to both the scene and the light.
  48967. *
  48968. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48969. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48970. * @param activeCamera The camera we are returning the max for
  48971. * @returns the depth max z
  48972. */
  48973. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48974. return 1;
  48975. };
  48976. __decorate([
  48977. BABYLON.serialize()
  48978. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48979. __decorate([
  48980. BABYLON.serialize()
  48981. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48982. __decorate([
  48983. BABYLON.serialize()
  48984. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48985. return DirectionalLight;
  48986. }(BABYLON.ShadowLight));
  48987. BABYLON.DirectionalLight = DirectionalLight;
  48988. })(BABYLON || (BABYLON = {}));
  48989. //# sourceMappingURL=babylon.directionalLight.js.map
  48990. var BABYLON;
  48991. (function (BABYLON) {
  48992. /**
  48993. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48994. * These values define a cone of light starting from the position, emitting toward the direction.
  48995. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48996. * and the exponent defines the speed of the decay of the light with distance (reach).
  48997. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48998. */
  48999. var SpotLight = /** @class */ (function (_super) {
  49000. __extends(SpotLight, _super);
  49001. /**
  49002. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49003. * It can cast shadows.
  49004. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49005. * @param name The light friendly name
  49006. * @param position The position of the spot light in the scene
  49007. * @param direction The direction of the light in the scene
  49008. * @param angle The cone angle of the light in Radians
  49009. * @param exponent The light decay speed with the distance from the emission spot
  49010. * @param scene The scene the lights belongs to
  49011. */
  49012. function SpotLight(name, position, direction, angle, exponent, scene) {
  49013. var _this = _super.call(this, name, scene) || this;
  49014. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49015. _this._projectionTextureLightNear = 1e-6;
  49016. _this._projectionTextureLightFar = 1000.0;
  49017. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49018. _this._projectionTextureViewLightDirty = true;
  49019. _this._projectionTextureProjectionLightDirty = true;
  49020. _this._projectionTextureDirty = true;
  49021. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49022. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49023. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49024. _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);
  49025. _this.position = position;
  49026. _this.direction = direction;
  49027. _this.angle = angle;
  49028. _this.exponent = exponent;
  49029. return _this;
  49030. }
  49031. Object.defineProperty(SpotLight.prototype, "angle", {
  49032. /**
  49033. * Gets the cone angle of the spot light in Radians.
  49034. */
  49035. get: function () {
  49036. return this._angle;
  49037. },
  49038. /**
  49039. * Sets the cone angle of the spot light in Radians.
  49040. */
  49041. set: function (value) {
  49042. this._angle = value;
  49043. this._projectionTextureProjectionLightDirty = true;
  49044. this.forceProjectionMatrixCompute();
  49045. },
  49046. enumerable: true,
  49047. configurable: true
  49048. });
  49049. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49050. /**
  49051. * Allows scaling the angle of the light for shadow generation only.
  49052. */
  49053. get: function () {
  49054. return this._shadowAngleScale;
  49055. },
  49056. /**
  49057. * Allows scaling the angle of the light for shadow generation only.
  49058. */
  49059. set: function (value) {
  49060. this._shadowAngleScale = value;
  49061. this.forceProjectionMatrixCompute();
  49062. },
  49063. enumerable: true,
  49064. configurable: true
  49065. });
  49066. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49067. /**
  49068. * Allows reading the projecton texture
  49069. */
  49070. get: function () {
  49071. return this._projectionTextureMatrix;
  49072. },
  49073. enumerable: true,
  49074. configurable: true
  49075. });
  49076. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49077. /**
  49078. * Gets the near clip of the Spotlight for texture projection.
  49079. */
  49080. get: function () {
  49081. return this._projectionTextureLightNear;
  49082. },
  49083. /**
  49084. * Sets the near clip of the Spotlight for texture projection.
  49085. */
  49086. set: function (value) {
  49087. this._projectionTextureLightNear = value;
  49088. this._projectionTextureProjectionLightDirty = true;
  49089. },
  49090. enumerable: true,
  49091. configurable: true
  49092. });
  49093. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49094. /**
  49095. * Gets the far clip of the Spotlight for texture projection.
  49096. */
  49097. get: function () {
  49098. return this._projectionTextureLightFar;
  49099. },
  49100. /**
  49101. * Sets the far clip of the Spotlight for texture projection.
  49102. */
  49103. set: function (value) {
  49104. this._projectionTextureLightFar = value;
  49105. this._projectionTextureProjectionLightDirty = true;
  49106. },
  49107. enumerable: true,
  49108. configurable: true
  49109. });
  49110. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49111. /**
  49112. * Gets the Up vector of the Spotlight for texture projection.
  49113. */
  49114. get: function () {
  49115. return this._projectionTextureUpDirection;
  49116. },
  49117. /**
  49118. * Sets the Up vector of the Spotlight for texture projection.
  49119. */
  49120. set: function (value) {
  49121. this._projectionTextureUpDirection = value;
  49122. this._projectionTextureProjectionLightDirty = true;
  49123. },
  49124. enumerable: true,
  49125. configurable: true
  49126. });
  49127. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49128. /**
  49129. * Gets the projection texture of the light.
  49130. */
  49131. get: function () {
  49132. return this._projectionTexture;
  49133. },
  49134. /**
  49135. * Sets the projection texture of the light.
  49136. */
  49137. set: function (value) {
  49138. this._projectionTexture = value;
  49139. this._projectionTextureDirty = true;
  49140. },
  49141. enumerable: true,
  49142. configurable: true
  49143. });
  49144. /**
  49145. * Returns the string "SpotLight".
  49146. * @returns the class name
  49147. */
  49148. SpotLight.prototype.getClassName = function () {
  49149. return "SpotLight";
  49150. };
  49151. /**
  49152. * Returns the integer 2.
  49153. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49154. */
  49155. SpotLight.prototype.getTypeID = function () {
  49156. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49157. };
  49158. /**
  49159. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49160. */
  49161. SpotLight.prototype._setDirection = function (value) {
  49162. _super.prototype._setDirection.call(this, value);
  49163. this._projectionTextureViewLightDirty = true;
  49164. };
  49165. /**
  49166. * Overrides the position setter to recompute the projection texture view light Matrix.
  49167. */
  49168. SpotLight.prototype._setPosition = function (value) {
  49169. _super.prototype._setPosition.call(this, value);
  49170. this._projectionTextureViewLightDirty = true;
  49171. };
  49172. /**
  49173. * 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.
  49174. * Returns the SpotLight.
  49175. */
  49176. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49177. var activeCamera = this.getScene().activeCamera;
  49178. if (!activeCamera) {
  49179. return;
  49180. }
  49181. this._shadowAngleScale = this._shadowAngleScale || 1;
  49182. var angle = this._shadowAngleScale * this._angle;
  49183. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49184. };
  49185. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49186. this._projectionTextureViewLightDirty = false;
  49187. this._projectionTextureDirty = true;
  49188. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49189. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49190. };
  49191. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49192. this._projectionTextureProjectionLightDirty = false;
  49193. this._projectionTextureDirty = true;
  49194. var light_far = this.projectionTextureLightFar;
  49195. var light_near = this.projectionTextureLightNear;
  49196. var P = light_far / (light_far - light_near);
  49197. var Q = -P * light_near;
  49198. var S = 1.0 / Math.tan(this._angle / 2.0);
  49199. var A = 1.0;
  49200. 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);
  49201. };
  49202. /**
  49203. * Main function for light texture projection matrix computing.
  49204. */
  49205. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49206. this._projectionTextureDirty = false;
  49207. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49208. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49209. };
  49210. SpotLight.prototype._buildUniformLayout = function () {
  49211. this._uniformBuffer.addUniform("vLightData", 4);
  49212. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49213. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49214. this._uniformBuffer.addUniform("vLightDirection", 3);
  49215. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49216. this._uniformBuffer.addUniform("depthValues", 2);
  49217. this._uniformBuffer.create();
  49218. };
  49219. /**
  49220. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49221. * @param effect The effect to update
  49222. * @param lightIndex The index of the light in the effect to update
  49223. * @returns The spot light
  49224. */
  49225. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49226. var normalizeDirection;
  49227. if (this.computeTransformedInformation()) {
  49228. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49229. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49230. }
  49231. else {
  49232. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49233. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49234. }
  49235. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49236. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49237. if (this._projectionTextureViewLightDirty) {
  49238. this._computeProjectionTextureViewLightMatrix();
  49239. }
  49240. if (this._projectionTextureProjectionLightDirty) {
  49241. this._computeProjectionTextureProjectionLightMatrix();
  49242. }
  49243. if (this._projectionTextureDirty) {
  49244. this._computeProjectionTextureMatrix();
  49245. }
  49246. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49247. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49248. }
  49249. return this;
  49250. };
  49251. /**
  49252. * Disposes the light and the associated resources.
  49253. */
  49254. SpotLight.prototype.dispose = function () {
  49255. _super.prototype.dispose.call(this);
  49256. if (this._projectionTexture) {
  49257. this._projectionTexture.dispose();
  49258. }
  49259. };
  49260. __decorate([
  49261. BABYLON.serialize()
  49262. ], SpotLight.prototype, "angle", null);
  49263. __decorate([
  49264. BABYLON.serialize()
  49265. ], SpotLight.prototype, "shadowAngleScale", null);
  49266. __decorate([
  49267. BABYLON.serialize()
  49268. ], SpotLight.prototype, "exponent", void 0);
  49269. __decorate([
  49270. BABYLON.serialize()
  49271. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49272. __decorate([
  49273. BABYLON.serialize()
  49274. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49275. __decorate([
  49276. BABYLON.serialize()
  49277. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49278. __decorate([
  49279. BABYLON.serializeAsTexture("projectedLightTexture")
  49280. ], SpotLight.prototype, "_projectionTexture", void 0);
  49281. return SpotLight;
  49282. }(BABYLON.ShadowLight));
  49283. BABYLON.SpotLight = SpotLight;
  49284. })(BABYLON || (BABYLON = {}));
  49285. //# sourceMappingURL=babylon.spotLight.js.map
  49286. var BABYLON;
  49287. (function (BABYLON) {
  49288. /**
  49289. * Class used to override all child animations of a given target
  49290. */
  49291. var AnimationPropertiesOverride = /** @class */ (function () {
  49292. function AnimationPropertiesOverride() {
  49293. /**
  49294. * Gets or sets a value indicating if animation blending must be used
  49295. */
  49296. this.enableBlending = false;
  49297. /**
  49298. * Gets or sets the blending speed to use when enableBlending is true
  49299. */
  49300. this.blendingSpeed = 0.01;
  49301. /**
  49302. * Gets or sets the default loop mode to use
  49303. */
  49304. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49305. }
  49306. return AnimationPropertiesOverride;
  49307. }());
  49308. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49309. })(BABYLON || (BABYLON = {}));
  49310. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49311. var BABYLON;
  49312. (function (BABYLON) {
  49313. /**
  49314. * Represents the range of an animation
  49315. */
  49316. var AnimationRange = /** @class */ (function () {
  49317. /**
  49318. * Initializes the range of an animation
  49319. * @param name The name of the animation range
  49320. * @param from The starting frame of the animation
  49321. * @param to The ending frame of the animation
  49322. */
  49323. function AnimationRange(
  49324. /**The name of the animation range**/
  49325. name,
  49326. /**The starting frame of the animation */
  49327. from,
  49328. /**The ending frame of the animation*/
  49329. to) {
  49330. this.name = name;
  49331. this.from = from;
  49332. this.to = to;
  49333. }
  49334. /**
  49335. * Makes a copy of the animation range
  49336. * @returns A copy of the animation range
  49337. */
  49338. AnimationRange.prototype.clone = function () {
  49339. return new AnimationRange(this.name, this.from, this.to);
  49340. };
  49341. return AnimationRange;
  49342. }());
  49343. BABYLON.AnimationRange = AnimationRange;
  49344. /**
  49345. * Composed of a frame, and an action function
  49346. */
  49347. var AnimationEvent = /** @class */ (function () {
  49348. /**
  49349. * Initializes the animation event
  49350. * @param frame The frame for which the event is triggered
  49351. * @param action The event to perform when triggered
  49352. * @param onlyOnce Specifies if the event should be triggered only once
  49353. */
  49354. function AnimationEvent(
  49355. /** The frame for which the event is triggered **/
  49356. frame,
  49357. /** The event to perform when triggered **/
  49358. action,
  49359. /** Specifies if the event should be triggered only once**/
  49360. onlyOnce) {
  49361. this.frame = frame;
  49362. this.action = action;
  49363. this.onlyOnce = onlyOnce;
  49364. /**
  49365. * Specifies if the animation event is done
  49366. */
  49367. this.isDone = false;
  49368. }
  49369. /** @hidden */
  49370. AnimationEvent.prototype._clone = function () {
  49371. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49372. };
  49373. return AnimationEvent;
  49374. }());
  49375. BABYLON.AnimationEvent = AnimationEvent;
  49376. /**
  49377. * A cursor which tracks a point on a path
  49378. */
  49379. var PathCursor = /** @class */ (function () {
  49380. /**
  49381. * Initializes the path cursor
  49382. * @param path The path to track
  49383. */
  49384. function PathCursor(path) {
  49385. this.path = path;
  49386. /**
  49387. * Stores path cursor callbacks for when an onchange event is triggered
  49388. */
  49389. this._onchange = new Array();
  49390. /**
  49391. * The value of the path cursor
  49392. */
  49393. this.value = 0;
  49394. /**
  49395. * The animation array of the path cursor
  49396. */
  49397. this.animations = new Array();
  49398. }
  49399. /**
  49400. * Gets the cursor point on the path
  49401. * @returns A point on the path cursor at the cursor location
  49402. */
  49403. PathCursor.prototype.getPoint = function () {
  49404. var point = this.path.getPointAtLengthPosition(this.value);
  49405. return new BABYLON.Vector3(point.x, 0, point.y);
  49406. };
  49407. /**
  49408. * Moves the cursor ahead by the step amount
  49409. * @param step The amount to move the cursor forward
  49410. * @returns This path cursor
  49411. */
  49412. PathCursor.prototype.moveAhead = function (step) {
  49413. if (step === void 0) { step = 0.002; }
  49414. this.move(step);
  49415. return this;
  49416. };
  49417. /**
  49418. * Moves the cursor behind by the step amount
  49419. * @param step The amount to move the cursor back
  49420. * @returns This path cursor
  49421. */
  49422. PathCursor.prototype.moveBack = function (step) {
  49423. if (step === void 0) { step = 0.002; }
  49424. this.move(-step);
  49425. return this;
  49426. };
  49427. /**
  49428. * Moves the cursor by the step amount
  49429. * If the step amount is greater than one, an exception is thrown
  49430. * @param step The amount to move the cursor
  49431. * @returns This path cursor
  49432. */
  49433. PathCursor.prototype.move = function (step) {
  49434. if (Math.abs(step) > 1) {
  49435. throw "step size should be less than 1.";
  49436. }
  49437. this.value += step;
  49438. this.ensureLimits();
  49439. this.raiseOnChange();
  49440. return this;
  49441. };
  49442. /**
  49443. * Ensures that the value is limited between zero and one
  49444. * @returns This path cursor
  49445. */
  49446. PathCursor.prototype.ensureLimits = function () {
  49447. while (this.value > 1) {
  49448. this.value -= 1;
  49449. }
  49450. while (this.value < 0) {
  49451. this.value += 1;
  49452. }
  49453. return this;
  49454. };
  49455. /**
  49456. * Runs onchange callbacks on change (used by the animation engine)
  49457. * @returns This path cursor
  49458. */
  49459. PathCursor.prototype.raiseOnChange = function () {
  49460. var _this = this;
  49461. this._onchange.forEach(function (f) { return f(_this); });
  49462. return this;
  49463. };
  49464. /**
  49465. * Executes a function on change
  49466. * @param f A path cursor onchange callback
  49467. * @returns This path cursor
  49468. */
  49469. PathCursor.prototype.onchange = function (f) {
  49470. this._onchange.push(f);
  49471. return this;
  49472. };
  49473. return PathCursor;
  49474. }());
  49475. BABYLON.PathCursor = PathCursor;
  49476. /**
  49477. * Enum for the animation key frame interpolation type
  49478. */
  49479. var AnimationKeyInterpolation;
  49480. (function (AnimationKeyInterpolation) {
  49481. /**
  49482. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49483. */
  49484. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49485. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49486. /**
  49487. * Class used to store any kind of animation
  49488. */
  49489. var Animation = /** @class */ (function () {
  49490. /**
  49491. * Initializes the animation
  49492. * @param name Name of the animation
  49493. * @param targetProperty Property to animate
  49494. * @param framePerSecond The frames per second of the animation
  49495. * @param dataType The data type of the animation
  49496. * @param loopMode The loop mode of the animation
  49497. * @param enableBlendings Specifies if blending should be enabled
  49498. */
  49499. function Animation(
  49500. /**Name of the animation */
  49501. name,
  49502. /**Property to animate */
  49503. targetProperty,
  49504. /**The frames per second of the animation */
  49505. framePerSecond,
  49506. /**The data type of the animation */
  49507. dataType,
  49508. /**The loop mode of the animation */
  49509. loopMode,
  49510. /**Specifies if blending should be enabled */
  49511. enableBlending) {
  49512. this.name = name;
  49513. this.targetProperty = targetProperty;
  49514. this.framePerSecond = framePerSecond;
  49515. this.dataType = dataType;
  49516. this.loopMode = loopMode;
  49517. this.enableBlending = enableBlending;
  49518. /**
  49519. * @hidden Internal use only
  49520. */
  49521. this._runtimeAnimations = new Array();
  49522. /**
  49523. * The set of event that will be linked to this animation
  49524. */
  49525. this._events = new Array();
  49526. /**
  49527. * Stores the blending speed of the animation
  49528. */
  49529. this.blendingSpeed = 0.01;
  49530. /**
  49531. * Stores the animation ranges for the animation
  49532. */
  49533. this._ranges = {};
  49534. this.targetPropertyPath = targetProperty.split(".");
  49535. this.dataType = dataType;
  49536. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49537. }
  49538. /**
  49539. * @hidden Internal use
  49540. */
  49541. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49542. var dataType = undefined;
  49543. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49544. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49545. }
  49546. else if (from instanceof BABYLON.Quaternion) {
  49547. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49548. }
  49549. else if (from instanceof BABYLON.Vector3) {
  49550. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49551. }
  49552. else if (from instanceof BABYLON.Vector2) {
  49553. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49554. }
  49555. else if (from instanceof BABYLON.Color3) {
  49556. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49557. }
  49558. else if (from instanceof BABYLON.Size) {
  49559. dataType = Animation.ANIMATIONTYPE_SIZE;
  49560. }
  49561. if (dataType == undefined) {
  49562. return null;
  49563. }
  49564. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49565. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49566. animation.setKeys(keys);
  49567. if (easingFunction !== undefined) {
  49568. animation.setEasingFunction(easingFunction);
  49569. }
  49570. return animation;
  49571. };
  49572. /**
  49573. * Sets up an animation
  49574. * @param property The property to animate
  49575. * @param animationType The animation type to apply
  49576. * @param framePerSecond The frames per second of the animation
  49577. * @param easingFunction The easing function used in the animation
  49578. * @returns The created animation
  49579. */
  49580. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49581. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49582. animation.setEasingFunction(easingFunction);
  49583. return animation;
  49584. };
  49585. /**
  49586. * Create and start an animation on a node
  49587. * @param name defines the name of the global animation that will be run on all nodes
  49588. * @param node defines the root node where the animation will take place
  49589. * @param targetProperty defines property to animate
  49590. * @param framePerSecond defines the number of frame per second yo use
  49591. * @param totalFrame defines the number of frames in total
  49592. * @param from defines the initial value
  49593. * @param to defines the final value
  49594. * @param loopMode defines which loop mode you want to use (off by default)
  49595. * @param easingFunction defines the easing function to use (linear by default)
  49596. * @param onAnimationEnd defines the callback to call when animation end
  49597. * @returns the animatable created for this animation
  49598. */
  49599. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49600. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49601. if (!animation) {
  49602. return null;
  49603. }
  49604. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49605. };
  49606. /**
  49607. * Create and start an animation on a node and its descendants
  49608. * @param name defines the name of the global animation that will be run on all nodes
  49609. * @param node defines the root node where the animation will take place
  49610. * @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
  49611. * @param targetProperty defines property to animate
  49612. * @param framePerSecond defines the number of frame per second to use
  49613. * @param totalFrame defines the number of frames in total
  49614. * @param from defines the initial value
  49615. * @param to defines the final value
  49616. * @param loopMode defines which loop mode you want to use (off by default)
  49617. * @param easingFunction defines the easing function to use (linear by default)
  49618. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49619. * @returns the list of animatables created for all nodes
  49620. * @example https://www.babylonjs-playground.com/#MH0VLI
  49621. */
  49622. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49623. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49624. if (!animation) {
  49625. return null;
  49626. }
  49627. var scene = node.getScene();
  49628. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49629. };
  49630. /**
  49631. * Creates a new animation, merges it with the existing animations and starts it
  49632. * @param name Name of the animation
  49633. * @param node Node which contains the scene that begins the animations
  49634. * @param targetProperty Specifies which property to animate
  49635. * @param framePerSecond The frames per second of the animation
  49636. * @param totalFrame The total number of frames
  49637. * @param from The frame at the beginning of the animation
  49638. * @param to The frame at the end of the animation
  49639. * @param loopMode Specifies the loop mode of the animation
  49640. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49641. * @param onAnimationEnd Callback to run once the animation is complete
  49642. * @returns Nullable animation
  49643. */
  49644. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49645. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49646. if (!animation) {
  49647. return null;
  49648. }
  49649. node.animations.push(animation);
  49650. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49651. };
  49652. /**
  49653. * Transition property of an host to the target Value
  49654. * @param property The property to transition
  49655. * @param targetValue The target Value of the property
  49656. * @param host The object where the property to animate belongs
  49657. * @param scene Scene used to run the animation
  49658. * @param frameRate Framerate (in frame/s) to use
  49659. * @param transition The transition type we want to use
  49660. * @param duration The duration of the animation, in milliseconds
  49661. * @param onAnimationEnd Callback trigger at the end of the animation
  49662. * @returns Nullable animation
  49663. */
  49664. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49665. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49666. if (duration <= 0) {
  49667. host[property] = targetValue;
  49668. if (onAnimationEnd) {
  49669. onAnimationEnd();
  49670. }
  49671. return null;
  49672. }
  49673. var endFrame = frameRate * (duration / 1000);
  49674. transition.setKeys([{
  49675. frame: 0,
  49676. value: host[property].clone ? host[property].clone() : host[property]
  49677. },
  49678. {
  49679. frame: endFrame,
  49680. value: targetValue
  49681. }]);
  49682. if (!host.animations) {
  49683. host.animations = [];
  49684. }
  49685. host.animations.push(transition);
  49686. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49687. animation.onAnimationEnd = onAnimationEnd;
  49688. return animation;
  49689. };
  49690. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49691. /**
  49692. * Return the array of runtime animations currently using this animation
  49693. */
  49694. get: function () {
  49695. return this._runtimeAnimations;
  49696. },
  49697. enumerable: true,
  49698. configurable: true
  49699. });
  49700. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49701. /**
  49702. * Specifies if any of the runtime animations are currently running
  49703. */
  49704. get: function () {
  49705. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49706. var runtimeAnimation = _a[_i];
  49707. if (!runtimeAnimation.isStopped) {
  49708. return true;
  49709. }
  49710. }
  49711. return false;
  49712. },
  49713. enumerable: true,
  49714. configurable: true
  49715. });
  49716. // Methods
  49717. /**
  49718. * Converts the animation to a string
  49719. * @param fullDetails support for multiple levels of logging within scene loading
  49720. * @returns String form of the animation
  49721. */
  49722. Animation.prototype.toString = function (fullDetails) {
  49723. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49724. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49725. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49726. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49727. if (fullDetails) {
  49728. ret += ", Ranges: {";
  49729. var first = true;
  49730. for (var name in this._ranges) {
  49731. if (first) {
  49732. ret += ", ";
  49733. first = false;
  49734. }
  49735. ret += name;
  49736. }
  49737. ret += "}";
  49738. }
  49739. return ret;
  49740. };
  49741. /**
  49742. * Add an event to this animation
  49743. * @param event Event to add
  49744. */
  49745. Animation.prototype.addEvent = function (event) {
  49746. this._events.push(event);
  49747. };
  49748. /**
  49749. * Remove all events found at the given frame
  49750. * @param frame The frame to remove events from
  49751. */
  49752. Animation.prototype.removeEvents = function (frame) {
  49753. for (var index = 0; index < this._events.length; index++) {
  49754. if (this._events[index].frame === frame) {
  49755. this._events.splice(index, 1);
  49756. index--;
  49757. }
  49758. }
  49759. };
  49760. /**
  49761. * Retrieves all the events from the animation
  49762. * @returns Events from the animation
  49763. */
  49764. Animation.prototype.getEvents = function () {
  49765. return this._events;
  49766. };
  49767. /**
  49768. * Creates an animation range
  49769. * @param name Name of the animation range
  49770. * @param from Starting frame of the animation range
  49771. * @param to Ending frame of the animation
  49772. */
  49773. Animation.prototype.createRange = function (name, from, to) {
  49774. // check name not already in use; could happen for bones after serialized
  49775. if (!this._ranges[name]) {
  49776. this._ranges[name] = new AnimationRange(name, from, to);
  49777. }
  49778. };
  49779. /**
  49780. * Deletes an animation range by name
  49781. * @param name Name of the animation range to delete
  49782. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49783. */
  49784. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49785. if (deleteFrames === void 0) { deleteFrames = true; }
  49786. var range = this._ranges[name];
  49787. if (!range) {
  49788. return;
  49789. }
  49790. if (deleteFrames) {
  49791. var from = range.from;
  49792. var to = range.to;
  49793. // this loop MUST go high to low for multiple splices to work
  49794. for (var key = this._keys.length - 1; key >= 0; key--) {
  49795. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49796. this._keys.splice(key, 1);
  49797. }
  49798. }
  49799. }
  49800. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49801. };
  49802. /**
  49803. * Gets the animation range by name, or null if not defined
  49804. * @param name Name of the animation range
  49805. * @returns Nullable animation range
  49806. */
  49807. Animation.prototype.getRange = function (name) {
  49808. return this._ranges[name];
  49809. };
  49810. /**
  49811. * Gets the key frames from the animation
  49812. * @returns The key frames of the animation
  49813. */
  49814. Animation.prototype.getKeys = function () {
  49815. return this._keys;
  49816. };
  49817. /**
  49818. * Gets the highest frame rate of the animation
  49819. * @returns Highest frame rate of the animation
  49820. */
  49821. Animation.prototype.getHighestFrame = function () {
  49822. var ret = 0;
  49823. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49824. if (ret < this._keys[key].frame) {
  49825. ret = this._keys[key].frame;
  49826. }
  49827. }
  49828. return ret;
  49829. };
  49830. /**
  49831. * Gets the easing function of the animation
  49832. * @returns Easing function of the animation
  49833. */
  49834. Animation.prototype.getEasingFunction = function () {
  49835. return this._easingFunction;
  49836. };
  49837. /**
  49838. * Sets the easing function of the animation
  49839. * @param easingFunction A custom mathematical formula for animation
  49840. */
  49841. Animation.prototype.setEasingFunction = function (easingFunction) {
  49842. this._easingFunction = easingFunction;
  49843. };
  49844. /**
  49845. * Interpolates a scalar linearly
  49846. * @param startValue Start value of the animation curve
  49847. * @param endValue End value of the animation curve
  49848. * @param gradient Scalar amount to interpolate
  49849. * @returns Interpolated scalar value
  49850. */
  49851. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49852. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49853. };
  49854. /**
  49855. * Interpolates a scalar cubically
  49856. * @param startValue Start value of the animation curve
  49857. * @param outTangent End tangent of the animation
  49858. * @param endValue End value of the animation curve
  49859. * @param inTangent Start tangent of the animation curve
  49860. * @param gradient Scalar amount to interpolate
  49861. * @returns Interpolated scalar value
  49862. */
  49863. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49864. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49865. };
  49866. /**
  49867. * Interpolates a quaternion using a spherical linear interpolation
  49868. * @param startValue Start value of the animation curve
  49869. * @param endValue End value of the animation curve
  49870. * @param gradient Scalar amount to interpolate
  49871. * @returns Interpolated quaternion value
  49872. */
  49873. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49874. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49875. };
  49876. /**
  49877. * Interpolates a quaternion cubically
  49878. * @param startValue Start value of the animation curve
  49879. * @param outTangent End tangent of the animation curve
  49880. * @param endValue End value of the animation curve
  49881. * @param inTangent Start tangent of the animation curve
  49882. * @param gradient Scalar amount to interpolate
  49883. * @returns Interpolated quaternion value
  49884. */
  49885. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49886. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49887. };
  49888. /**
  49889. * Interpolates a Vector3 linearl
  49890. * @param startValue Start value of the animation curve
  49891. * @param endValue End value of the animation curve
  49892. * @param gradient Scalar amount to interpolate
  49893. * @returns Interpolated scalar value
  49894. */
  49895. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49896. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49897. };
  49898. /**
  49899. * Interpolates a Vector3 cubically
  49900. * @param startValue Start value of the animation curve
  49901. * @param outTangent End tangent of the animation
  49902. * @param endValue End value of the animation curve
  49903. * @param inTangent Start tangent of the animation curve
  49904. * @param gradient Scalar amount to interpolate
  49905. * @returns InterpolatedVector3 value
  49906. */
  49907. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49908. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49909. };
  49910. /**
  49911. * Interpolates a Vector2 linearly
  49912. * @param startValue Start value of the animation curve
  49913. * @param endValue End value of the animation curve
  49914. * @param gradient Scalar amount to interpolate
  49915. * @returns Interpolated Vector2 value
  49916. */
  49917. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49918. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49919. };
  49920. /**
  49921. * Interpolates a Vector2 cubically
  49922. * @param startValue Start value of the animation curve
  49923. * @param outTangent End tangent of the animation
  49924. * @param endValue End value of the animation curve
  49925. * @param inTangent Start tangent of the animation curve
  49926. * @param gradient Scalar amount to interpolate
  49927. * @returns Interpolated Vector2 value
  49928. */
  49929. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49930. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49931. };
  49932. /**
  49933. * Interpolates a size linearly
  49934. * @param startValue Start value of the animation curve
  49935. * @param endValue End value of the animation curve
  49936. * @param gradient Scalar amount to interpolate
  49937. * @returns Interpolated Size value
  49938. */
  49939. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49940. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49941. };
  49942. /**
  49943. * Interpolates a Color3 linearly
  49944. * @param startValue Start value of the animation curve
  49945. * @param endValue End value of the animation curve
  49946. * @param gradient Scalar amount to interpolate
  49947. * @returns Interpolated Color3 value
  49948. */
  49949. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49950. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49951. };
  49952. /**
  49953. * @hidden Internal use only
  49954. */
  49955. Animation.prototype._getKeyValue = function (value) {
  49956. if (typeof value === "function") {
  49957. return value();
  49958. }
  49959. return value;
  49960. };
  49961. /**
  49962. * @hidden Internal use only
  49963. */
  49964. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49965. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49966. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49967. }
  49968. var keys = this.getKeys();
  49969. // Try to get a hash to find the right key
  49970. 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));
  49971. if (keys[startKeyIndex].frame >= currentFrame) {
  49972. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49973. startKeyIndex--;
  49974. }
  49975. }
  49976. for (var key = startKeyIndex; key < keys.length; key++) {
  49977. var endKey = keys[key + 1];
  49978. if (endKey.frame >= currentFrame) {
  49979. var startKey = keys[key];
  49980. var startValue = this._getKeyValue(startKey.value);
  49981. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49982. return startValue;
  49983. }
  49984. var endValue = this._getKeyValue(endKey.value);
  49985. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49986. var frameDelta = endKey.frame - startKey.frame;
  49987. // gradient : percent of currentFrame between the frame inf and the frame sup
  49988. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49989. // check for easingFunction and correction of gradient
  49990. var easingFunction = this.getEasingFunction();
  49991. if (easingFunction != null) {
  49992. gradient = easingFunction.ease(gradient);
  49993. }
  49994. switch (this.dataType) {
  49995. // Float
  49996. case Animation.ANIMATIONTYPE_FLOAT:
  49997. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49998. switch (loopMode) {
  49999. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50000. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50001. return floatValue;
  50002. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50003. return offsetValue * repeatCount + floatValue;
  50004. }
  50005. break;
  50006. // Quaternion
  50007. case Animation.ANIMATIONTYPE_QUATERNION:
  50008. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50009. switch (loopMode) {
  50010. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50011. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50012. return quatValue;
  50013. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50014. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50015. }
  50016. return quatValue;
  50017. // Vector3
  50018. case Animation.ANIMATIONTYPE_VECTOR3:
  50019. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50020. switch (loopMode) {
  50021. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50022. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50023. return vec3Value;
  50024. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50025. return vec3Value.add(offsetValue.scale(repeatCount));
  50026. }
  50027. // Vector2
  50028. case Animation.ANIMATIONTYPE_VECTOR2:
  50029. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50030. switch (loopMode) {
  50031. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50032. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50033. return vec2Value;
  50034. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50035. return vec2Value.add(offsetValue.scale(repeatCount));
  50036. }
  50037. // Size
  50038. case Animation.ANIMATIONTYPE_SIZE:
  50039. switch (loopMode) {
  50040. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50041. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50042. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50043. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50044. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50045. }
  50046. // Color3
  50047. case Animation.ANIMATIONTYPE_COLOR3:
  50048. switch (loopMode) {
  50049. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50050. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50051. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50052. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50053. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50054. }
  50055. // Matrix
  50056. case Animation.ANIMATIONTYPE_MATRIX:
  50057. switch (loopMode) {
  50058. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50059. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50060. if (Animation.AllowMatricesInterpolation) {
  50061. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50062. }
  50063. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50064. return startValue;
  50065. }
  50066. default:
  50067. break;
  50068. }
  50069. break;
  50070. }
  50071. }
  50072. return this._getKeyValue(keys[keys.length - 1].value);
  50073. };
  50074. /**
  50075. * Defines the function to use to interpolate matrices
  50076. * @param startValue defines the start matrix
  50077. * @param endValue defines the end matrix
  50078. * @param gradient defines the gradient between both matrices
  50079. * @param result defines an optional target matrix where to store the interpolation
  50080. * @returns the interpolated matrix
  50081. */
  50082. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50083. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50084. if (result) {
  50085. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50086. return result;
  50087. }
  50088. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50089. }
  50090. if (result) {
  50091. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50092. return result;
  50093. }
  50094. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50095. };
  50096. /**
  50097. * Makes a copy of the animation
  50098. * @returns Cloned animation
  50099. */
  50100. Animation.prototype.clone = function () {
  50101. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50102. clone.enableBlending = this.enableBlending;
  50103. clone.blendingSpeed = this.blendingSpeed;
  50104. if (this._keys) {
  50105. clone.setKeys(this._keys);
  50106. }
  50107. if (this._ranges) {
  50108. clone._ranges = {};
  50109. for (var name in this._ranges) {
  50110. var range = this._ranges[name];
  50111. if (!range) {
  50112. continue;
  50113. }
  50114. clone._ranges[name] = range.clone();
  50115. }
  50116. }
  50117. return clone;
  50118. };
  50119. /**
  50120. * Sets the key frames of the animation
  50121. * @param values The animation key frames to set
  50122. */
  50123. Animation.prototype.setKeys = function (values) {
  50124. this._keys = values.slice(0);
  50125. };
  50126. /**
  50127. * Serializes the animation to an object
  50128. * @returns Serialized object
  50129. */
  50130. Animation.prototype.serialize = function () {
  50131. var serializationObject = {};
  50132. serializationObject.name = this.name;
  50133. serializationObject.property = this.targetProperty;
  50134. serializationObject.framePerSecond = this.framePerSecond;
  50135. serializationObject.dataType = this.dataType;
  50136. serializationObject.loopBehavior = this.loopMode;
  50137. serializationObject.enableBlending = this.enableBlending;
  50138. serializationObject.blendingSpeed = this.blendingSpeed;
  50139. var dataType = this.dataType;
  50140. serializationObject.keys = [];
  50141. var keys = this.getKeys();
  50142. for (var index = 0; index < keys.length; index++) {
  50143. var animationKey = keys[index];
  50144. var key = {};
  50145. key.frame = animationKey.frame;
  50146. switch (dataType) {
  50147. case Animation.ANIMATIONTYPE_FLOAT:
  50148. key.values = [animationKey.value];
  50149. break;
  50150. case Animation.ANIMATIONTYPE_QUATERNION:
  50151. case Animation.ANIMATIONTYPE_MATRIX:
  50152. case Animation.ANIMATIONTYPE_VECTOR3:
  50153. case Animation.ANIMATIONTYPE_COLOR3:
  50154. key.values = animationKey.value.asArray();
  50155. break;
  50156. }
  50157. serializationObject.keys.push(key);
  50158. }
  50159. serializationObject.ranges = [];
  50160. for (var name in this._ranges) {
  50161. var source = this._ranges[name];
  50162. if (!source) {
  50163. continue;
  50164. }
  50165. var range = {};
  50166. range.name = name;
  50167. range.from = source.from;
  50168. range.to = source.to;
  50169. serializationObject.ranges.push(range);
  50170. }
  50171. return serializationObject;
  50172. };
  50173. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50174. /**
  50175. * Get the float animation type
  50176. */
  50177. get: function () {
  50178. return Animation._ANIMATIONTYPE_FLOAT;
  50179. },
  50180. enumerable: true,
  50181. configurable: true
  50182. });
  50183. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50184. /**
  50185. * Get the Vector3 animation type
  50186. */
  50187. get: function () {
  50188. return Animation._ANIMATIONTYPE_VECTOR3;
  50189. },
  50190. enumerable: true,
  50191. configurable: true
  50192. });
  50193. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50194. /**
  50195. * Get the Vectpr2 animation type
  50196. */
  50197. get: function () {
  50198. return Animation._ANIMATIONTYPE_VECTOR2;
  50199. },
  50200. enumerable: true,
  50201. configurable: true
  50202. });
  50203. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50204. /**
  50205. * Get the Size animation type
  50206. */
  50207. get: function () {
  50208. return Animation._ANIMATIONTYPE_SIZE;
  50209. },
  50210. enumerable: true,
  50211. configurable: true
  50212. });
  50213. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50214. /**
  50215. * Get the Quaternion animation type
  50216. */
  50217. get: function () {
  50218. return Animation._ANIMATIONTYPE_QUATERNION;
  50219. },
  50220. enumerable: true,
  50221. configurable: true
  50222. });
  50223. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50224. /**
  50225. * Get the Matrix animation type
  50226. */
  50227. get: function () {
  50228. return Animation._ANIMATIONTYPE_MATRIX;
  50229. },
  50230. enumerable: true,
  50231. configurable: true
  50232. });
  50233. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50234. /**
  50235. * Get the Color3 animation type
  50236. */
  50237. get: function () {
  50238. return Animation._ANIMATIONTYPE_COLOR3;
  50239. },
  50240. enumerable: true,
  50241. configurable: true
  50242. });
  50243. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50244. /**
  50245. * Get the Relative Loop Mode
  50246. */
  50247. get: function () {
  50248. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50249. },
  50250. enumerable: true,
  50251. configurable: true
  50252. });
  50253. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50254. /**
  50255. * Get the Cycle Loop Mode
  50256. */
  50257. get: function () {
  50258. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50259. },
  50260. enumerable: true,
  50261. configurable: true
  50262. });
  50263. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50264. /**
  50265. * Get the Constant Loop Mode
  50266. */
  50267. get: function () {
  50268. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50269. },
  50270. enumerable: true,
  50271. configurable: true
  50272. });
  50273. /** @hidden */
  50274. Animation._UniversalLerp = function (left, right, amount) {
  50275. var constructor = left.constructor;
  50276. if (constructor.Lerp) { // Lerp supported
  50277. return constructor.Lerp(left, right, amount);
  50278. }
  50279. else if (constructor.Slerp) { // Slerp supported
  50280. return constructor.Slerp(left, right, amount);
  50281. }
  50282. else if (left.toFixed) { // Number
  50283. return left * (1.0 - amount) + amount * right;
  50284. }
  50285. else { // Blending not supported
  50286. return right;
  50287. }
  50288. };
  50289. /**
  50290. * Parses an animation object and creates an animation
  50291. * @param parsedAnimation Parsed animation object
  50292. * @returns Animation object
  50293. */
  50294. Animation.Parse = function (parsedAnimation) {
  50295. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50296. var dataType = parsedAnimation.dataType;
  50297. var keys = [];
  50298. var data;
  50299. var index;
  50300. if (parsedAnimation.enableBlending) {
  50301. animation.enableBlending = parsedAnimation.enableBlending;
  50302. }
  50303. if (parsedAnimation.blendingSpeed) {
  50304. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50305. }
  50306. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50307. var key = parsedAnimation.keys[index];
  50308. var inTangent;
  50309. var outTangent;
  50310. switch (dataType) {
  50311. case Animation.ANIMATIONTYPE_FLOAT:
  50312. data = key.values[0];
  50313. if (key.values.length >= 1) {
  50314. inTangent = key.values[1];
  50315. }
  50316. if (key.values.length >= 2) {
  50317. outTangent = key.values[2];
  50318. }
  50319. break;
  50320. case Animation.ANIMATIONTYPE_QUATERNION:
  50321. data = BABYLON.Quaternion.FromArray(key.values);
  50322. if (key.values.length >= 8) {
  50323. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50324. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50325. inTangent = _inTangent;
  50326. }
  50327. }
  50328. if (key.values.length >= 12) {
  50329. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50330. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50331. outTangent = _outTangent;
  50332. }
  50333. }
  50334. break;
  50335. case Animation.ANIMATIONTYPE_MATRIX:
  50336. data = BABYLON.Matrix.FromArray(key.values);
  50337. break;
  50338. case Animation.ANIMATIONTYPE_COLOR3:
  50339. data = BABYLON.Color3.FromArray(key.values);
  50340. break;
  50341. case Animation.ANIMATIONTYPE_VECTOR3:
  50342. default:
  50343. data = BABYLON.Vector3.FromArray(key.values);
  50344. break;
  50345. }
  50346. var keyData = {};
  50347. keyData.frame = key.frame;
  50348. keyData.value = data;
  50349. if (inTangent != undefined) {
  50350. keyData.inTangent = inTangent;
  50351. }
  50352. if (outTangent != undefined) {
  50353. keyData.outTangent = outTangent;
  50354. }
  50355. keys.push(keyData);
  50356. }
  50357. animation.setKeys(keys);
  50358. if (parsedAnimation.ranges) {
  50359. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50360. data = parsedAnimation.ranges[index];
  50361. animation.createRange(data.name, data.from, data.to);
  50362. }
  50363. }
  50364. return animation;
  50365. };
  50366. /**
  50367. * Appends the serialized animations from the source animations
  50368. * @param source Source containing the animations
  50369. * @param destination Target to store the animations
  50370. */
  50371. Animation.AppendSerializedAnimations = function (source, destination) {
  50372. if (source.animations) {
  50373. destination.animations = [];
  50374. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50375. var animation = source.animations[animationIndex];
  50376. destination.animations.push(animation.serialize());
  50377. }
  50378. }
  50379. };
  50380. /**
  50381. * Use matrix interpolation instead of using direct key value when animating matrices
  50382. */
  50383. Animation.AllowMatricesInterpolation = false;
  50384. /**
  50385. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50386. */
  50387. Animation.AllowMatrixDecomposeForInterpolation = true;
  50388. // Statics
  50389. /**
  50390. * Float animation type
  50391. */
  50392. Animation._ANIMATIONTYPE_FLOAT = 0;
  50393. /**
  50394. * Vector3 animation type
  50395. */
  50396. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50397. /**
  50398. * Quaternion animation type
  50399. */
  50400. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50401. /**
  50402. * Matrix animation type
  50403. */
  50404. Animation._ANIMATIONTYPE_MATRIX = 3;
  50405. /**
  50406. * Color3 animation type
  50407. */
  50408. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50409. /**
  50410. * Vector2 animation type
  50411. */
  50412. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50413. /**
  50414. * Size animation type
  50415. */
  50416. Animation._ANIMATIONTYPE_SIZE = 6;
  50417. /**
  50418. * Relative Loop Mode
  50419. */
  50420. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50421. /**
  50422. * Cycle Loop Mode
  50423. */
  50424. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50425. /**
  50426. * Constant Loop Mode
  50427. */
  50428. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50429. return Animation;
  50430. }());
  50431. BABYLON.Animation = Animation;
  50432. })(BABYLON || (BABYLON = {}));
  50433. //# sourceMappingURL=babylon.animation.js.map
  50434. var BABYLON;
  50435. (function (BABYLON) {
  50436. /**
  50437. * This class defines the direct association between an animation and a target
  50438. */
  50439. var TargetedAnimation = /** @class */ (function () {
  50440. function TargetedAnimation() {
  50441. }
  50442. return TargetedAnimation;
  50443. }());
  50444. BABYLON.TargetedAnimation = TargetedAnimation;
  50445. /**
  50446. * Use this class to create coordinated animations on multiple targets
  50447. */
  50448. var AnimationGroup = /** @class */ (function () {
  50449. function AnimationGroup(name, scene) {
  50450. if (scene === void 0) { scene = null; }
  50451. this.name = name;
  50452. this._targetedAnimations = new Array();
  50453. this._animatables = new Array();
  50454. this._from = Number.MAX_VALUE;
  50455. this._to = -Number.MAX_VALUE;
  50456. this._speedRatio = 1;
  50457. this.onAnimationEndObservable = new BABYLON.Observable();
  50458. /**
  50459. * This observable will notify when all animations have ended.
  50460. */
  50461. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50462. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50463. this._scene.animationGroups.push(this);
  50464. }
  50465. Object.defineProperty(AnimationGroup.prototype, "from", {
  50466. /**
  50467. * Gets the first frame
  50468. */
  50469. get: function () {
  50470. return this._from;
  50471. },
  50472. enumerable: true,
  50473. configurable: true
  50474. });
  50475. Object.defineProperty(AnimationGroup.prototype, "to", {
  50476. /**
  50477. * Gets the last frame
  50478. */
  50479. get: function () {
  50480. return this._to;
  50481. },
  50482. enumerable: true,
  50483. configurable: true
  50484. });
  50485. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50486. /**
  50487. * Define if the animations are started
  50488. */
  50489. get: function () {
  50490. return this._isStarted;
  50491. },
  50492. enumerable: true,
  50493. configurable: true
  50494. });
  50495. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50496. /**
  50497. * Gets or sets the speed ratio to use for all animations
  50498. */
  50499. get: function () {
  50500. return this._speedRatio;
  50501. },
  50502. /**
  50503. * Gets or sets the speed ratio to use for all animations
  50504. */
  50505. set: function (value) {
  50506. if (this._speedRatio === value) {
  50507. return;
  50508. }
  50509. this._speedRatio = value;
  50510. for (var index = 0; index < this._animatables.length; index++) {
  50511. var animatable = this._animatables[index];
  50512. animatable.speedRatio = this._speedRatio;
  50513. }
  50514. },
  50515. enumerable: true,
  50516. configurable: true
  50517. });
  50518. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50519. /**
  50520. * Gets the targeted animations for this animation group
  50521. */
  50522. get: function () {
  50523. return this._targetedAnimations;
  50524. },
  50525. enumerable: true,
  50526. configurable: true
  50527. });
  50528. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50529. /**
  50530. * returning the list of animatables controlled by this animation group.
  50531. */
  50532. get: function () {
  50533. return this._animatables;
  50534. },
  50535. enumerable: true,
  50536. configurable: true
  50537. });
  50538. /**
  50539. * Add an animation (with its target) in the group
  50540. * @param animation defines the animation we want to add
  50541. * @param target defines the target of the animation
  50542. * @returns the {BABYLON.TargetedAnimation} object
  50543. */
  50544. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50545. var targetedAnimation = {
  50546. animation: animation,
  50547. target: target
  50548. };
  50549. var keys = animation.getKeys();
  50550. if (this._from > keys[0].frame) {
  50551. this._from = keys[0].frame;
  50552. }
  50553. if (this._to < keys[keys.length - 1].frame) {
  50554. this._to = keys[keys.length - 1].frame;
  50555. }
  50556. this._targetedAnimations.push(targetedAnimation);
  50557. return targetedAnimation;
  50558. };
  50559. /**
  50560. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50561. * It can add constant keys at begin or end
  50562. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50563. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50564. */
  50565. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50566. if (beginFrame === void 0) { beginFrame = null; }
  50567. if (endFrame === void 0) { endFrame = null; }
  50568. if (beginFrame == null)
  50569. beginFrame = this._from;
  50570. if (endFrame == null)
  50571. endFrame = this._to;
  50572. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50573. var targetedAnimation = this._targetedAnimations[index];
  50574. var keys = targetedAnimation.animation.getKeys();
  50575. var startKey = keys[0];
  50576. var endKey = keys[keys.length - 1];
  50577. if (startKey.frame > beginFrame) {
  50578. var newKey = {
  50579. frame: beginFrame,
  50580. value: startKey.value,
  50581. inTangent: startKey.inTangent,
  50582. outTangent: startKey.outTangent,
  50583. interpolation: startKey.interpolation
  50584. };
  50585. keys.splice(0, 0, newKey);
  50586. }
  50587. if (endKey.frame < endFrame) {
  50588. var newKey = {
  50589. frame: endFrame,
  50590. value: endKey.value,
  50591. inTangent: endKey.outTangent,
  50592. outTangent: endKey.outTangent,
  50593. interpolation: endKey.interpolation
  50594. };
  50595. keys.push(newKey);
  50596. }
  50597. }
  50598. this._from = beginFrame;
  50599. this._to = endFrame;
  50600. return this;
  50601. };
  50602. /**
  50603. * Start all animations on given targets
  50604. * @param loop defines if animations must loop
  50605. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50606. * @param from defines the from key (optional)
  50607. * @param to defines the to key (optional)
  50608. * @returns the current animation group
  50609. */
  50610. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50611. var _this = this;
  50612. if (loop === void 0) { loop = false; }
  50613. if (speedRatio === void 0) { speedRatio = 1; }
  50614. if (this._isStarted || this._targetedAnimations.length === 0) {
  50615. return this;
  50616. }
  50617. var _loop_1 = function (targetedAnimation) {
  50618. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50619. animatable.onAnimationEnd = function () {
  50620. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50621. _this._checkAnimationGroupEnded(animatable);
  50622. };
  50623. this_1._animatables.push(animatable);
  50624. };
  50625. var this_1 = this;
  50626. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50627. var targetedAnimation = _a[_i];
  50628. _loop_1(targetedAnimation);
  50629. }
  50630. this._speedRatio = speedRatio;
  50631. this._isStarted = true;
  50632. return this;
  50633. };
  50634. /**
  50635. * Pause all animations
  50636. */
  50637. AnimationGroup.prototype.pause = function () {
  50638. if (!this._isStarted) {
  50639. return this;
  50640. }
  50641. for (var index = 0; index < this._animatables.length; index++) {
  50642. var animatable = this._animatables[index];
  50643. animatable.pause();
  50644. }
  50645. return this;
  50646. };
  50647. /**
  50648. * Play all animations to initial state
  50649. * This function will start() the animations if they were not started or will restart() them if they were paused
  50650. * @param loop defines if animations must loop
  50651. */
  50652. AnimationGroup.prototype.play = function (loop) {
  50653. // only if all animatables are ready and exist
  50654. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50655. if (loop !== undefined) {
  50656. for (var index = 0; index < this._animatables.length; index++) {
  50657. var animatable = this._animatables[index];
  50658. animatable.loopAnimation = loop;
  50659. }
  50660. }
  50661. this.restart();
  50662. }
  50663. else {
  50664. this.stop();
  50665. this.start(loop, this._speedRatio);
  50666. }
  50667. return this;
  50668. };
  50669. /**
  50670. * Reset all animations to initial state
  50671. */
  50672. AnimationGroup.prototype.reset = function () {
  50673. if (!this._isStarted) {
  50674. return this;
  50675. }
  50676. for (var index = 0; index < this._animatables.length; index++) {
  50677. var animatable = this._animatables[index];
  50678. animatable.reset();
  50679. }
  50680. return this;
  50681. };
  50682. /**
  50683. * Restart animations from key 0
  50684. */
  50685. AnimationGroup.prototype.restart = function () {
  50686. if (!this._isStarted) {
  50687. return this;
  50688. }
  50689. for (var index = 0; index < this._animatables.length; index++) {
  50690. var animatable = this._animatables[index];
  50691. animatable.restart();
  50692. }
  50693. return this;
  50694. };
  50695. /**
  50696. * Stop all animations
  50697. */
  50698. AnimationGroup.prototype.stop = function () {
  50699. if (!this._isStarted) {
  50700. return this;
  50701. }
  50702. var list = this._animatables.slice();
  50703. for (var index = 0; index < list.length; index++) {
  50704. list[index].stop();
  50705. }
  50706. this._isStarted = false;
  50707. return this;
  50708. };
  50709. /**
  50710. * Set animation weight for all animatables
  50711. * @param weight defines the weight to use
  50712. * @return the animationGroup
  50713. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50714. */
  50715. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50716. for (var index = 0; index < this._animatables.length; index++) {
  50717. var animatable = this._animatables[index];
  50718. animatable.weight = weight;
  50719. }
  50720. return this;
  50721. };
  50722. /**
  50723. * Synchronize and normalize all animatables with a source animatable
  50724. * @param root defines the root animatable to synchronize with
  50725. * @return the animationGroup
  50726. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50727. */
  50728. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50729. for (var index = 0; index < this._animatables.length; index++) {
  50730. var animatable = this._animatables[index];
  50731. animatable.syncWith(root);
  50732. }
  50733. return this;
  50734. };
  50735. /**
  50736. * Goes to a specific frame in this animation group
  50737. * @param frame the frame number to go to
  50738. * @return the animationGroup
  50739. */
  50740. AnimationGroup.prototype.goToFrame = function (frame) {
  50741. if (!this._isStarted) {
  50742. return this;
  50743. }
  50744. for (var index = 0; index < this._animatables.length; index++) {
  50745. var animatable = this._animatables[index];
  50746. animatable.goToFrame(frame);
  50747. }
  50748. return this;
  50749. };
  50750. /**
  50751. * Dispose all associated resources
  50752. */
  50753. AnimationGroup.prototype.dispose = function () {
  50754. this._targetedAnimations = [];
  50755. this._animatables = [];
  50756. var index = this._scene.animationGroups.indexOf(this);
  50757. if (index > -1) {
  50758. this._scene.animationGroups.splice(index, 1);
  50759. }
  50760. };
  50761. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50762. // animatable should be taken out of the array
  50763. var idx = this._animatables.indexOf(animatable);
  50764. if (idx > -1) {
  50765. this._animatables.splice(idx, 1);
  50766. }
  50767. // all animatables were removed? animation group ended!
  50768. if (this._animatables.length === 0) {
  50769. this._isStarted = false;
  50770. this.onAnimationGroupEndObservable.notifyObservers(this);
  50771. }
  50772. };
  50773. return AnimationGroup;
  50774. }());
  50775. BABYLON.AnimationGroup = AnimationGroup;
  50776. })(BABYLON || (BABYLON = {}));
  50777. //# sourceMappingURL=babylon.animationGroup.js.map
  50778. var BABYLON;
  50779. (function (BABYLON) {
  50780. /**
  50781. * Defines a runtime animation
  50782. */
  50783. var RuntimeAnimation = /** @class */ (function () {
  50784. /**
  50785. * Create a new RuntimeAnimation object
  50786. * @param target defines the target of the animation
  50787. * @param animation defines the source animation object
  50788. * @param scene defines the hosting scene
  50789. * @param host defines the initiating Animatable
  50790. */
  50791. function RuntimeAnimation(target, animation, scene, host) {
  50792. var _this = this;
  50793. this._events = new Array();
  50794. /**
  50795. * The current frame of the runtime animation
  50796. */
  50797. this._currentFrame = 0;
  50798. /**
  50799. * The original value of the runtime animation
  50800. */
  50801. this._originalValue = new Array();
  50802. /**
  50803. * The offsets cache of the runtime animation
  50804. */
  50805. this._offsetsCache = {};
  50806. /**
  50807. * The high limits cache of the runtime animation
  50808. */
  50809. this._highLimitsCache = {};
  50810. /**
  50811. * Specifies if the runtime animation has been stopped
  50812. */
  50813. this._stopped = false;
  50814. /**
  50815. * The blending factor of the runtime animation
  50816. */
  50817. this._blendingFactor = 0;
  50818. /**
  50819. * The target path of the runtime animation
  50820. */
  50821. this._targetPath = "";
  50822. /**
  50823. * The weight of the runtime animation
  50824. */
  50825. this._weight = 1.0;
  50826. /**
  50827. * The ratio offset of the runtime animation
  50828. */
  50829. this._ratioOffset = 0;
  50830. /**
  50831. * The previous delay of the runtime animation
  50832. */
  50833. this._previousDelay = 0;
  50834. /**
  50835. * The previous ratio of the runtime animation
  50836. */
  50837. this._previousRatio = 0;
  50838. this._animation = animation;
  50839. this._target = target;
  50840. this._scene = scene;
  50841. this._host = host;
  50842. animation._runtimeAnimations.push(this);
  50843. // Cloning events locally
  50844. var events = animation.getEvents();
  50845. if (events && events.length > 0) {
  50846. events.forEach(function (e) {
  50847. _this._events.push(e._clone());
  50848. });
  50849. }
  50850. }
  50851. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50852. /**
  50853. * Gets the current frame of the runtime animation
  50854. */
  50855. get: function () {
  50856. return this._currentFrame;
  50857. },
  50858. enumerable: true,
  50859. configurable: true
  50860. });
  50861. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50862. /**
  50863. * Gets the weight of the runtime animation
  50864. */
  50865. get: function () {
  50866. return this._weight;
  50867. },
  50868. enumerable: true,
  50869. configurable: true
  50870. });
  50871. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50872. /**
  50873. * Gets the current value of the runtime animation
  50874. */
  50875. get: function () {
  50876. return this._currentValue;
  50877. },
  50878. enumerable: true,
  50879. configurable: true
  50880. });
  50881. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50882. /**
  50883. * Gets the target path of the runtime animation
  50884. */
  50885. get: function () {
  50886. return this._targetPath;
  50887. },
  50888. enumerable: true,
  50889. configurable: true
  50890. });
  50891. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50892. /**
  50893. * Gets the actual target of the runtime animation
  50894. */
  50895. get: function () {
  50896. return this._activeTarget;
  50897. },
  50898. enumerable: true,
  50899. configurable: true
  50900. });
  50901. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50902. /**
  50903. * Gets the animation from the runtime animation
  50904. */
  50905. get: function () {
  50906. return this._animation;
  50907. },
  50908. enumerable: true,
  50909. configurable: true
  50910. });
  50911. /**
  50912. * Resets the runtime animation to the beginning
  50913. * @param restoreOriginal defines whether to restore the target property to the original value
  50914. */
  50915. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50916. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50917. if (restoreOriginal) {
  50918. if (this._target instanceof Array) {
  50919. var index = 0;
  50920. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50921. var target = _a[_i];
  50922. if (this._originalValue[index] !== undefined) {
  50923. this._setValue(target, this._originalValue[index], -1);
  50924. }
  50925. index++;
  50926. }
  50927. }
  50928. else {
  50929. if (this._originalValue[0] !== undefined) {
  50930. this._setValue(this._target, this._originalValue[0], -1);
  50931. }
  50932. }
  50933. }
  50934. this._offsetsCache = {};
  50935. this._highLimitsCache = {};
  50936. this._currentFrame = 0;
  50937. this._blendingFactor = 0;
  50938. this._originalValue = new Array();
  50939. // Events
  50940. for (var index = 0; index < this._events.length; index++) {
  50941. this._events[index].isDone = false;
  50942. }
  50943. };
  50944. /**
  50945. * Specifies if the runtime animation is stopped
  50946. * @returns Boolean specifying if the runtime animation is stopped
  50947. */
  50948. RuntimeAnimation.prototype.isStopped = function () {
  50949. return this._stopped;
  50950. };
  50951. /**
  50952. * Disposes of the runtime animation
  50953. */
  50954. RuntimeAnimation.prototype.dispose = function () {
  50955. var index = this._animation.runtimeAnimations.indexOf(this);
  50956. if (index > -1) {
  50957. this._animation.runtimeAnimations.splice(index, 1);
  50958. }
  50959. };
  50960. /**
  50961. * Interpolates the animation from the current frame
  50962. * @param currentFrame The frame to interpolate the animation to
  50963. * @param repeatCount The number of times that the animation should loop
  50964. * @param loopMode The type of looping mode to use
  50965. * @param offsetValue Animation offset value
  50966. * @param highLimitValue The high limit value
  50967. * @returns The interpolated value
  50968. */
  50969. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50970. this._currentFrame = currentFrame;
  50971. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50972. this._workValue = BABYLON.Matrix.Zero();
  50973. }
  50974. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50975. };
  50976. /**
  50977. * Apply the interpolated value to the target
  50978. * @param currentValue defines the value computed by the animation
  50979. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50980. */
  50981. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50982. if (weight === void 0) { weight = 1.0; }
  50983. if (this._target instanceof Array) {
  50984. var index = 0;
  50985. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50986. var target = _a[_i];
  50987. this._setValue(target, currentValue, weight, index);
  50988. index++;
  50989. }
  50990. }
  50991. else {
  50992. this._setValue(this._target, currentValue, weight);
  50993. }
  50994. };
  50995. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50996. if (targetIndex === void 0) { targetIndex = 0; }
  50997. // Set value
  50998. var path;
  50999. var destination;
  51000. var targetPropertyPath = this._animation.targetPropertyPath;
  51001. if (targetPropertyPath.length > 1) {
  51002. var property = target[targetPropertyPath[0]];
  51003. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51004. property = property[targetPropertyPath[index]];
  51005. }
  51006. path = targetPropertyPath[targetPropertyPath.length - 1];
  51007. destination = property;
  51008. }
  51009. else {
  51010. path = targetPropertyPath[0];
  51011. destination = target;
  51012. }
  51013. this._targetPath = path;
  51014. this._activeTarget = destination;
  51015. this._weight = weight;
  51016. if (this._originalValue[targetIndex] === undefined) {
  51017. var originalValue = void 0;
  51018. if (destination.getRestPose && path === "_matrix") { // For bones
  51019. originalValue = destination.getRestPose();
  51020. }
  51021. else {
  51022. originalValue = destination[path];
  51023. }
  51024. if (originalValue && originalValue.clone) {
  51025. this._originalValue[targetIndex] = originalValue.clone();
  51026. }
  51027. else {
  51028. this._originalValue[targetIndex] = originalValue;
  51029. }
  51030. }
  51031. // Blending
  51032. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51033. if (enableBlending && this._blendingFactor <= 1.0) {
  51034. if (!this._originalBlendValue) {
  51035. var originalValue = destination[path];
  51036. if (originalValue.clone) {
  51037. this._originalBlendValue = originalValue.clone();
  51038. }
  51039. else {
  51040. this._originalBlendValue = originalValue;
  51041. }
  51042. }
  51043. if (this._originalBlendValue.m) { // Matrix
  51044. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51045. if (this._currentValue) {
  51046. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51047. }
  51048. else {
  51049. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51050. }
  51051. }
  51052. else {
  51053. if (this._currentValue) {
  51054. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51055. }
  51056. else {
  51057. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51058. }
  51059. }
  51060. }
  51061. else {
  51062. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51063. }
  51064. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51065. this._blendingFactor += blendingSpeed;
  51066. }
  51067. else {
  51068. this._currentValue = currentValue;
  51069. }
  51070. if (weight !== -1.0) {
  51071. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51072. }
  51073. else {
  51074. destination[path] = this._currentValue;
  51075. }
  51076. if (target.markAsDirty) {
  51077. target.markAsDirty(this._animation.targetProperty);
  51078. }
  51079. };
  51080. /**
  51081. * Gets the loop pmode of the runtime animation
  51082. * @returns Loop Mode
  51083. */
  51084. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51085. if (this._target && this._target.animationPropertiesOverride) {
  51086. return this._target.animationPropertiesOverride.loopMode;
  51087. }
  51088. return this._animation.loopMode;
  51089. };
  51090. /**
  51091. * Move the current animation to a given frame
  51092. * @param frame defines the frame to move to
  51093. */
  51094. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51095. var keys = this._animation.getKeys();
  51096. if (frame < keys[0].frame) {
  51097. frame = keys[0].frame;
  51098. }
  51099. else if (frame > keys[keys.length - 1].frame) {
  51100. frame = keys[keys.length - 1].frame;
  51101. }
  51102. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51103. this.setValue(currentValue, -1);
  51104. };
  51105. /**
  51106. * @hidden Internal use only
  51107. */
  51108. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51109. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51110. this._ratioOffset = this._previousRatio - newRatio;
  51111. };
  51112. /**
  51113. * Execute the current animation
  51114. * @param delay defines the delay to add to the current frame
  51115. * @param from defines the lower bound of the animation range
  51116. * @param to defines the upper bound of the animation range
  51117. * @param loop defines if the current animation must loop
  51118. * @param speedRatio defines the current speed ratio
  51119. * @param weight defines the weight of the animation (default is -1 so no weight)
  51120. * @returns a boolean indicating if the animation has ended
  51121. */
  51122. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51123. if (weight === void 0) { weight = -1.0; }
  51124. var targetPropertyPath = this._animation.targetPropertyPath;
  51125. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51126. this._stopped = true;
  51127. return false;
  51128. }
  51129. var keys = this._animation.getKeys();
  51130. // Return immediately if there is only one key frame.
  51131. if (keys.length === 1) {
  51132. this.setValue(keys[0].value, weight);
  51133. return !loop;
  51134. }
  51135. var returnValue = true;
  51136. // Adding a start key at frame 0 if missing
  51137. if (keys[0].frame !== 0) {
  51138. var newKey = { frame: 0, value: keys[0].value };
  51139. keys.splice(0, 0, newKey);
  51140. }
  51141. // Check limits
  51142. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51143. from = keys[0].frame;
  51144. }
  51145. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51146. to = keys[keys.length - 1].frame;
  51147. }
  51148. //to and from cannot be the same key
  51149. if (from === to) {
  51150. if (from > keys[0].frame) {
  51151. from--;
  51152. }
  51153. else if (to < keys[keys.length - 1].frame) {
  51154. to++;
  51155. }
  51156. }
  51157. // Compute ratio
  51158. var range = to - from;
  51159. var offsetValue;
  51160. // ratio represents the frame delta between from and to
  51161. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51162. var highLimitValue = 0;
  51163. this._previousDelay = delay;
  51164. this._previousRatio = ratio;
  51165. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51166. returnValue = false;
  51167. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51168. }
  51169. else {
  51170. // Get max value if required
  51171. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51172. var keyOffset = to.toString() + from.toString();
  51173. if (!this._offsetsCache[keyOffset]) {
  51174. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51175. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51176. switch (this._animation.dataType) {
  51177. // Float
  51178. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51179. this._offsetsCache[keyOffset] = toValue - fromValue;
  51180. break;
  51181. // Quaternion
  51182. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51183. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51184. break;
  51185. // Vector3
  51186. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51187. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51188. // Vector2
  51189. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51190. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51191. // Size
  51192. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51193. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51194. // Color3
  51195. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51196. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51197. default:
  51198. break;
  51199. }
  51200. this._highLimitsCache[keyOffset] = toValue;
  51201. }
  51202. highLimitValue = this._highLimitsCache[keyOffset];
  51203. offsetValue = this._offsetsCache[keyOffset];
  51204. }
  51205. }
  51206. if (offsetValue === undefined) {
  51207. switch (this._animation.dataType) {
  51208. // Float
  51209. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51210. offsetValue = 0;
  51211. break;
  51212. // Quaternion
  51213. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51214. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51215. break;
  51216. // Vector3
  51217. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51218. offsetValue = BABYLON.Vector3.Zero();
  51219. break;
  51220. // Vector2
  51221. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51222. offsetValue = BABYLON.Vector2.Zero();
  51223. break;
  51224. // Size
  51225. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51226. offsetValue = BABYLON.Size.Zero();
  51227. break;
  51228. // Color3
  51229. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51230. offsetValue = BABYLON.Color3.Black();
  51231. }
  51232. }
  51233. // Compute value
  51234. var repeatCount = (ratio / range) >> 0;
  51235. var currentFrame = returnValue ? from + ratio % range : to;
  51236. // Need to normalize?
  51237. if (this._host && this._host.syncRoot) {
  51238. var syncRoot = this._host.syncRoot;
  51239. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51240. currentFrame = from + (to - from) * hostNormalizedFrame;
  51241. }
  51242. // Reset events if looping
  51243. var events = this._events;
  51244. if (range > 0 && this.currentFrame > currentFrame ||
  51245. range < 0 && this.currentFrame < currentFrame) {
  51246. // Need to reset animation events
  51247. for (var index = 0; index < events.length; index++) {
  51248. if (!events[index].onlyOnce) {
  51249. // reset event, the animation is looping
  51250. events[index].isDone = false;
  51251. }
  51252. }
  51253. }
  51254. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51255. // Set value
  51256. this.setValue(currentValue, weight);
  51257. // Check events
  51258. for (var index = 0; index < events.length; index++) {
  51259. // Make sure current frame has passed event frame and that event frame is within the current range
  51260. // Also, handle both forward and reverse animations
  51261. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51262. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51263. var event = events[index];
  51264. if (!event.isDone) {
  51265. // If event should be done only once, remove it.
  51266. if (event.onlyOnce) {
  51267. events.splice(index, 1);
  51268. index--;
  51269. }
  51270. event.isDone = true;
  51271. event.action();
  51272. } // Don't do anything if the event has already be done.
  51273. }
  51274. }
  51275. if (!returnValue) {
  51276. this._stopped = true;
  51277. }
  51278. return returnValue;
  51279. };
  51280. return RuntimeAnimation;
  51281. }());
  51282. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51283. })(BABYLON || (BABYLON = {}));
  51284. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51285. var BABYLON;
  51286. (function (BABYLON) {
  51287. /**
  51288. * Class used to store an actual running animation
  51289. */
  51290. var Animatable = /** @class */ (function () {
  51291. /**
  51292. * Creates a new Animatable
  51293. * @param scene defines the hosting scene
  51294. * @param target defines the target object
  51295. * @param fromFrame defines the starting frame number (default is 0)
  51296. * @param toFrame defines the ending frame number (default is 100)
  51297. * @param loopAnimation defines if the animation must loop (default is false)
  51298. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51299. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51300. * @param animations defines a group of animation to add to the new Animatable
  51301. */
  51302. function Animatable(scene,
  51303. /** defines the target object */
  51304. target,
  51305. /** defines the starting frame number (default is 0) */
  51306. fromFrame,
  51307. /** defines the ending frame number (default is 100) */
  51308. toFrame,
  51309. /** defines if the animation must loop (default is false) */
  51310. loopAnimation, speedRatio,
  51311. /** defines a callback to call when animation ends if it is not looping */
  51312. onAnimationEnd, animations) {
  51313. if (fromFrame === void 0) { fromFrame = 0; }
  51314. if (toFrame === void 0) { toFrame = 100; }
  51315. if (loopAnimation === void 0) { loopAnimation = false; }
  51316. if (speedRatio === void 0) { speedRatio = 1.0; }
  51317. this.target = target;
  51318. this.fromFrame = fromFrame;
  51319. this.toFrame = toFrame;
  51320. this.loopAnimation = loopAnimation;
  51321. this.onAnimationEnd = onAnimationEnd;
  51322. this._localDelayOffset = null;
  51323. this._pausedDelay = null;
  51324. this._runtimeAnimations = new Array();
  51325. this._paused = false;
  51326. this._speedRatio = 1;
  51327. this._weight = -1.0;
  51328. /**
  51329. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51330. * This will only apply for non looping animation (default is true)
  51331. */
  51332. this.disposeOnEnd = true;
  51333. /**
  51334. * Gets a boolean indicating if the animation has started
  51335. */
  51336. this.animationStarted = false;
  51337. /**
  51338. * Observer raised when the animation ends
  51339. */
  51340. this.onAnimationEndObservable = new BABYLON.Observable();
  51341. this._scene = scene;
  51342. if (animations) {
  51343. this.appendAnimations(target, animations);
  51344. }
  51345. this._speedRatio = speedRatio;
  51346. scene._activeAnimatables.push(this);
  51347. }
  51348. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51349. /**
  51350. * Gets the root Animatable used to synchronize and normalize animations
  51351. */
  51352. get: function () {
  51353. return this._syncRoot;
  51354. },
  51355. enumerable: true,
  51356. configurable: true
  51357. });
  51358. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51359. /**
  51360. * Gets the current frame of the first RuntimeAnimation
  51361. * Used to synchronize Animatables
  51362. */
  51363. get: function () {
  51364. if (this._runtimeAnimations.length === 0) {
  51365. return 0;
  51366. }
  51367. return this._runtimeAnimations[0].currentFrame;
  51368. },
  51369. enumerable: true,
  51370. configurable: true
  51371. });
  51372. Object.defineProperty(Animatable.prototype, "weight", {
  51373. /**
  51374. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51375. */
  51376. get: function () {
  51377. return this._weight;
  51378. },
  51379. set: function (value) {
  51380. if (value === -1) { // -1 is ok and means no weight
  51381. this._weight = -1;
  51382. return;
  51383. }
  51384. // Else weight must be in [0, 1] range
  51385. this._weight = Math.min(Math.max(value, 0), 1.0);
  51386. },
  51387. enumerable: true,
  51388. configurable: true
  51389. });
  51390. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51391. /**
  51392. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51393. */
  51394. get: function () {
  51395. return this._speedRatio;
  51396. },
  51397. set: function (value) {
  51398. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51399. var animation = this._runtimeAnimations[index];
  51400. animation._prepareForSpeedRatioChange(value);
  51401. }
  51402. this._speedRatio = value;
  51403. },
  51404. enumerable: true,
  51405. configurable: true
  51406. });
  51407. // Methods
  51408. /**
  51409. * Synchronize and normalize current Animatable with a source Animatable
  51410. * This is useful when using animation weights and when animations are not of the same length
  51411. * @param root defines the root Animatable to synchronize with
  51412. * @returns the current Animatable
  51413. */
  51414. Animatable.prototype.syncWith = function (root) {
  51415. this._syncRoot = root;
  51416. if (root) {
  51417. // Make sure this animatable will animate after the root
  51418. var index = this._scene._activeAnimatables.indexOf(this);
  51419. if (index > -1) {
  51420. this._scene._activeAnimatables.splice(index, 1);
  51421. this._scene._activeAnimatables.push(this);
  51422. }
  51423. }
  51424. return this;
  51425. };
  51426. /**
  51427. * Gets the list of runtime animations
  51428. * @returns an array of RuntimeAnimation
  51429. */
  51430. Animatable.prototype.getAnimations = function () {
  51431. return this._runtimeAnimations;
  51432. };
  51433. /**
  51434. * Adds more animations to the current animatable
  51435. * @param target defines the target of the animations
  51436. * @param animations defines the new animations to add
  51437. */
  51438. Animatable.prototype.appendAnimations = function (target, animations) {
  51439. for (var index = 0; index < animations.length; index++) {
  51440. var animation = animations[index];
  51441. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51442. }
  51443. };
  51444. /**
  51445. * Gets the source animation for a specific property
  51446. * @param property defines the propertyu to look for
  51447. * @returns null or the source animation for the given property
  51448. */
  51449. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51450. var runtimeAnimations = this._runtimeAnimations;
  51451. for (var index = 0; index < runtimeAnimations.length; index++) {
  51452. if (runtimeAnimations[index].animation.targetProperty === property) {
  51453. return runtimeAnimations[index].animation;
  51454. }
  51455. }
  51456. return null;
  51457. };
  51458. /**
  51459. * Gets the runtime animation for a specific property
  51460. * @param property defines the propertyu to look for
  51461. * @returns null or the runtime animation for the given property
  51462. */
  51463. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51464. var runtimeAnimations = this._runtimeAnimations;
  51465. for (var index = 0; index < runtimeAnimations.length; index++) {
  51466. if (runtimeAnimations[index].animation.targetProperty === property) {
  51467. return runtimeAnimations[index];
  51468. }
  51469. }
  51470. return null;
  51471. };
  51472. /**
  51473. * Resets the animatable to its original state
  51474. */
  51475. Animatable.prototype.reset = function () {
  51476. var runtimeAnimations = this._runtimeAnimations;
  51477. for (var index = 0; index < runtimeAnimations.length; index++) {
  51478. runtimeAnimations[index].reset(true);
  51479. }
  51480. this._localDelayOffset = null;
  51481. this._pausedDelay = null;
  51482. };
  51483. /**
  51484. * Allows the animatable to blend with current running animations
  51485. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51486. * @param blendingSpeed defines the blending speed to use
  51487. */
  51488. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51489. var runtimeAnimations = this._runtimeAnimations;
  51490. for (var index = 0; index < runtimeAnimations.length; index++) {
  51491. runtimeAnimations[index].animation.enableBlending = true;
  51492. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51493. }
  51494. };
  51495. /**
  51496. * Disable animation blending
  51497. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51498. */
  51499. Animatable.prototype.disableBlending = function () {
  51500. var runtimeAnimations = this._runtimeAnimations;
  51501. for (var index = 0; index < runtimeAnimations.length; index++) {
  51502. runtimeAnimations[index].animation.enableBlending = false;
  51503. }
  51504. };
  51505. /**
  51506. * Jump directly to a given frame
  51507. * @param frame defines the frame to jump to
  51508. */
  51509. Animatable.prototype.goToFrame = function (frame) {
  51510. var runtimeAnimations = this._runtimeAnimations;
  51511. if (runtimeAnimations[0]) {
  51512. var fps = runtimeAnimations[0].animation.framePerSecond;
  51513. var currentFrame = runtimeAnimations[0].currentFrame;
  51514. var adjustTime = frame - currentFrame;
  51515. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51516. if (this._localDelayOffset === null) {
  51517. this._localDelayOffset = 0;
  51518. }
  51519. this._localDelayOffset -= delay;
  51520. }
  51521. for (var index = 0; index < runtimeAnimations.length; index++) {
  51522. runtimeAnimations[index].goToFrame(frame);
  51523. }
  51524. };
  51525. /**
  51526. * Pause the animation
  51527. */
  51528. Animatable.prototype.pause = function () {
  51529. if (this._paused) {
  51530. return;
  51531. }
  51532. this._paused = true;
  51533. };
  51534. /**
  51535. * Restart the animation
  51536. */
  51537. Animatable.prototype.restart = function () {
  51538. this._paused = false;
  51539. };
  51540. Animatable.prototype._raiseOnAnimationEnd = function () {
  51541. if (this.onAnimationEnd) {
  51542. this.onAnimationEnd();
  51543. }
  51544. this.onAnimationEndObservable.notifyObservers(this);
  51545. };
  51546. /**
  51547. * Stop and delete the current animation
  51548. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51549. */
  51550. Animatable.prototype.stop = function (animationName) {
  51551. if (animationName) {
  51552. var idx = this._scene._activeAnimatables.indexOf(this);
  51553. if (idx > -1) {
  51554. var runtimeAnimations = this._runtimeAnimations;
  51555. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51556. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51557. continue;
  51558. }
  51559. runtimeAnimations[index].dispose();
  51560. runtimeAnimations.splice(index, 1);
  51561. }
  51562. if (runtimeAnimations.length == 0) {
  51563. this._scene._activeAnimatables.splice(idx, 1);
  51564. this._raiseOnAnimationEnd();
  51565. }
  51566. }
  51567. }
  51568. else {
  51569. var index = this._scene._activeAnimatables.indexOf(this);
  51570. if (index > -1) {
  51571. this._scene._activeAnimatables.splice(index, 1);
  51572. var runtimeAnimations = this._runtimeAnimations;
  51573. for (var index = 0; index < runtimeAnimations.length; index++) {
  51574. runtimeAnimations[index].dispose();
  51575. }
  51576. this._raiseOnAnimationEnd();
  51577. }
  51578. }
  51579. };
  51580. /**
  51581. * Wait asynchronously for the animation to end
  51582. * @returns a promise which will be fullfilled when the animation ends
  51583. */
  51584. Animatable.prototype.waitAsync = function () {
  51585. var _this = this;
  51586. return new Promise(function (resolve, reject) {
  51587. _this.onAnimationEndObservable.add(function () {
  51588. resolve(_this);
  51589. }, undefined, undefined, _this, true);
  51590. });
  51591. };
  51592. /** @hidden */
  51593. Animatable.prototype._animate = function (delay) {
  51594. if (this._paused) {
  51595. this.animationStarted = false;
  51596. if (this._pausedDelay === null) {
  51597. this._pausedDelay = delay;
  51598. }
  51599. return true;
  51600. }
  51601. if (this._localDelayOffset === null) {
  51602. this._localDelayOffset = delay;
  51603. this._pausedDelay = null;
  51604. }
  51605. else if (this._pausedDelay !== null) {
  51606. this._localDelayOffset += delay - this._pausedDelay;
  51607. this._pausedDelay = null;
  51608. }
  51609. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51610. return true;
  51611. }
  51612. // Animating
  51613. var running = false;
  51614. var runtimeAnimations = this._runtimeAnimations;
  51615. var index;
  51616. for (index = 0; index < runtimeAnimations.length; index++) {
  51617. var animation = runtimeAnimations[index];
  51618. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51619. running = running || isRunning;
  51620. }
  51621. this.animationStarted = running;
  51622. if (!running) {
  51623. if (this.disposeOnEnd) {
  51624. // Remove from active animatables
  51625. index = this._scene._activeAnimatables.indexOf(this);
  51626. this._scene._activeAnimatables.splice(index, 1);
  51627. // Dispose all runtime animations
  51628. for (index = 0; index < runtimeAnimations.length; index++) {
  51629. runtimeAnimations[index].dispose();
  51630. }
  51631. }
  51632. this._raiseOnAnimationEnd();
  51633. if (this.disposeOnEnd) {
  51634. this.onAnimationEnd = null;
  51635. this.onAnimationEndObservable.clear();
  51636. }
  51637. }
  51638. return running;
  51639. };
  51640. return Animatable;
  51641. }());
  51642. BABYLON.Animatable = Animatable;
  51643. })(BABYLON || (BABYLON = {}));
  51644. //# sourceMappingURL=babylon.animatable.js.map
  51645. var BABYLON;
  51646. (function (BABYLON) {
  51647. var EasingFunction = /** @class */ (function () {
  51648. function EasingFunction() {
  51649. // Properties
  51650. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51651. }
  51652. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51653. get: function () {
  51654. return EasingFunction._EASINGMODE_EASEIN;
  51655. },
  51656. enumerable: true,
  51657. configurable: true
  51658. });
  51659. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51660. get: function () {
  51661. return EasingFunction._EASINGMODE_EASEOUT;
  51662. },
  51663. enumerable: true,
  51664. configurable: true
  51665. });
  51666. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51667. get: function () {
  51668. return EasingFunction._EASINGMODE_EASEINOUT;
  51669. },
  51670. enumerable: true,
  51671. configurable: true
  51672. });
  51673. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51674. var n = Math.min(Math.max(easingMode, 0), 2);
  51675. this._easingMode = n;
  51676. };
  51677. EasingFunction.prototype.getEasingMode = function () {
  51678. return this._easingMode;
  51679. };
  51680. EasingFunction.prototype.easeInCore = function (gradient) {
  51681. throw new Error('You must implement this method');
  51682. };
  51683. EasingFunction.prototype.ease = function (gradient) {
  51684. switch (this._easingMode) {
  51685. case EasingFunction.EASINGMODE_EASEIN:
  51686. return this.easeInCore(gradient);
  51687. case EasingFunction.EASINGMODE_EASEOUT:
  51688. return (1 - this.easeInCore(1 - gradient));
  51689. }
  51690. if (gradient >= 0.5) {
  51691. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51692. }
  51693. return (this.easeInCore(gradient * 2) * 0.5);
  51694. };
  51695. //Statics
  51696. EasingFunction._EASINGMODE_EASEIN = 0;
  51697. EasingFunction._EASINGMODE_EASEOUT = 1;
  51698. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51699. return EasingFunction;
  51700. }());
  51701. BABYLON.EasingFunction = EasingFunction;
  51702. var CircleEase = /** @class */ (function (_super) {
  51703. __extends(CircleEase, _super);
  51704. function CircleEase() {
  51705. return _super !== null && _super.apply(this, arguments) || this;
  51706. }
  51707. CircleEase.prototype.easeInCore = function (gradient) {
  51708. gradient = Math.max(0, Math.min(1, gradient));
  51709. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51710. };
  51711. return CircleEase;
  51712. }(EasingFunction));
  51713. BABYLON.CircleEase = CircleEase;
  51714. var BackEase = /** @class */ (function (_super) {
  51715. __extends(BackEase, _super);
  51716. function BackEase(amplitude) {
  51717. if (amplitude === void 0) { amplitude = 1; }
  51718. var _this = _super.call(this) || this;
  51719. _this.amplitude = amplitude;
  51720. return _this;
  51721. }
  51722. BackEase.prototype.easeInCore = function (gradient) {
  51723. var num = Math.max(0, this.amplitude);
  51724. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51725. };
  51726. return BackEase;
  51727. }(EasingFunction));
  51728. BABYLON.BackEase = BackEase;
  51729. var BounceEase = /** @class */ (function (_super) {
  51730. __extends(BounceEase, _super);
  51731. function BounceEase(bounces, bounciness) {
  51732. if (bounces === void 0) { bounces = 3; }
  51733. if (bounciness === void 0) { bounciness = 2; }
  51734. var _this = _super.call(this) || this;
  51735. _this.bounces = bounces;
  51736. _this.bounciness = bounciness;
  51737. return _this;
  51738. }
  51739. BounceEase.prototype.easeInCore = function (gradient) {
  51740. var y = Math.max(0.0, this.bounces);
  51741. var bounciness = this.bounciness;
  51742. if (bounciness <= 1.0) {
  51743. bounciness = 1.001;
  51744. }
  51745. var num9 = Math.pow(bounciness, y);
  51746. var num5 = 1.0 - bounciness;
  51747. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51748. var num15 = gradient * num4;
  51749. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51750. var num3 = Math.floor(num65);
  51751. var num13 = num3 + 1.0;
  51752. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51753. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51754. var num7 = (num8 + num12) * 0.5;
  51755. var num6 = gradient - num7;
  51756. var num2 = num7 - num8;
  51757. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51758. };
  51759. return BounceEase;
  51760. }(EasingFunction));
  51761. BABYLON.BounceEase = BounceEase;
  51762. var CubicEase = /** @class */ (function (_super) {
  51763. __extends(CubicEase, _super);
  51764. function CubicEase() {
  51765. return _super !== null && _super.apply(this, arguments) || this;
  51766. }
  51767. CubicEase.prototype.easeInCore = function (gradient) {
  51768. return (gradient * gradient * gradient);
  51769. };
  51770. return CubicEase;
  51771. }(EasingFunction));
  51772. BABYLON.CubicEase = CubicEase;
  51773. var ElasticEase = /** @class */ (function (_super) {
  51774. __extends(ElasticEase, _super);
  51775. function ElasticEase(oscillations, springiness) {
  51776. if (oscillations === void 0) { oscillations = 3; }
  51777. if (springiness === void 0) { springiness = 3; }
  51778. var _this = _super.call(this) || this;
  51779. _this.oscillations = oscillations;
  51780. _this.springiness = springiness;
  51781. return _this;
  51782. }
  51783. ElasticEase.prototype.easeInCore = function (gradient) {
  51784. var num2;
  51785. var num3 = Math.max(0.0, this.oscillations);
  51786. var num = Math.max(0.0, this.springiness);
  51787. if (num == 0) {
  51788. num2 = gradient;
  51789. }
  51790. else {
  51791. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51792. }
  51793. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51794. };
  51795. return ElasticEase;
  51796. }(EasingFunction));
  51797. BABYLON.ElasticEase = ElasticEase;
  51798. var ExponentialEase = /** @class */ (function (_super) {
  51799. __extends(ExponentialEase, _super);
  51800. function ExponentialEase(exponent) {
  51801. if (exponent === void 0) { exponent = 2; }
  51802. var _this = _super.call(this) || this;
  51803. _this.exponent = exponent;
  51804. return _this;
  51805. }
  51806. ExponentialEase.prototype.easeInCore = function (gradient) {
  51807. if (this.exponent <= 0) {
  51808. return gradient;
  51809. }
  51810. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51811. };
  51812. return ExponentialEase;
  51813. }(EasingFunction));
  51814. BABYLON.ExponentialEase = ExponentialEase;
  51815. var PowerEase = /** @class */ (function (_super) {
  51816. __extends(PowerEase, _super);
  51817. function PowerEase(power) {
  51818. if (power === void 0) { power = 2; }
  51819. var _this = _super.call(this) || this;
  51820. _this.power = power;
  51821. return _this;
  51822. }
  51823. PowerEase.prototype.easeInCore = function (gradient) {
  51824. var y = Math.max(0.0, this.power);
  51825. return Math.pow(gradient, y);
  51826. };
  51827. return PowerEase;
  51828. }(EasingFunction));
  51829. BABYLON.PowerEase = PowerEase;
  51830. var QuadraticEase = /** @class */ (function (_super) {
  51831. __extends(QuadraticEase, _super);
  51832. function QuadraticEase() {
  51833. return _super !== null && _super.apply(this, arguments) || this;
  51834. }
  51835. QuadraticEase.prototype.easeInCore = function (gradient) {
  51836. return (gradient * gradient);
  51837. };
  51838. return QuadraticEase;
  51839. }(EasingFunction));
  51840. BABYLON.QuadraticEase = QuadraticEase;
  51841. var QuarticEase = /** @class */ (function (_super) {
  51842. __extends(QuarticEase, _super);
  51843. function QuarticEase() {
  51844. return _super !== null && _super.apply(this, arguments) || this;
  51845. }
  51846. QuarticEase.prototype.easeInCore = function (gradient) {
  51847. return (gradient * gradient * gradient * gradient);
  51848. };
  51849. return QuarticEase;
  51850. }(EasingFunction));
  51851. BABYLON.QuarticEase = QuarticEase;
  51852. var QuinticEase = /** @class */ (function (_super) {
  51853. __extends(QuinticEase, _super);
  51854. function QuinticEase() {
  51855. return _super !== null && _super.apply(this, arguments) || this;
  51856. }
  51857. QuinticEase.prototype.easeInCore = function (gradient) {
  51858. return (gradient * gradient * gradient * gradient * gradient);
  51859. };
  51860. return QuinticEase;
  51861. }(EasingFunction));
  51862. BABYLON.QuinticEase = QuinticEase;
  51863. var SineEase = /** @class */ (function (_super) {
  51864. __extends(SineEase, _super);
  51865. function SineEase() {
  51866. return _super !== null && _super.apply(this, arguments) || this;
  51867. }
  51868. SineEase.prototype.easeInCore = function (gradient) {
  51869. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51870. };
  51871. return SineEase;
  51872. }(EasingFunction));
  51873. BABYLON.SineEase = SineEase;
  51874. var BezierCurveEase = /** @class */ (function (_super) {
  51875. __extends(BezierCurveEase, _super);
  51876. function BezierCurveEase(x1, y1, x2, y2) {
  51877. if (x1 === void 0) { x1 = 0; }
  51878. if (y1 === void 0) { y1 = 0; }
  51879. if (x2 === void 0) { x2 = 1; }
  51880. if (y2 === void 0) { y2 = 1; }
  51881. var _this = _super.call(this) || this;
  51882. _this.x1 = x1;
  51883. _this.y1 = y1;
  51884. _this.x2 = x2;
  51885. _this.y2 = y2;
  51886. return _this;
  51887. }
  51888. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51889. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51890. };
  51891. return BezierCurveEase;
  51892. }(EasingFunction));
  51893. BABYLON.BezierCurveEase = BezierCurveEase;
  51894. })(BABYLON || (BABYLON = {}));
  51895. //# sourceMappingURL=babylon.easing.js.map
  51896. var BABYLON;
  51897. (function (BABYLON) {
  51898. /**
  51899. * A Condition applied to an Action
  51900. */
  51901. var Condition = /** @class */ (function () {
  51902. /**
  51903. * Creates a new Condition
  51904. * @param actionManager the manager of the action the condition is applied to
  51905. */
  51906. function Condition(actionManager) {
  51907. this._actionManager = actionManager;
  51908. }
  51909. /**
  51910. * Check if the current condition is valid
  51911. * @returns a boolean
  51912. */
  51913. Condition.prototype.isValid = function () {
  51914. return true;
  51915. };
  51916. /**
  51917. * Internal only
  51918. * @hidden
  51919. */
  51920. Condition.prototype._getProperty = function (propertyPath) {
  51921. return this._actionManager._getProperty(propertyPath);
  51922. };
  51923. /**
  51924. * Internal only
  51925. * @hidden
  51926. */
  51927. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51928. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51929. };
  51930. /**
  51931. * Serialize placeholder for child classes
  51932. * @returns the serialized object
  51933. */
  51934. Condition.prototype.serialize = function () {
  51935. };
  51936. /**
  51937. * Internal only
  51938. * @hidden
  51939. */
  51940. Condition.prototype._serialize = function (serializedCondition) {
  51941. return {
  51942. type: 2,
  51943. children: [],
  51944. name: serializedCondition.name,
  51945. properties: serializedCondition.properties
  51946. };
  51947. };
  51948. return Condition;
  51949. }());
  51950. BABYLON.Condition = Condition;
  51951. /**
  51952. * Defines specific conditional operators as extensions of Condition
  51953. */
  51954. var ValueCondition = /** @class */ (function (_super) {
  51955. __extends(ValueCondition, _super);
  51956. /**
  51957. * Creates a new ValueCondition
  51958. * @param actionManager manager for the action the condition applies to
  51959. * @param target for the action
  51960. * @param propertyPath path to specify the property of the target the conditional operator uses
  51961. * @param value the value compared by the conditional operator against the current value of the property
  51962. * @param operator the conditional operator, default ValueCondition.IsEqual
  51963. */
  51964. function ValueCondition(actionManager, target,
  51965. /** path to specify the property of the target the conditional operator uses */
  51966. propertyPath,
  51967. /** the value compared by the conditional operator against the current value of the property */
  51968. value,
  51969. /** the conditional operator, default ValueCondition.IsEqual */
  51970. operator) {
  51971. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51972. var _this = _super.call(this, actionManager) || this;
  51973. _this.propertyPath = propertyPath;
  51974. _this.value = value;
  51975. _this.operator = operator;
  51976. _this._target = target;
  51977. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51978. _this._property = _this._getProperty(_this.propertyPath);
  51979. return _this;
  51980. }
  51981. Object.defineProperty(ValueCondition, "IsEqual", {
  51982. /**
  51983. * returns the number for IsEqual
  51984. */
  51985. get: function () {
  51986. return ValueCondition._IsEqual;
  51987. },
  51988. enumerable: true,
  51989. configurable: true
  51990. });
  51991. Object.defineProperty(ValueCondition, "IsDifferent", {
  51992. /**
  51993. * Returns the number for IsDifferent
  51994. */
  51995. get: function () {
  51996. return ValueCondition._IsDifferent;
  51997. },
  51998. enumerable: true,
  51999. configurable: true
  52000. });
  52001. Object.defineProperty(ValueCondition, "IsGreater", {
  52002. /**
  52003. * Returns the number for IsGreater
  52004. */
  52005. get: function () {
  52006. return ValueCondition._IsGreater;
  52007. },
  52008. enumerable: true,
  52009. configurable: true
  52010. });
  52011. Object.defineProperty(ValueCondition, "IsLesser", {
  52012. /**
  52013. * Returns the number for IsLesser
  52014. */
  52015. get: function () {
  52016. return ValueCondition._IsLesser;
  52017. },
  52018. enumerable: true,
  52019. configurable: true
  52020. });
  52021. /**
  52022. * Compares the given value with the property value for the specified conditional operator
  52023. * @returns the result of the comparison
  52024. */
  52025. ValueCondition.prototype.isValid = function () {
  52026. switch (this.operator) {
  52027. case ValueCondition.IsGreater:
  52028. return this._effectiveTarget[this._property] > this.value;
  52029. case ValueCondition.IsLesser:
  52030. return this._effectiveTarget[this._property] < this.value;
  52031. case ValueCondition.IsEqual:
  52032. case ValueCondition.IsDifferent:
  52033. var check;
  52034. if (this.value.equals) {
  52035. check = this.value.equals(this._effectiveTarget[this._property]);
  52036. }
  52037. else {
  52038. check = this.value === this._effectiveTarget[this._property];
  52039. }
  52040. return this.operator === ValueCondition.IsEqual ? check : !check;
  52041. }
  52042. return false;
  52043. };
  52044. /**
  52045. * Serialize the ValueCondition into a JSON compatible object
  52046. * @returns serialization object
  52047. */
  52048. ValueCondition.prototype.serialize = function () {
  52049. return this._serialize({
  52050. name: "ValueCondition",
  52051. properties: [
  52052. BABYLON.Action._GetTargetProperty(this._target),
  52053. { name: "propertyPath", value: this.propertyPath },
  52054. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52055. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52056. ]
  52057. });
  52058. };
  52059. /**
  52060. * Gets the name of the conditional operator for the ValueCondition
  52061. * @param operator the conditional operator
  52062. * @returns the name
  52063. */
  52064. ValueCondition.GetOperatorName = function (operator) {
  52065. switch (operator) {
  52066. case ValueCondition._IsEqual: return "IsEqual";
  52067. case ValueCondition._IsDifferent: return "IsDifferent";
  52068. case ValueCondition._IsGreater: return "IsGreater";
  52069. case ValueCondition._IsLesser: return "IsLesser";
  52070. default: return "";
  52071. }
  52072. };
  52073. /**
  52074. * Internal only
  52075. * @hidden
  52076. */
  52077. ValueCondition._IsEqual = 0;
  52078. /**
  52079. * Internal only
  52080. * @hidden
  52081. */
  52082. ValueCondition._IsDifferent = 1;
  52083. /**
  52084. * Internal only
  52085. * @hidden
  52086. */
  52087. ValueCondition._IsGreater = 2;
  52088. /**
  52089. * Internal only
  52090. * @hidden
  52091. */
  52092. ValueCondition._IsLesser = 3;
  52093. return ValueCondition;
  52094. }(Condition));
  52095. BABYLON.ValueCondition = ValueCondition;
  52096. /**
  52097. * Defines a predicate condition as an extension of Condition
  52098. */
  52099. var PredicateCondition = /** @class */ (function (_super) {
  52100. __extends(PredicateCondition, _super);
  52101. /**
  52102. * Creates a new PredicateCondition
  52103. * @param actionManager manager for the action the condition applies to
  52104. * @param predicate defines the predicate function used to validate the condition
  52105. */
  52106. function PredicateCondition(actionManager,
  52107. /** defines the predicate function used to validate the condition */
  52108. predicate) {
  52109. var _this = _super.call(this, actionManager) || this;
  52110. _this.predicate = predicate;
  52111. return _this;
  52112. }
  52113. /**
  52114. * @returns the validity of the predicate condition
  52115. */
  52116. PredicateCondition.prototype.isValid = function () {
  52117. return this.predicate();
  52118. };
  52119. return PredicateCondition;
  52120. }(Condition));
  52121. BABYLON.PredicateCondition = PredicateCondition;
  52122. /**
  52123. * Defines a state condition as an extension of Condition
  52124. */
  52125. var StateCondition = /** @class */ (function (_super) {
  52126. __extends(StateCondition, _super);
  52127. /**
  52128. * Creates a new StateCondition
  52129. * @param actionManager manager for the action the condition applies to
  52130. * @param target of the condition
  52131. * @param value to compare with target state
  52132. */
  52133. function StateCondition(actionManager, target, value) {
  52134. var _this = _super.call(this, actionManager) || this;
  52135. _this.value = value;
  52136. _this._target = target;
  52137. return _this;
  52138. }
  52139. /**
  52140. * @returns the validity of the state
  52141. */
  52142. StateCondition.prototype.isValid = function () {
  52143. return this._target.state === this.value;
  52144. };
  52145. /**
  52146. * Serialize the StateCondition into a JSON compatible object
  52147. * @returns serialization object
  52148. */
  52149. StateCondition.prototype.serialize = function () {
  52150. return this._serialize({
  52151. name: "StateCondition",
  52152. properties: [
  52153. BABYLON.Action._GetTargetProperty(this._target),
  52154. { name: "value", value: this.value }
  52155. ]
  52156. });
  52157. };
  52158. return StateCondition;
  52159. }(Condition));
  52160. BABYLON.StateCondition = StateCondition;
  52161. })(BABYLON || (BABYLON = {}));
  52162. //# sourceMappingURL=babylon.condition.js.map
  52163. var BABYLON;
  52164. (function (BABYLON) {
  52165. /**
  52166. * The action to be carried out following a trigger
  52167. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52168. */
  52169. var Action = /** @class */ (function () {
  52170. /**
  52171. * Creates a new Action
  52172. * @param triggerOptions the trigger, with or without parameters, for the action
  52173. * @param condition an optional determinant of action
  52174. */
  52175. function Action(
  52176. /** the trigger, with or without parameters, for the action */
  52177. triggerOptions, condition) {
  52178. this.triggerOptions = triggerOptions;
  52179. /**
  52180. * An event triggered prior to action being executed.
  52181. */
  52182. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52183. if (triggerOptions.parameter) {
  52184. this.trigger = triggerOptions.trigger;
  52185. this._triggerParameter = triggerOptions.parameter;
  52186. }
  52187. else {
  52188. this.trigger = triggerOptions;
  52189. }
  52190. this._nextActiveAction = this;
  52191. this._condition = condition;
  52192. }
  52193. /**
  52194. * Internal only
  52195. * @hidden
  52196. */
  52197. Action.prototype._prepare = function () {
  52198. };
  52199. /**
  52200. * Gets the trigger parameters
  52201. * @returns the trigger parameters
  52202. */
  52203. Action.prototype.getTriggerParameter = function () {
  52204. return this._triggerParameter;
  52205. };
  52206. /**
  52207. * Internal only - executes current action event
  52208. * @hidden
  52209. */
  52210. Action.prototype._executeCurrent = function (evt) {
  52211. if (this._nextActiveAction._condition) {
  52212. var condition = this._nextActiveAction._condition;
  52213. var currentRenderId = this._actionManager.getScene().getRenderId();
  52214. // We cache the current evaluation for the current frame
  52215. if (condition._evaluationId === currentRenderId) {
  52216. if (!condition._currentResult) {
  52217. return;
  52218. }
  52219. }
  52220. else {
  52221. condition._evaluationId = currentRenderId;
  52222. if (!condition.isValid()) {
  52223. condition._currentResult = false;
  52224. return;
  52225. }
  52226. condition._currentResult = true;
  52227. }
  52228. }
  52229. this.onBeforeExecuteObservable.notifyObservers(this);
  52230. this._nextActiveAction.execute(evt);
  52231. this.skipToNextActiveAction();
  52232. };
  52233. /**
  52234. * Execute placeholder for child classes
  52235. * @param evt optional action event
  52236. */
  52237. Action.prototype.execute = function (evt) {
  52238. };
  52239. /**
  52240. * Skips to next active action
  52241. */
  52242. Action.prototype.skipToNextActiveAction = function () {
  52243. if (this._nextActiveAction._child) {
  52244. if (!this._nextActiveAction._child._actionManager) {
  52245. this._nextActiveAction._child._actionManager = this._actionManager;
  52246. }
  52247. this._nextActiveAction = this._nextActiveAction._child;
  52248. }
  52249. else {
  52250. this._nextActiveAction = this;
  52251. }
  52252. };
  52253. /**
  52254. * Adds action to chain of actions, may be a DoNothingAction
  52255. * @param action defines the next action to execute
  52256. * @returns The action passed in
  52257. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52258. */
  52259. Action.prototype.then = function (action) {
  52260. this._child = action;
  52261. action._actionManager = this._actionManager;
  52262. action._prepare();
  52263. return action;
  52264. };
  52265. /**
  52266. * Internal only
  52267. * @hidden
  52268. */
  52269. Action.prototype._getProperty = function (propertyPath) {
  52270. return this._actionManager._getProperty(propertyPath);
  52271. };
  52272. /**
  52273. * Internal only
  52274. * @hidden
  52275. */
  52276. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52277. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52278. };
  52279. /**
  52280. * Serialize placeholder for child classes
  52281. * @param parent of child
  52282. * @returns the serialized object
  52283. */
  52284. Action.prototype.serialize = function (parent) {
  52285. };
  52286. /**
  52287. * Internal only called by serialize
  52288. * @hidden
  52289. */
  52290. Action.prototype._serialize = function (serializedAction, parent) {
  52291. var serializationObject = {
  52292. type: 1,
  52293. children: [],
  52294. name: serializedAction.name,
  52295. properties: serializedAction.properties || []
  52296. };
  52297. // Serialize child
  52298. if (this._child) {
  52299. this._child.serialize(serializationObject);
  52300. }
  52301. // Check if "this" has a condition
  52302. if (this._condition) {
  52303. var serializedCondition = this._condition.serialize();
  52304. serializedCondition.children.push(serializationObject);
  52305. if (parent) {
  52306. parent.children.push(serializedCondition);
  52307. }
  52308. return serializedCondition;
  52309. }
  52310. if (parent) {
  52311. parent.children.push(serializationObject);
  52312. }
  52313. return serializationObject;
  52314. };
  52315. /**
  52316. * Internal only
  52317. * @hidden
  52318. */
  52319. Action._SerializeValueAsString = function (value) {
  52320. if (typeof value === "number") {
  52321. return value.toString();
  52322. }
  52323. if (typeof value === "boolean") {
  52324. return value ? "true" : "false";
  52325. }
  52326. if (value instanceof BABYLON.Vector2) {
  52327. return value.x + ", " + value.y;
  52328. }
  52329. if (value instanceof BABYLON.Vector3) {
  52330. return value.x + ", " + value.y + ", " + value.z;
  52331. }
  52332. if (value instanceof BABYLON.Color3) {
  52333. return value.r + ", " + value.g + ", " + value.b;
  52334. }
  52335. if (value instanceof BABYLON.Color4) {
  52336. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52337. }
  52338. return value; // string
  52339. };
  52340. /**
  52341. * Internal only
  52342. * @hidden
  52343. */
  52344. Action._GetTargetProperty = function (target) {
  52345. return {
  52346. name: "target",
  52347. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52348. : target instanceof BABYLON.Light ? "LightProperties"
  52349. : target instanceof BABYLON.Camera ? "CameraProperties"
  52350. : "SceneProperties",
  52351. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52352. };
  52353. };
  52354. return Action;
  52355. }());
  52356. BABYLON.Action = Action;
  52357. })(BABYLON || (BABYLON = {}));
  52358. //# sourceMappingURL=babylon.action.js.map
  52359. var BABYLON;
  52360. (function (BABYLON) {
  52361. /**
  52362. * ActionEvent is the event being sent when an action is triggered.
  52363. */
  52364. var ActionEvent = /** @class */ (function () {
  52365. /**
  52366. * Creates a new ActionEvent
  52367. * @param source The mesh or sprite that triggered the action
  52368. * @param pointerX The X mouse cursor position at the time of the event
  52369. * @param pointerY The Y mouse cursor position at the time of the event
  52370. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52371. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52372. * @param additionalData additional data for the event
  52373. */
  52374. function ActionEvent(
  52375. /** The mesh or sprite that triggered the action */
  52376. source,
  52377. /** The X mouse cursor position at the time of the event */
  52378. pointerX,
  52379. /** The Y mouse cursor position at the time of the event */
  52380. pointerY,
  52381. /** The mesh that is currently pointed at (can be null) */
  52382. meshUnderPointer,
  52383. /** the original (browser) event that triggered the ActionEvent */
  52384. sourceEvent,
  52385. /** additional data for the event */
  52386. additionalData) {
  52387. this.source = source;
  52388. this.pointerX = pointerX;
  52389. this.pointerY = pointerY;
  52390. this.meshUnderPointer = meshUnderPointer;
  52391. this.sourceEvent = sourceEvent;
  52392. this.additionalData = additionalData;
  52393. }
  52394. /**
  52395. * Helper function to auto-create an ActionEvent from a source mesh.
  52396. * @param source The source mesh that triggered the event
  52397. * @param evt The original (browser) event
  52398. * @param additionalData additional data for the event
  52399. * @returns the new ActionEvent
  52400. */
  52401. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52402. var scene = source.getScene();
  52403. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52404. };
  52405. /**
  52406. * Helper function to auto-create an ActionEvent from a source sprite
  52407. * @param source The source sprite that triggered the event
  52408. * @param scene Scene associated with the sprite
  52409. * @param evt The original (browser) event
  52410. * @param additionalData additional data for the event
  52411. * @returns the new ActionEvent
  52412. */
  52413. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52414. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52415. };
  52416. /**
  52417. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52418. * @param scene the scene where the event occurred
  52419. * @param evt The original (browser) event
  52420. * @returns the new ActionEvent
  52421. */
  52422. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52423. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52424. };
  52425. /**
  52426. * Helper function to auto-create an ActionEvent from a primitive
  52427. * @param prim defines the target primitive
  52428. * @param pointerPos defines the pointer position
  52429. * @param evt The original (browser) event
  52430. * @param additionalData additional data for the event
  52431. * @returns the new ActionEvent
  52432. */
  52433. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52434. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52435. };
  52436. return ActionEvent;
  52437. }());
  52438. BABYLON.ActionEvent = ActionEvent;
  52439. /**
  52440. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52441. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52442. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52443. */
  52444. var ActionManager = /** @class */ (function () {
  52445. /**
  52446. * Creates a new action manager
  52447. * @param scene defines the hosting scene
  52448. */
  52449. function ActionManager(scene) {
  52450. // Members
  52451. /** Gets the list of actions */
  52452. this.actions = new Array();
  52453. /** Gets the cursor to use when hovering items */
  52454. this.hoverCursor = '';
  52455. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52456. scene.actionManagers.push(this);
  52457. }
  52458. Object.defineProperty(ActionManager, "NothingTrigger", {
  52459. /**
  52460. * Nothing
  52461. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52462. */
  52463. get: function () {
  52464. return ActionManager._NothingTrigger;
  52465. },
  52466. enumerable: true,
  52467. configurable: true
  52468. });
  52469. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52470. /**
  52471. * On pick
  52472. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52473. */
  52474. get: function () {
  52475. return ActionManager._OnPickTrigger;
  52476. },
  52477. enumerable: true,
  52478. configurable: true
  52479. });
  52480. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52481. /**
  52482. * On left pick
  52483. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52484. */
  52485. get: function () {
  52486. return ActionManager._OnLeftPickTrigger;
  52487. },
  52488. enumerable: true,
  52489. configurable: true
  52490. });
  52491. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52492. /**
  52493. * On right pick
  52494. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52495. */
  52496. get: function () {
  52497. return ActionManager._OnRightPickTrigger;
  52498. },
  52499. enumerable: true,
  52500. configurable: true
  52501. });
  52502. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52503. /**
  52504. * On center pick
  52505. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52506. */
  52507. get: function () {
  52508. return ActionManager._OnCenterPickTrigger;
  52509. },
  52510. enumerable: true,
  52511. configurable: true
  52512. });
  52513. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52514. /**
  52515. * On pick down
  52516. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52517. */
  52518. get: function () {
  52519. return ActionManager._OnPickDownTrigger;
  52520. },
  52521. enumerable: true,
  52522. configurable: true
  52523. });
  52524. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52525. /**
  52526. * On double pick
  52527. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52528. */
  52529. get: function () {
  52530. return ActionManager._OnDoublePickTrigger;
  52531. },
  52532. enumerable: true,
  52533. configurable: true
  52534. });
  52535. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52536. /**
  52537. * On pick up
  52538. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52539. */
  52540. get: function () {
  52541. return ActionManager._OnPickUpTrigger;
  52542. },
  52543. enumerable: true,
  52544. configurable: true
  52545. });
  52546. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52547. /**
  52548. * On pick out.
  52549. * This trigger will only be raised if you also declared a OnPickDown
  52550. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52551. */
  52552. get: function () {
  52553. return ActionManager._OnPickOutTrigger;
  52554. },
  52555. enumerable: true,
  52556. configurable: true
  52557. });
  52558. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52559. /**
  52560. * On long press
  52561. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52562. */
  52563. get: function () {
  52564. return ActionManager._OnLongPressTrigger;
  52565. },
  52566. enumerable: true,
  52567. configurable: true
  52568. });
  52569. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52570. /**
  52571. * On pointer over
  52572. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52573. */
  52574. get: function () {
  52575. return ActionManager._OnPointerOverTrigger;
  52576. },
  52577. enumerable: true,
  52578. configurable: true
  52579. });
  52580. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52581. /**
  52582. * On pointer out
  52583. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52584. */
  52585. get: function () {
  52586. return ActionManager._OnPointerOutTrigger;
  52587. },
  52588. enumerable: true,
  52589. configurable: true
  52590. });
  52591. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52592. /**
  52593. * On every frame
  52594. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52595. */
  52596. get: function () {
  52597. return ActionManager._OnEveryFrameTrigger;
  52598. },
  52599. enumerable: true,
  52600. configurable: true
  52601. });
  52602. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52603. /**
  52604. * On intersection enter
  52605. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52606. */
  52607. get: function () {
  52608. return ActionManager._OnIntersectionEnterTrigger;
  52609. },
  52610. enumerable: true,
  52611. configurable: true
  52612. });
  52613. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52614. /**
  52615. * On intersection exit
  52616. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52617. */
  52618. get: function () {
  52619. return ActionManager._OnIntersectionExitTrigger;
  52620. },
  52621. enumerable: true,
  52622. configurable: true
  52623. });
  52624. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52625. /**
  52626. * On key down
  52627. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52628. */
  52629. get: function () {
  52630. return ActionManager._OnKeyDownTrigger;
  52631. },
  52632. enumerable: true,
  52633. configurable: true
  52634. });
  52635. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52636. /**
  52637. * On key up
  52638. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52639. */
  52640. get: function () {
  52641. return ActionManager._OnKeyUpTrigger;
  52642. },
  52643. enumerable: true,
  52644. configurable: true
  52645. });
  52646. // Methods
  52647. /**
  52648. * Releases all associated resources
  52649. */
  52650. ActionManager.prototype.dispose = function () {
  52651. var index = this._scene.actionManagers.indexOf(this);
  52652. for (var i = 0; i < this.actions.length; i++) {
  52653. var action = this.actions[i];
  52654. ActionManager.Triggers[action.trigger]--;
  52655. if (ActionManager.Triggers[action.trigger] === 0) {
  52656. delete ActionManager.Triggers[action.trigger];
  52657. }
  52658. }
  52659. if (index > -1) {
  52660. this._scene.actionManagers.splice(index, 1);
  52661. }
  52662. };
  52663. /**
  52664. * Gets hosting scene
  52665. * @returns the hosting scene
  52666. */
  52667. ActionManager.prototype.getScene = function () {
  52668. return this._scene;
  52669. };
  52670. /**
  52671. * Does this action manager handles actions of any of the given triggers
  52672. * @param triggers defines the triggers to be tested
  52673. * @return a boolean indicating whether one (or more) of the triggers is handled
  52674. */
  52675. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52676. for (var index = 0; index < this.actions.length; index++) {
  52677. var action = this.actions[index];
  52678. if (triggers.indexOf(action.trigger) > -1) {
  52679. return true;
  52680. }
  52681. }
  52682. return false;
  52683. };
  52684. /**
  52685. * Does this action manager handles actions of a given trigger
  52686. * @param trigger defines the trigger to be tested
  52687. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52688. * @return whether the trigger is handled
  52689. */
  52690. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52691. for (var index = 0; index < this.actions.length; index++) {
  52692. var action = this.actions[index];
  52693. if (action.trigger === trigger) {
  52694. if (parameterPredicate) {
  52695. if (parameterPredicate(action.getTriggerParameter())) {
  52696. return true;
  52697. }
  52698. }
  52699. else {
  52700. return true;
  52701. }
  52702. }
  52703. }
  52704. return false;
  52705. };
  52706. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52707. /**
  52708. * Does this action manager has pointer triggers
  52709. */
  52710. get: function () {
  52711. for (var index = 0; index < this.actions.length; index++) {
  52712. var action = this.actions[index];
  52713. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52714. return true;
  52715. }
  52716. }
  52717. return false;
  52718. },
  52719. enumerable: true,
  52720. configurable: true
  52721. });
  52722. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52723. /**
  52724. * Does this action manager has pick triggers
  52725. */
  52726. get: function () {
  52727. for (var index = 0; index < this.actions.length; index++) {
  52728. var action = this.actions[index];
  52729. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52730. return true;
  52731. }
  52732. }
  52733. return false;
  52734. },
  52735. enumerable: true,
  52736. configurable: true
  52737. });
  52738. Object.defineProperty(ActionManager, "HasTriggers", {
  52739. /**
  52740. * Does exist one action manager with at least one trigger
  52741. **/
  52742. get: function () {
  52743. for (var t in ActionManager.Triggers) {
  52744. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52745. return true;
  52746. }
  52747. }
  52748. return false;
  52749. },
  52750. enumerable: true,
  52751. configurable: true
  52752. });
  52753. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52754. /**
  52755. * Does exist one action manager with at least one pick trigger
  52756. **/
  52757. get: function () {
  52758. for (var t in ActionManager.Triggers) {
  52759. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52760. var t_int = parseInt(t);
  52761. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52762. return true;
  52763. }
  52764. }
  52765. }
  52766. return false;
  52767. },
  52768. enumerable: true,
  52769. configurable: true
  52770. });
  52771. /**
  52772. * Does exist one action manager that handles actions of a given trigger
  52773. * @param trigger defines the trigger to be tested
  52774. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52775. **/
  52776. ActionManager.HasSpecificTrigger = function (trigger) {
  52777. for (var t in ActionManager.Triggers) {
  52778. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52779. var t_int = parseInt(t);
  52780. if (t_int === trigger) {
  52781. return true;
  52782. }
  52783. }
  52784. }
  52785. return false;
  52786. };
  52787. /**
  52788. * Registers an action to this action manager
  52789. * @param action defines the action to be registered
  52790. * @return the action amended (prepared) after registration
  52791. */
  52792. ActionManager.prototype.registerAction = function (action) {
  52793. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52794. if (this.getScene().actionManager !== this) {
  52795. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52796. return null;
  52797. }
  52798. }
  52799. this.actions.push(action);
  52800. if (ActionManager.Triggers[action.trigger]) {
  52801. ActionManager.Triggers[action.trigger]++;
  52802. }
  52803. else {
  52804. ActionManager.Triggers[action.trigger] = 1;
  52805. }
  52806. action._actionManager = this;
  52807. action._prepare();
  52808. return action;
  52809. };
  52810. /**
  52811. * Unregisters an action to this action manager
  52812. * @param action defines the action to be unregistered
  52813. * @return a boolean indicating whether the action has been unregistered
  52814. */
  52815. ActionManager.prototype.unregisterAction = function (action) {
  52816. var index = this.actions.indexOf(action);
  52817. if (index !== -1) {
  52818. this.actions.splice(index, 1);
  52819. ActionManager.Triggers[action.trigger] -= 1;
  52820. if (ActionManager.Triggers[action.trigger] === 0) {
  52821. delete ActionManager.Triggers[action.trigger];
  52822. }
  52823. delete action._actionManager;
  52824. return true;
  52825. }
  52826. return false;
  52827. };
  52828. /**
  52829. * Process a specific trigger
  52830. * @param trigger defines the trigger to process
  52831. * @param evt defines the event details to be processed
  52832. */
  52833. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52834. for (var index = 0; index < this.actions.length; index++) {
  52835. var action = this.actions[index];
  52836. if (action.trigger === trigger) {
  52837. if (evt) {
  52838. if (trigger === ActionManager.OnKeyUpTrigger
  52839. || trigger === ActionManager.OnKeyDownTrigger) {
  52840. var parameter = action.getTriggerParameter();
  52841. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52842. if (!parameter.toLowerCase) {
  52843. continue;
  52844. }
  52845. var lowerCase = parameter.toLowerCase();
  52846. if (lowerCase !== evt.sourceEvent.key) {
  52847. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52848. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52849. if (actualkey !== lowerCase) {
  52850. continue;
  52851. }
  52852. }
  52853. }
  52854. }
  52855. }
  52856. action._executeCurrent(evt);
  52857. }
  52858. }
  52859. };
  52860. /** @hidden */
  52861. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52862. var properties = propertyPath.split(".");
  52863. for (var index = 0; index < properties.length - 1; index++) {
  52864. target = target[properties[index]];
  52865. }
  52866. return target;
  52867. };
  52868. /** @hidden */
  52869. ActionManager.prototype._getProperty = function (propertyPath) {
  52870. var properties = propertyPath.split(".");
  52871. return properties[properties.length - 1];
  52872. };
  52873. /**
  52874. * Serialize this manager to a JSON object
  52875. * @param name defines the property name to store this manager
  52876. * @returns a JSON representation of this manager
  52877. */
  52878. ActionManager.prototype.serialize = function (name) {
  52879. var root = {
  52880. children: new Array(),
  52881. name: name,
  52882. type: 3,
  52883. properties: new Array() // Empty for root but required
  52884. };
  52885. for (var i = 0; i < this.actions.length; i++) {
  52886. var triggerObject = {
  52887. type: 0,
  52888. children: new Array(),
  52889. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52890. properties: new Array()
  52891. };
  52892. var triggerOptions = this.actions[i].triggerOptions;
  52893. if (triggerOptions && typeof triggerOptions !== "number") {
  52894. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52895. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52896. }
  52897. else {
  52898. var parameter = {};
  52899. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52900. if (triggerOptions.parameter.mesh) {
  52901. parameter._meshId = triggerOptions.parameter.mesh.id;
  52902. }
  52903. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52904. }
  52905. }
  52906. // Serialize child action, recursively
  52907. this.actions[i].serialize(triggerObject);
  52908. // Add serialized trigger
  52909. root.children.push(triggerObject);
  52910. }
  52911. return root;
  52912. };
  52913. /**
  52914. * Creates a new ActionManager from a JSON data
  52915. * @param parsedActions defines the JSON data to read from
  52916. * @param object defines the hosting mesh
  52917. * @param scene defines the hosting scene
  52918. */
  52919. ActionManager.Parse = function (parsedActions, object, scene) {
  52920. var actionManager = new ActionManager(scene);
  52921. if (object === null)
  52922. scene.actionManager = actionManager;
  52923. else
  52924. object.actionManager = actionManager;
  52925. // instanciate a new object
  52926. var instanciate = function (name, params) {
  52927. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52928. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52929. newInstance.constructor.apply(newInstance, params);
  52930. return newInstance;
  52931. };
  52932. var parseParameter = function (name, value, target, propertyPath) {
  52933. if (propertyPath === null) {
  52934. // String, boolean or float
  52935. var floatValue = parseFloat(value);
  52936. if (value === "true" || value === "false")
  52937. return value === "true";
  52938. else
  52939. return isNaN(floatValue) ? value : floatValue;
  52940. }
  52941. var effectiveTarget = propertyPath.split(".");
  52942. var values = value.split(",");
  52943. // Get effective Target
  52944. for (var i = 0; i < effectiveTarget.length; i++) {
  52945. target = target[effectiveTarget[i]];
  52946. }
  52947. // Return appropriate value with its type
  52948. if (typeof (target) === "boolean")
  52949. return values[0] === "true";
  52950. if (typeof (target) === "string")
  52951. return values[0];
  52952. // Parameters with multiple values such as Vector3 etc.
  52953. var split = new Array();
  52954. for (var i = 0; i < values.length; i++)
  52955. split.push(parseFloat(values[i]));
  52956. if (target instanceof BABYLON.Vector3)
  52957. return BABYLON.Vector3.FromArray(split);
  52958. if (target instanceof BABYLON.Vector4)
  52959. return BABYLON.Vector4.FromArray(split);
  52960. if (target instanceof BABYLON.Color3)
  52961. return BABYLON.Color3.FromArray(split);
  52962. if (target instanceof BABYLON.Color4)
  52963. return BABYLON.Color4.FromArray(split);
  52964. return parseFloat(values[0]);
  52965. };
  52966. // traverse graph per trigger
  52967. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52968. if (combineArray === void 0) { combineArray = null; }
  52969. if (parsedAction.detached)
  52970. return;
  52971. var parameters = new Array();
  52972. var target = null;
  52973. var propertyPath = null;
  52974. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52975. // Parameters
  52976. if (parsedAction.type === 2)
  52977. parameters.push(actionManager);
  52978. else
  52979. parameters.push(trigger);
  52980. if (combine) {
  52981. var actions = new Array();
  52982. for (var j = 0; j < parsedAction.combine.length; j++) {
  52983. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52984. }
  52985. parameters.push(actions);
  52986. }
  52987. else {
  52988. for (var i = 0; i < parsedAction.properties.length; i++) {
  52989. var value = parsedAction.properties[i].value;
  52990. var name = parsedAction.properties[i].name;
  52991. var targetType = parsedAction.properties[i].targetType;
  52992. if (name === "target")
  52993. if (targetType !== null && targetType === "SceneProperties")
  52994. value = target = scene;
  52995. else
  52996. value = target = scene.getNodeByName(value);
  52997. else if (name === "parent")
  52998. value = scene.getNodeByName(value);
  52999. else if (name === "sound")
  53000. value = scene.getSoundByName(value);
  53001. else if (name !== "propertyPath") {
  53002. if (parsedAction.type === 2 && name === "operator")
  53003. value = BABYLON.ValueCondition[value];
  53004. else
  53005. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53006. }
  53007. else {
  53008. propertyPath = value;
  53009. }
  53010. parameters.push(value);
  53011. }
  53012. }
  53013. if (combineArray === null) {
  53014. parameters.push(condition);
  53015. }
  53016. else {
  53017. parameters.push(null);
  53018. }
  53019. // If interpolate value action
  53020. if (parsedAction.name === "InterpolateValueAction") {
  53021. var param = parameters[parameters.length - 2];
  53022. parameters[parameters.length - 1] = param;
  53023. parameters[parameters.length - 2] = condition;
  53024. }
  53025. // Action or condition(s) and not CombineAction
  53026. var newAction = instanciate(parsedAction.name, parameters);
  53027. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53028. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53029. if (action)
  53030. action.then(nothing);
  53031. else
  53032. actionManager.registerAction(nothing);
  53033. action = nothing;
  53034. }
  53035. if (combineArray === null) {
  53036. if (newAction instanceof BABYLON.Condition) {
  53037. condition = newAction;
  53038. newAction = action;
  53039. }
  53040. else {
  53041. condition = null;
  53042. if (action)
  53043. action.then(newAction);
  53044. else
  53045. actionManager.registerAction(newAction);
  53046. }
  53047. }
  53048. else {
  53049. combineArray.push(newAction);
  53050. }
  53051. for (var i = 0; i < parsedAction.children.length; i++)
  53052. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53053. };
  53054. // triggers
  53055. for (var i = 0; i < parsedActions.children.length; i++) {
  53056. var triggerParams;
  53057. var trigger = parsedActions.children[i];
  53058. if (trigger.properties.length > 0) {
  53059. var param = trigger.properties[0].value;
  53060. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53061. if (value._meshId) {
  53062. value.mesh = scene.getMeshByID(value._meshId);
  53063. }
  53064. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53065. }
  53066. else
  53067. triggerParams = ActionManager[trigger.name];
  53068. for (var j = 0; j < trigger.children.length; j++) {
  53069. if (!trigger.detached)
  53070. traverse(trigger.children[j], triggerParams, null, null);
  53071. }
  53072. }
  53073. };
  53074. /**
  53075. * Get a trigger name by index
  53076. * @param trigger defines the trigger index
  53077. * @returns a trigger name
  53078. */
  53079. ActionManager.GetTriggerName = function (trigger) {
  53080. switch (trigger) {
  53081. case 0: return "NothingTrigger";
  53082. case 1: return "OnPickTrigger";
  53083. case 2: return "OnLeftPickTrigger";
  53084. case 3: return "OnRightPickTrigger";
  53085. case 4: return "OnCenterPickTrigger";
  53086. case 5: return "OnPickDownTrigger";
  53087. case 6: return "OnPickUpTrigger";
  53088. case 7: return "OnLongPressTrigger";
  53089. case 8: return "OnPointerOverTrigger";
  53090. case 9: return "OnPointerOutTrigger";
  53091. case 10: return "OnEveryFrameTrigger";
  53092. case 11: return "OnIntersectionEnterTrigger";
  53093. case 12: return "OnIntersectionExitTrigger";
  53094. case 13: return "OnKeyDownTrigger";
  53095. case 14: return "OnKeyUpTrigger";
  53096. case 15: return "OnPickOutTrigger";
  53097. default: return "";
  53098. }
  53099. };
  53100. // Statics
  53101. ActionManager._NothingTrigger = 0;
  53102. ActionManager._OnPickTrigger = 1;
  53103. ActionManager._OnLeftPickTrigger = 2;
  53104. ActionManager._OnRightPickTrigger = 3;
  53105. ActionManager._OnCenterPickTrigger = 4;
  53106. ActionManager._OnPickDownTrigger = 5;
  53107. ActionManager._OnDoublePickTrigger = 6;
  53108. ActionManager._OnPickUpTrigger = 7;
  53109. ActionManager._OnLongPressTrigger = 8;
  53110. ActionManager._OnPointerOverTrigger = 9;
  53111. ActionManager._OnPointerOutTrigger = 10;
  53112. ActionManager._OnEveryFrameTrigger = 11;
  53113. ActionManager._OnIntersectionEnterTrigger = 12;
  53114. ActionManager._OnIntersectionExitTrigger = 13;
  53115. ActionManager._OnKeyDownTrigger = 14;
  53116. ActionManager._OnKeyUpTrigger = 15;
  53117. ActionManager._OnPickOutTrigger = 16;
  53118. /** Gets the list of active triggers */
  53119. ActionManager.Triggers = {};
  53120. return ActionManager;
  53121. }());
  53122. BABYLON.ActionManager = ActionManager;
  53123. })(BABYLON || (BABYLON = {}));
  53124. //# sourceMappingURL=babylon.actionManager.js.map
  53125. var BABYLON;
  53126. (function (BABYLON) {
  53127. var InterpolateValueAction = /** @class */ (function (_super) {
  53128. __extends(InterpolateValueAction, _super);
  53129. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53130. if (duration === void 0) { duration = 1000; }
  53131. var _this = _super.call(this, triggerOptions, condition) || this;
  53132. _this.propertyPath = propertyPath;
  53133. _this.value = value;
  53134. _this.duration = duration;
  53135. _this.stopOtherAnimations = stopOtherAnimations;
  53136. _this.onInterpolationDone = onInterpolationDone;
  53137. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53138. _this._target = _this._effectiveTarget = target;
  53139. return _this;
  53140. }
  53141. InterpolateValueAction.prototype._prepare = function () {
  53142. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53143. this._property = this._getProperty(this.propertyPath);
  53144. };
  53145. InterpolateValueAction.prototype.execute = function () {
  53146. var _this = this;
  53147. var scene = this._actionManager.getScene();
  53148. var keys = [
  53149. {
  53150. frame: 0,
  53151. value: this._effectiveTarget[this._property]
  53152. }, {
  53153. frame: 100,
  53154. value: this.value
  53155. }
  53156. ];
  53157. var dataType;
  53158. if (typeof this.value === "number") {
  53159. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53160. }
  53161. else if (this.value instanceof BABYLON.Color3) {
  53162. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53163. }
  53164. else if (this.value instanceof BABYLON.Vector3) {
  53165. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53166. }
  53167. else if (this.value instanceof BABYLON.Matrix) {
  53168. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53169. }
  53170. else if (this.value instanceof BABYLON.Quaternion) {
  53171. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53172. }
  53173. else {
  53174. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53175. return;
  53176. }
  53177. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53178. animation.setKeys(keys);
  53179. if (this.stopOtherAnimations) {
  53180. scene.stopAnimation(this._effectiveTarget);
  53181. }
  53182. var wrapper = function () {
  53183. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53184. if (_this.onInterpolationDone) {
  53185. _this.onInterpolationDone();
  53186. }
  53187. };
  53188. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53189. };
  53190. InterpolateValueAction.prototype.serialize = function (parent) {
  53191. return _super.prototype._serialize.call(this, {
  53192. name: "InterpolateValueAction",
  53193. properties: [
  53194. BABYLON.Action._GetTargetProperty(this._target),
  53195. { name: "propertyPath", value: this.propertyPath },
  53196. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53197. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53198. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53199. ]
  53200. }, parent);
  53201. };
  53202. return InterpolateValueAction;
  53203. }(BABYLON.Action));
  53204. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53205. })(BABYLON || (BABYLON = {}));
  53206. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53207. var BABYLON;
  53208. (function (BABYLON) {
  53209. var SwitchBooleanAction = /** @class */ (function (_super) {
  53210. __extends(SwitchBooleanAction, _super);
  53211. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53212. var _this = _super.call(this, triggerOptions, condition) || this;
  53213. _this.propertyPath = propertyPath;
  53214. _this._target = _this._effectiveTarget = target;
  53215. return _this;
  53216. }
  53217. SwitchBooleanAction.prototype._prepare = function () {
  53218. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53219. this._property = this._getProperty(this.propertyPath);
  53220. };
  53221. SwitchBooleanAction.prototype.execute = function () {
  53222. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53223. };
  53224. SwitchBooleanAction.prototype.serialize = function (parent) {
  53225. return _super.prototype._serialize.call(this, {
  53226. name: "SwitchBooleanAction",
  53227. properties: [
  53228. BABYLON.Action._GetTargetProperty(this._target),
  53229. { name: "propertyPath", value: this.propertyPath }
  53230. ]
  53231. }, parent);
  53232. };
  53233. return SwitchBooleanAction;
  53234. }(BABYLON.Action));
  53235. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53236. var SetStateAction = /** @class */ (function (_super) {
  53237. __extends(SetStateAction, _super);
  53238. function SetStateAction(triggerOptions, target, value, condition) {
  53239. var _this = _super.call(this, triggerOptions, condition) || this;
  53240. _this.value = value;
  53241. _this._target = target;
  53242. return _this;
  53243. }
  53244. SetStateAction.prototype.execute = function () {
  53245. this._target.state = this.value;
  53246. };
  53247. SetStateAction.prototype.serialize = function (parent) {
  53248. return _super.prototype._serialize.call(this, {
  53249. name: "SetStateAction",
  53250. properties: [
  53251. BABYLON.Action._GetTargetProperty(this._target),
  53252. { name: "value", value: this.value }
  53253. ]
  53254. }, parent);
  53255. };
  53256. return SetStateAction;
  53257. }(BABYLON.Action));
  53258. BABYLON.SetStateAction = SetStateAction;
  53259. var SetValueAction = /** @class */ (function (_super) {
  53260. __extends(SetValueAction, _super);
  53261. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53262. var _this = _super.call(this, triggerOptions, condition) || this;
  53263. _this.propertyPath = propertyPath;
  53264. _this.value = value;
  53265. _this._target = _this._effectiveTarget = target;
  53266. return _this;
  53267. }
  53268. SetValueAction.prototype._prepare = function () {
  53269. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53270. this._property = this._getProperty(this.propertyPath);
  53271. };
  53272. SetValueAction.prototype.execute = function () {
  53273. this._effectiveTarget[this._property] = this.value;
  53274. if (this._target.markAsDirty) {
  53275. this._target.markAsDirty(this._property);
  53276. }
  53277. };
  53278. SetValueAction.prototype.serialize = function (parent) {
  53279. return _super.prototype._serialize.call(this, {
  53280. name: "SetValueAction",
  53281. properties: [
  53282. BABYLON.Action._GetTargetProperty(this._target),
  53283. { name: "propertyPath", value: this.propertyPath },
  53284. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53285. ]
  53286. }, parent);
  53287. };
  53288. return SetValueAction;
  53289. }(BABYLON.Action));
  53290. BABYLON.SetValueAction = SetValueAction;
  53291. var IncrementValueAction = /** @class */ (function (_super) {
  53292. __extends(IncrementValueAction, _super);
  53293. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53294. var _this = _super.call(this, triggerOptions, condition) || this;
  53295. _this.propertyPath = propertyPath;
  53296. _this.value = value;
  53297. _this._target = _this._effectiveTarget = target;
  53298. return _this;
  53299. }
  53300. IncrementValueAction.prototype._prepare = function () {
  53301. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53302. this._property = this._getProperty(this.propertyPath);
  53303. if (typeof this._effectiveTarget[this._property] !== "number") {
  53304. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53305. }
  53306. };
  53307. IncrementValueAction.prototype.execute = function () {
  53308. this._effectiveTarget[this._property] += this.value;
  53309. if (this._target.markAsDirty) {
  53310. this._target.markAsDirty(this._property);
  53311. }
  53312. };
  53313. IncrementValueAction.prototype.serialize = function (parent) {
  53314. return _super.prototype._serialize.call(this, {
  53315. name: "IncrementValueAction",
  53316. properties: [
  53317. BABYLON.Action._GetTargetProperty(this._target),
  53318. { name: "propertyPath", value: this.propertyPath },
  53319. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53320. ]
  53321. }, parent);
  53322. };
  53323. return IncrementValueAction;
  53324. }(BABYLON.Action));
  53325. BABYLON.IncrementValueAction = IncrementValueAction;
  53326. var PlayAnimationAction = /** @class */ (function (_super) {
  53327. __extends(PlayAnimationAction, _super);
  53328. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53329. var _this = _super.call(this, triggerOptions, condition) || this;
  53330. _this.from = from;
  53331. _this.to = to;
  53332. _this.loop = loop;
  53333. _this._target = target;
  53334. return _this;
  53335. }
  53336. PlayAnimationAction.prototype._prepare = function () {
  53337. };
  53338. PlayAnimationAction.prototype.execute = function () {
  53339. var scene = this._actionManager.getScene();
  53340. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53341. };
  53342. PlayAnimationAction.prototype.serialize = function (parent) {
  53343. return _super.prototype._serialize.call(this, {
  53344. name: "PlayAnimationAction",
  53345. properties: [
  53346. BABYLON.Action._GetTargetProperty(this._target),
  53347. { name: "from", value: String(this.from) },
  53348. { name: "to", value: String(this.to) },
  53349. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53350. ]
  53351. }, parent);
  53352. };
  53353. return PlayAnimationAction;
  53354. }(BABYLON.Action));
  53355. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53356. var StopAnimationAction = /** @class */ (function (_super) {
  53357. __extends(StopAnimationAction, _super);
  53358. function StopAnimationAction(triggerOptions, target, condition) {
  53359. var _this = _super.call(this, triggerOptions, condition) || this;
  53360. _this._target = target;
  53361. return _this;
  53362. }
  53363. StopAnimationAction.prototype._prepare = function () {
  53364. };
  53365. StopAnimationAction.prototype.execute = function () {
  53366. var scene = this._actionManager.getScene();
  53367. scene.stopAnimation(this._target);
  53368. };
  53369. StopAnimationAction.prototype.serialize = function (parent) {
  53370. return _super.prototype._serialize.call(this, {
  53371. name: "StopAnimationAction",
  53372. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53373. }, parent);
  53374. };
  53375. return StopAnimationAction;
  53376. }(BABYLON.Action));
  53377. BABYLON.StopAnimationAction = StopAnimationAction;
  53378. var DoNothingAction = /** @class */ (function (_super) {
  53379. __extends(DoNothingAction, _super);
  53380. function DoNothingAction(triggerOptions, condition) {
  53381. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53382. return _super.call(this, triggerOptions, condition) || this;
  53383. }
  53384. DoNothingAction.prototype.execute = function () {
  53385. };
  53386. DoNothingAction.prototype.serialize = function (parent) {
  53387. return _super.prototype._serialize.call(this, {
  53388. name: "DoNothingAction",
  53389. properties: []
  53390. }, parent);
  53391. };
  53392. return DoNothingAction;
  53393. }(BABYLON.Action));
  53394. BABYLON.DoNothingAction = DoNothingAction;
  53395. var CombineAction = /** @class */ (function (_super) {
  53396. __extends(CombineAction, _super);
  53397. function CombineAction(triggerOptions, children, condition) {
  53398. var _this = _super.call(this, triggerOptions, condition) || this;
  53399. _this.children = children;
  53400. return _this;
  53401. }
  53402. CombineAction.prototype._prepare = function () {
  53403. for (var index = 0; index < this.children.length; index++) {
  53404. this.children[index]._actionManager = this._actionManager;
  53405. this.children[index]._prepare();
  53406. }
  53407. };
  53408. CombineAction.prototype.execute = function (evt) {
  53409. for (var index = 0; index < this.children.length; index++) {
  53410. this.children[index].execute(evt);
  53411. }
  53412. };
  53413. CombineAction.prototype.serialize = function (parent) {
  53414. var serializationObject = _super.prototype._serialize.call(this, {
  53415. name: "CombineAction",
  53416. properties: [],
  53417. combine: []
  53418. }, parent);
  53419. for (var i = 0; i < this.children.length; i++) {
  53420. serializationObject.combine.push(this.children[i].serialize(null));
  53421. }
  53422. return serializationObject;
  53423. };
  53424. return CombineAction;
  53425. }(BABYLON.Action));
  53426. BABYLON.CombineAction = CombineAction;
  53427. var ExecuteCodeAction = /** @class */ (function (_super) {
  53428. __extends(ExecuteCodeAction, _super);
  53429. function ExecuteCodeAction(triggerOptions, func, condition) {
  53430. var _this = _super.call(this, triggerOptions, condition) || this;
  53431. _this.func = func;
  53432. return _this;
  53433. }
  53434. ExecuteCodeAction.prototype.execute = function (evt) {
  53435. this.func(evt);
  53436. };
  53437. return ExecuteCodeAction;
  53438. }(BABYLON.Action));
  53439. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53440. var SetParentAction = /** @class */ (function (_super) {
  53441. __extends(SetParentAction, _super);
  53442. function SetParentAction(triggerOptions, target, parent, condition) {
  53443. var _this = _super.call(this, triggerOptions, condition) || this;
  53444. _this._target = target;
  53445. _this._parent = parent;
  53446. return _this;
  53447. }
  53448. SetParentAction.prototype._prepare = function () {
  53449. };
  53450. SetParentAction.prototype.execute = function () {
  53451. if (this._target.parent === this._parent) {
  53452. return;
  53453. }
  53454. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53455. invertParentWorldMatrix.invert();
  53456. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53457. this._target.parent = this._parent;
  53458. };
  53459. SetParentAction.prototype.serialize = function (parent) {
  53460. return _super.prototype._serialize.call(this, {
  53461. name: "SetParentAction",
  53462. properties: [
  53463. BABYLON.Action._GetTargetProperty(this._target),
  53464. BABYLON.Action._GetTargetProperty(this._parent),
  53465. ]
  53466. }, parent);
  53467. };
  53468. return SetParentAction;
  53469. }(BABYLON.Action));
  53470. BABYLON.SetParentAction = SetParentAction;
  53471. var PlaySoundAction = /** @class */ (function (_super) {
  53472. __extends(PlaySoundAction, _super);
  53473. function PlaySoundAction(triggerOptions, sound, condition) {
  53474. var _this = _super.call(this, triggerOptions, condition) || this;
  53475. _this._sound = sound;
  53476. return _this;
  53477. }
  53478. PlaySoundAction.prototype._prepare = function () {
  53479. };
  53480. PlaySoundAction.prototype.execute = function () {
  53481. if (this._sound !== undefined)
  53482. this._sound.play();
  53483. };
  53484. PlaySoundAction.prototype.serialize = function (parent) {
  53485. return _super.prototype._serialize.call(this, {
  53486. name: "PlaySoundAction",
  53487. properties: [{ name: "sound", value: this._sound.name }]
  53488. }, parent);
  53489. };
  53490. return PlaySoundAction;
  53491. }(BABYLON.Action));
  53492. BABYLON.PlaySoundAction = PlaySoundAction;
  53493. var StopSoundAction = /** @class */ (function (_super) {
  53494. __extends(StopSoundAction, _super);
  53495. function StopSoundAction(triggerOptions, sound, condition) {
  53496. var _this = _super.call(this, triggerOptions, condition) || this;
  53497. _this._sound = sound;
  53498. return _this;
  53499. }
  53500. StopSoundAction.prototype._prepare = function () {
  53501. };
  53502. StopSoundAction.prototype.execute = function () {
  53503. if (this._sound !== undefined)
  53504. this._sound.stop();
  53505. };
  53506. StopSoundAction.prototype.serialize = function (parent) {
  53507. return _super.prototype._serialize.call(this, {
  53508. name: "StopSoundAction",
  53509. properties: [{ name: "sound", value: this._sound.name }]
  53510. }, parent);
  53511. };
  53512. return StopSoundAction;
  53513. }(BABYLON.Action));
  53514. BABYLON.StopSoundAction = StopSoundAction;
  53515. })(BABYLON || (BABYLON = {}));
  53516. //# sourceMappingURL=babylon.directActions.js.map
  53517. var BABYLON;
  53518. (function (BABYLON) {
  53519. var SpriteManager = /** @class */ (function () {
  53520. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53521. if (epsilon === void 0) { epsilon = 0.01; }
  53522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53523. this.name = name;
  53524. this.sprites = new Array();
  53525. this.renderingGroupId = 0;
  53526. this.layerMask = 0x0FFFFFFF;
  53527. this.fogEnabled = true;
  53528. this.isPickable = false;
  53529. /**
  53530. * An event triggered when the manager is disposed.
  53531. */
  53532. this.onDisposeObservable = new BABYLON.Observable();
  53533. this._vertexBuffers = {};
  53534. this._capacity = capacity;
  53535. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53536. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53537. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53538. if (cellSize.width && cellSize.height) {
  53539. this.cellWidth = cellSize.width;
  53540. this.cellHeight = cellSize.height;
  53541. }
  53542. else if (cellSize !== undefined) {
  53543. this.cellWidth = cellSize;
  53544. this.cellHeight = cellSize;
  53545. }
  53546. else {
  53547. return;
  53548. }
  53549. this._epsilon = epsilon;
  53550. this._scene = scene;
  53551. this._scene.spriteManagers.push(this);
  53552. var indices = [];
  53553. var index = 0;
  53554. for (var count = 0; count < capacity; count++) {
  53555. indices.push(index);
  53556. indices.push(index + 1);
  53557. indices.push(index + 2);
  53558. indices.push(index);
  53559. indices.push(index + 2);
  53560. indices.push(index + 3);
  53561. index += 4;
  53562. }
  53563. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53564. // VBO
  53565. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53566. this._vertexData = new Float32Array(capacity * 16 * 4);
  53567. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53568. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53569. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53570. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53571. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53572. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53573. this._vertexBuffers["options"] = options;
  53574. this._vertexBuffers["cellInfo"] = cellInfo;
  53575. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53576. // Effects
  53577. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53578. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53579. }
  53580. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53581. set: function (callback) {
  53582. if (this._onDisposeObserver) {
  53583. this.onDisposeObservable.remove(this._onDisposeObserver);
  53584. }
  53585. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53586. },
  53587. enumerable: true,
  53588. configurable: true
  53589. });
  53590. Object.defineProperty(SpriteManager.prototype, "texture", {
  53591. get: function () {
  53592. return this._spriteTexture;
  53593. },
  53594. set: function (value) {
  53595. this._spriteTexture = value;
  53596. },
  53597. enumerable: true,
  53598. configurable: true
  53599. });
  53600. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53601. var arrayOffset = index * 16;
  53602. if (offsetX === 0)
  53603. offsetX = this._epsilon;
  53604. else if (offsetX === 1)
  53605. offsetX = 1 - this._epsilon;
  53606. if (offsetY === 0)
  53607. offsetY = this._epsilon;
  53608. else if (offsetY === 1)
  53609. offsetY = 1 - this._epsilon;
  53610. this._vertexData[arrayOffset] = sprite.position.x;
  53611. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53612. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53613. this._vertexData[arrayOffset + 3] = sprite.angle;
  53614. this._vertexData[arrayOffset + 4] = sprite.width;
  53615. this._vertexData[arrayOffset + 5] = sprite.height;
  53616. this._vertexData[arrayOffset + 6] = offsetX;
  53617. this._vertexData[arrayOffset + 7] = offsetY;
  53618. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53619. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53620. var offset = (sprite.cellIndex / rowSize) >> 0;
  53621. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53622. this._vertexData[arrayOffset + 11] = offset;
  53623. // Color
  53624. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53625. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53626. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53627. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53628. };
  53629. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53630. var count = Math.min(this._capacity, this.sprites.length);
  53631. var min = BABYLON.Vector3.Zero();
  53632. var max = BABYLON.Vector3.Zero();
  53633. var distance = Number.MAX_VALUE;
  53634. var currentSprite = null;
  53635. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53636. var cameraView = camera.getViewMatrix();
  53637. for (var index = 0; index < count; index++) {
  53638. var sprite = this.sprites[index];
  53639. if (!sprite) {
  53640. continue;
  53641. }
  53642. if (predicate) {
  53643. if (!predicate(sprite)) {
  53644. continue;
  53645. }
  53646. }
  53647. else if (!sprite.isPickable) {
  53648. continue;
  53649. }
  53650. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53651. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53652. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53653. if (ray.intersectsBoxMinMax(min, max)) {
  53654. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53655. if (distance > currentDistance) {
  53656. distance = currentDistance;
  53657. currentSprite = sprite;
  53658. if (fastCheck) {
  53659. break;
  53660. }
  53661. }
  53662. }
  53663. }
  53664. if (currentSprite) {
  53665. var result = new BABYLON.PickingInfo();
  53666. result.hit = true;
  53667. result.pickedSprite = currentSprite;
  53668. result.distance = distance;
  53669. return result;
  53670. }
  53671. return null;
  53672. };
  53673. SpriteManager.prototype.render = function () {
  53674. // Check
  53675. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53676. return;
  53677. var engine = this._scene.getEngine();
  53678. var baseSize = this._spriteTexture.getBaseSize();
  53679. // Sprites
  53680. var deltaTime = engine.getDeltaTime();
  53681. var max = Math.min(this._capacity, this.sprites.length);
  53682. var rowSize = baseSize.width / this.cellWidth;
  53683. var offset = 0;
  53684. for (var index = 0; index < max; index++) {
  53685. var sprite = this.sprites[index];
  53686. if (!sprite || !sprite.isVisible) {
  53687. continue;
  53688. }
  53689. sprite._animate(deltaTime);
  53690. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53691. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53692. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53693. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53694. }
  53695. this._buffer.update(this._vertexData);
  53696. // Render
  53697. var effect = this._effectBase;
  53698. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53699. effect = this._effectFog;
  53700. }
  53701. engine.enableEffect(effect);
  53702. var viewMatrix = this._scene.getViewMatrix();
  53703. effect.setTexture("diffuseSampler", this._spriteTexture);
  53704. effect.setMatrix("view", viewMatrix);
  53705. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53706. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53707. // Fog
  53708. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53709. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53710. effect.setColor3("vFogColor", this._scene.fogColor);
  53711. }
  53712. // VBOs
  53713. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53714. // Draw order
  53715. engine.setDepthFunctionToLessOrEqual();
  53716. effect.setBool("alphaTest", true);
  53717. engine.setColorWrite(false);
  53718. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53719. engine.setColorWrite(true);
  53720. effect.setBool("alphaTest", false);
  53721. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53722. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53723. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53724. };
  53725. SpriteManager.prototype.dispose = function () {
  53726. if (this._buffer) {
  53727. this._buffer.dispose();
  53728. this._buffer = null;
  53729. }
  53730. if (this._indexBuffer) {
  53731. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53732. this._indexBuffer = null;
  53733. }
  53734. if (this._spriteTexture) {
  53735. this._spriteTexture.dispose();
  53736. this._spriteTexture = null;
  53737. }
  53738. // Remove from scene
  53739. var index = this._scene.spriteManagers.indexOf(this);
  53740. this._scene.spriteManagers.splice(index, 1);
  53741. // Callback
  53742. this.onDisposeObservable.notifyObservers(this);
  53743. this.onDisposeObservable.clear();
  53744. };
  53745. return SpriteManager;
  53746. }());
  53747. BABYLON.SpriteManager = SpriteManager;
  53748. })(BABYLON || (BABYLON = {}));
  53749. //# sourceMappingURL=babylon.spriteManager.js.map
  53750. var BABYLON;
  53751. (function (BABYLON) {
  53752. var Sprite = /** @class */ (function () {
  53753. function Sprite(name, manager) {
  53754. this.name = name;
  53755. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53756. this.width = 1.0;
  53757. this.height = 1.0;
  53758. this.angle = 0;
  53759. this.cellIndex = 0;
  53760. this.invertU = 0;
  53761. this.invertV = 0;
  53762. this.animations = new Array();
  53763. this.isPickable = false;
  53764. this._animationStarted = false;
  53765. this._loopAnimation = false;
  53766. this._fromIndex = 0;
  53767. this._toIndex = 0;
  53768. this._delay = 0;
  53769. this._direction = 1;
  53770. this._time = 0;
  53771. /**
  53772. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53773. */
  53774. this.isVisible = true;
  53775. this._manager = manager;
  53776. this._manager.sprites.push(this);
  53777. this.position = BABYLON.Vector3.Zero();
  53778. }
  53779. Object.defineProperty(Sprite.prototype, "size", {
  53780. get: function () {
  53781. return this.width;
  53782. },
  53783. set: function (value) {
  53784. this.width = value;
  53785. this.height = value;
  53786. },
  53787. enumerable: true,
  53788. configurable: true
  53789. });
  53790. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53791. this._fromIndex = from;
  53792. this._toIndex = to;
  53793. this._loopAnimation = loop;
  53794. this._delay = delay;
  53795. this._animationStarted = true;
  53796. this._direction = from < to ? 1 : -1;
  53797. this.cellIndex = from;
  53798. this._time = 0;
  53799. this._onAnimationEnd = onAnimationEnd;
  53800. };
  53801. Sprite.prototype.stopAnimation = function () {
  53802. this._animationStarted = false;
  53803. };
  53804. Sprite.prototype._animate = function (deltaTime) {
  53805. if (!this._animationStarted)
  53806. return;
  53807. this._time += deltaTime;
  53808. if (this._time > this._delay) {
  53809. this._time = this._time % this._delay;
  53810. this.cellIndex += this._direction;
  53811. if (this.cellIndex > this._toIndex) {
  53812. if (this._loopAnimation) {
  53813. this.cellIndex = this._fromIndex;
  53814. }
  53815. else {
  53816. this.cellIndex = this._toIndex;
  53817. this._animationStarted = false;
  53818. if (this._onAnimationEnd) {
  53819. this._onAnimationEnd();
  53820. }
  53821. if (this.disposeWhenFinishedAnimating) {
  53822. this.dispose();
  53823. }
  53824. }
  53825. }
  53826. }
  53827. };
  53828. Sprite.prototype.dispose = function () {
  53829. for (var i = 0; i < this._manager.sprites.length; i++) {
  53830. if (this._manager.sprites[i] == this) {
  53831. this._manager.sprites.splice(i, 1);
  53832. }
  53833. }
  53834. };
  53835. return Sprite;
  53836. }());
  53837. BABYLON.Sprite = Sprite;
  53838. })(BABYLON || (BABYLON = {}));
  53839. //# sourceMappingURL=babylon.sprite.js.map
  53840. var BABYLON;
  53841. (function (BABYLON) {
  53842. var IntersectionInfo = /** @class */ (function () {
  53843. function IntersectionInfo(bu, bv, distance) {
  53844. this.bu = bu;
  53845. this.bv = bv;
  53846. this.distance = distance;
  53847. this.faceId = 0;
  53848. this.subMeshId = 0;
  53849. }
  53850. return IntersectionInfo;
  53851. }());
  53852. BABYLON.IntersectionInfo = IntersectionInfo;
  53853. /**
  53854. * Information about the result of picking within a scene
  53855. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53856. */
  53857. var PickingInfo = /** @class */ (function () {
  53858. function PickingInfo() {
  53859. /**
  53860. * If the pick collided with an object
  53861. */
  53862. this.hit = false;
  53863. /**
  53864. * Distance away where the pick collided
  53865. */
  53866. this.distance = 0;
  53867. /**
  53868. * The location of pick collision
  53869. */
  53870. this.pickedPoint = null;
  53871. /**
  53872. * The mesh corrisponding the the pick collision
  53873. */
  53874. this.pickedMesh = null;
  53875. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53876. this.bu = 0;
  53877. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53878. this.bv = 0;
  53879. /** The id of the face on the mesh that was picked */
  53880. this.faceId = -1;
  53881. /** Id of the the submesh that was picked */
  53882. this.subMeshId = 0;
  53883. /** If a sprite was picked, this will be the sprite the pick collided with */
  53884. this.pickedSprite = null;
  53885. /**
  53886. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53887. */
  53888. this.originMesh = null;
  53889. /**
  53890. * The ray that was used to perform the picking.
  53891. */
  53892. this.ray = null;
  53893. }
  53894. /**
  53895. * Gets the normal corrispodning to the face the pick collided with
  53896. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53897. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53898. * @returns The normal corrispodning to the face the pick collided with
  53899. */
  53900. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53901. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53902. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53903. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53904. return null;
  53905. }
  53906. var indices = this.pickedMesh.getIndices();
  53907. if (!indices) {
  53908. return null;
  53909. }
  53910. var result;
  53911. if (useVerticesNormals) {
  53912. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53913. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53914. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53915. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53916. normal0 = normal0.scale(this.bu);
  53917. normal1 = normal1.scale(this.bv);
  53918. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53919. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53920. }
  53921. else {
  53922. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53923. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53924. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53925. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53926. var p1p2 = vertex1.subtract(vertex2);
  53927. var p3p2 = vertex3.subtract(vertex2);
  53928. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53929. }
  53930. if (useWorldCoordinates) {
  53931. var wm = this.pickedMesh.getWorldMatrix();
  53932. if (this.pickedMesh.nonUniformScaling) {
  53933. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53934. wm = BABYLON.Tmp.Matrix[0];
  53935. wm.setTranslationFromFloats(0, 0, 0);
  53936. wm.invert();
  53937. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53938. wm = BABYLON.Tmp.Matrix[1];
  53939. }
  53940. result = BABYLON.Vector3.TransformNormal(result, wm);
  53941. }
  53942. result.normalize();
  53943. return result;
  53944. };
  53945. /**
  53946. * Gets the texture coordinates of where the pick occured
  53947. * @returns the vector containing the coordnates of the texture
  53948. */
  53949. PickingInfo.prototype.getTextureCoordinates = function () {
  53950. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53951. return null;
  53952. }
  53953. var indices = this.pickedMesh.getIndices();
  53954. if (!indices) {
  53955. return null;
  53956. }
  53957. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53958. if (!uvs) {
  53959. return null;
  53960. }
  53961. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53962. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53963. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53964. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53965. uv1 = uv1.scale(this.bu);
  53966. uv2 = uv2.scale(this.bv);
  53967. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53968. };
  53969. return PickingInfo;
  53970. }());
  53971. BABYLON.PickingInfo = PickingInfo;
  53972. })(BABYLON || (BABYLON = {}));
  53973. //# sourceMappingURL=babylon.pickingInfo.js.map
  53974. var BABYLON;
  53975. (function (BABYLON) {
  53976. var Ray = /** @class */ (function () {
  53977. function Ray(origin, direction, length) {
  53978. if (length === void 0) { length = Number.MAX_VALUE; }
  53979. this.origin = origin;
  53980. this.direction = direction;
  53981. this.length = length;
  53982. }
  53983. // Methods
  53984. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53985. var d = 0.0;
  53986. var maxValue = Number.MAX_VALUE;
  53987. var inv;
  53988. var min;
  53989. var max;
  53990. var temp;
  53991. if (Math.abs(this.direction.x) < 0.0000001) {
  53992. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53993. return false;
  53994. }
  53995. }
  53996. else {
  53997. inv = 1.0 / this.direction.x;
  53998. min = (minimum.x - this.origin.x) * inv;
  53999. max = (maximum.x - this.origin.x) * inv;
  54000. if (max === -Infinity) {
  54001. max = Infinity;
  54002. }
  54003. if (min > max) {
  54004. temp = min;
  54005. min = max;
  54006. max = temp;
  54007. }
  54008. d = Math.max(min, d);
  54009. maxValue = Math.min(max, maxValue);
  54010. if (d > maxValue) {
  54011. return false;
  54012. }
  54013. }
  54014. if (Math.abs(this.direction.y) < 0.0000001) {
  54015. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54016. return false;
  54017. }
  54018. }
  54019. else {
  54020. inv = 1.0 / this.direction.y;
  54021. min = (minimum.y - this.origin.y) * inv;
  54022. max = (maximum.y - this.origin.y) * inv;
  54023. if (max === -Infinity) {
  54024. max = Infinity;
  54025. }
  54026. if (min > max) {
  54027. temp = min;
  54028. min = max;
  54029. max = temp;
  54030. }
  54031. d = Math.max(min, d);
  54032. maxValue = Math.min(max, maxValue);
  54033. if (d > maxValue) {
  54034. return false;
  54035. }
  54036. }
  54037. if (Math.abs(this.direction.z) < 0.0000001) {
  54038. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54039. return false;
  54040. }
  54041. }
  54042. else {
  54043. inv = 1.0 / this.direction.z;
  54044. min = (minimum.z - this.origin.z) * inv;
  54045. max = (maximum.z - this.origin.z) * inv;
  54046. if (max === -Infinity) {
  54047. max = Infinity;
  54048. }
  54049. if (min > max) {
  54050. temp = min;
  54051. min = max;
  54052. max = temp;
  54053. }
  54054. d = Math.max(min, d);
  54055. maxValue = Math.min(max, maxValue);
  54056. if (d > maxValue) {
  54057. return false;
  54058. }
  54059. }
  54060. return true;
  54061. };
  54062. Ray.prototype.intersectsBox = function (box) {
  54063. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54064. };
  54065. Ray.prototype.intersectsSphere = function (sphere) {
  54066. var x = sphere.center.x - this.origin.x;
  54067. var y = sphere.center.y - this.origin.y;
  54068. var z = sphere.center.z - this.origin.z;
  54069. var pyth = (x * x) + (y * y) + (z * z);
  54070. var rr = sphere.radius * sphere.radius;
  54071. if (pyth <= rr) {
  54072. return true;
  54073. }
  54074. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54075. if (dot < 0.0) {
  54076. return false;
  54077. }
  54078. var temp = pyth - (dot * dot);
  54079. return temp <= rr;
  54080. };
  54081. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54082. if (!this._edge1) {
  54083. this._edge1 = BABYLON.Vector3.Zero();
  54084. this._edge2 = BABYLON.Vector3.Zero();
  54085. this._pvec = BABYLON.Vector3.Zero();
  54086. this._tvec = BABYLON.Vector3.Zero();
  54087. this._qvec = BABYLON.Vector3.Zero();
  54088. }
  54089. vertex1.subtractToRef(vertex0, this._edge1);
  54090. vertex2.subtractToRef(vertex0, this._edge2);
  54091. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54092. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54093. if (det === 0) {
  54094. return null;
  54095. }
  54096. var invdet = 1 / det;
  54097. this.origin.subtractToRef(vertex0, this._tvec);
  54098. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54099. if (bu < 0 || bu > 1.0) {
  54100. return null;
  54101. }
  54102. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54103. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54104. if (bv < 0 || bu + bv > 1.0) {
  54105. return null;
  54106. }
  54107. //check if the distance is longer than the predefined length.
  54108. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54109. if (distance > this.length) {
  54110. return null;
  54111. }
  54112. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54113. };
  54114. Ray.prototype.intersectsPlane = function (plane) {
  54115. var distance;
  54116. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54117. if (Math.abs(result1) < 9.99999997475243E-07) {
  54118. return null;
  54119. }
  54120. else {
  54121. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54122. distance = (-plane.d - result2) / result1;
  54123. if (distance < 0.0) {
  54124. if (distance < -9.99999997475243E-07) {
  54125. return null;
  54126. }
  54127. else {
  54128. return 0;
  54129. }
  54130. }
  54131. return distance;
  54132. }
  54133. };
  54134. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54135. var tm = BABYLON.Tmp.Matrix[0];
  54136. mesh.getWorldMatrix().invertToRef(tm);
  54137. if (this._tmpRay) {
  54138. Ray.TransformToRef(this, tm, this._tmpRay);
  54139. }
  54140. else {
  54141. this._tmpRay = Ray.Transform(this, tm);
  54142. }
  54143. return mesh.intersects(this._tmpRay, fastCheck);
  54144. };
  54145. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54146. if (results) {
  54147. results.length = 0;
  54148. }
  54149. else {
  54150. results = [];
  54151. }
  54152. for (var i = 0; i < meshes.length; i++) {
  54153. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54154. if (pickInfo.hit) {
  54155. results.push(pickInfo);
  54156. }
  54157. }
  54158. results.sort(this._comparePickingInfo);
  54159. return results;
  54160. };
  54161. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54162. if (pickingInfoA.distance < pickingInfoB.distance) {
  54163. return -1;
  54164. }
  54165. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54166. return 1;
  54167. }
  54168. else {
  54169. return 0;
  54170. }
  54171. };
  54172. /**
  54173. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54174. * @param sega the first point of the segment to test the intersection against
  54175. * @param segb the second point of the segment to test the intersection against
  54176. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54177. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54178. */
  54179. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54180. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54181. var u = segb.subtract(sega);
  54182. var v = rsegb.subtract(this.origin);
  54183. var w = sega.subtract(this.origin);
  54184. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54185. var b = BABYLON.Vector3.Dot(u, v);
  54186. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54187. var d = BABYLON.Vector3.Dot(u, w);
  54188. var e = BABYLON.Vector3.Dot(v, w);
  54189. var D = a * c - b * b; // always >= 0
  54190. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54191. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54192. // compute the line parameters of the two closest points
  54193. if (D < Ray.smallnum) { // the lines are almost parallel
  54194. sN = 0.0; // force using point P0 on segment S1
  54195. sD = 1.0; // to prevent possible division by 0.0 later
  54196. tN = e;
  54197. tD = c;
  54198. }
  54199. else { // get the closest points on the infinite lines
  54200. sN = (b * e - c * d);
  54201. tN = (a * e - b * d);
  54202. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54203. sN = 0.0;
  54204. tN = e;
  54205. tD = c;
  54206. }
  54207. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54208. sN = sD;
  54209. tN = e + b;
  54210. tD = c;
  54211. }
  54212. }
  54213. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54214. tN = 0.0;
  54215. // recompute sc for this edge
  54216. if (-d < 0.0) {
  54217. sN = 0.0;
  54218. }
  54219. else if (-d > a)
  54220. sN = sD;
  54221. else {
  54222. sN = -d;
  54223. sD = a;
  54224. }
  54225. }
  54226. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54227. tN = tD;
  54228. // recompute sc for this edge
  54229. if ((-d + b) < 0.0) {
  54230. sN = 0;
  54231. }
  54232. else if ((-d + b) > a) {
  54233. sN = sD;
  54234. }
  54235. else {
  54236. sN = (-d + b);
  54237. sD = a;
  54238. }
  54239. }
  54240. // finally do the division to get sc and tc
  54241. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54242. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54243. // get the difference of the two closest points
  54244. var qtc = v.multiplyByFloats(tc, tc, tc);
  54245. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54246. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54247. if (isIntersected) {
  54248. return qtc.length();
  54249. }
  54250. return -1;
  54251. };
  54252. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54253. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54254. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54255. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54256. this.direction.normalize();
  54257. return this;
  54258. };
  54259. // Statics
  54260. Ray.Zero = function () {
  54261. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54262. };
  54263. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54264. var result = Ray.Zero();
  54265. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54266. };
  54267. /**
  54268. * 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
  54269. * transformed to the given world matrix.
  54270. * @param origin The origin point
  54271. * @param end The end point
  54272. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54273. */
  54274. Ray.CreateNewFromTo = function (origin, end, world) {
  54275. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54276. var direction = end.subtract(origin);
  54277. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54278. direction.normalize();
  54279. return Ray.Transform(new Ray(origin, direction, length), world);
  54280. };
  54281. Ray.Transform = function (ray, matrix) {
  54282. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54283. Ray.TransformToRef(ray, matrix, result);
  54284. return result;
  54285. };
  54286. Ray.TransformToRef = function (ray, matrix, result) {
  54287. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54288. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54289. result.length = ray.length;
  54290. var dir = result.direction;
  54291. var len = dir.length();
  54292. if (!(len === 0 || len === 1)) {
  54293. var num = 1.0 / len;
  54294. dir.x *= num;
  54295. dir.y *= num;
  54296. dir.z *= num;
  54297. result.length *= len;
  54298. }
  54299. };
  54300. Ray.smallnum = 0.00000001;
  54301. Ray.rayl = 10e8;
  54302. return Ray;
  54303. }());
  54304. BABYLON.Ray = Ray;
  54305. })(BABYLON || (BABYLON = {}));
  54306. //# sourceMappingURL=babylon.ray.js.map
  54307. var BABYLON;
  54308. (function (BABYLON) {
  54309. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54310. if (boxMin.x > sphereCenter.x + sphereRadius)
  54311. return false;
  54312. if (sphereCenter.x - sphereRadius > boxMax.x)
  54313. return false;
  54314. if (boxMin.y > sphereCenter.y + sphereRadius)
  54315. return false;
  54316. if (sphereCenter.y - sphereRadius > boxMax.y)
  54317. return false;
  54318. if (boxMin.z > sphereCenter.z + sphereRadius)
  54319. return false;
  54320. if (sphereCenter.z - sphereRadius > boxMax.z)
  54321. return false;
  54322. return true;
  54323. };
  54324. var getLowestRoot = (function () {
  54325. var result = { root: 0, found: false };
  54326. return function (a, b, c, maxR) {
  54327. result.root = 0;
  54328. result.found = false;
  54329. var determinant = b * b - 4.0 * a * c;
  54330. if (determinant < 0)
  54331. return result;
  54332. var sqrtD = Math.sqrt(determinant);
  54333. var r1 = (-b - sqrtD) / (2.0 * a);
  54334. var r2 = (-b + sqrtD) / (2.0 * a);
  54335. if (r1 > r2) {
  54336. var temp = r2;
  54337. r2 = r1;
  54338. r1 = temp;
  54339. }
  54340. if (r1 > 0 && r1 < maxR) {
  54341. result.root = r1;
  54342. result.found = true;
  54343. return result;
  54344. }
  54345. if (r2 > 0 && r2 < maxR) {
  54346. result.root = r2;
  54347. result.found = true;
  54348. return result;
  54349. }
  54350. return result;
  54351. };
  54352. })();
  54353. var Collider = /** @class */ (function () {
  54354. function Collider() {
  54355. this._collisionPoint = BABYLON.Vector3.Zero();
  54356. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54357. this._tempVector = BABYLON.Vector3.Zero();
  54358. this._tempVector2 = BABYLON.Vector3.Zero();
  54359. this._tempVector3 = BABYLON.Vector3.Zero();
  54360. this._tempVector4 = BABYLON.Vector3.Zero();
  54361. this._edge = BABYLON.Vector3.Zero();
  54362. this._baseToVertex = BABYLON.Vector3.Zero();
  54363. this._destinationPoint = BABYLON.Vector3.Zero();
  54364. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54365. this._displacementVector = BABYLON.Vector3.Zero();
  54366. this._radius = BABYLON.Vector3.One();
  54367. this._retry = 0;
  54368. this._basePointWorld = BABYLON.Vector3.Zero();
  54369. this._velocityWorld = BABYLON.Vector3.Zero();
  54370. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54371. this._collisionMask = -1;
  54372. }
  54373. Object.defineProperty(Collider.prototype, "collisionMask", {
  54374. get: function () {
  54375. return this._collisionMask;
  54376. },
  54377. set: function (mask) {
  54378. this._collisionMask = !isNaN(mask) ? mask : -1;
  54379. },
  54380. enumerable: true,
  54381. configurable: true
  54382. });
  54383. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54384. /**
  54385. * Gets the plane normal used to compute the sliding response (in local space)
  54386. */
  54387. get: function () {
  54388. return this._slidePlaneNormal;
  54389. },
  54390. enumerable: true,
  54391. configurable: true
  54392. });
  54393. // Methods
  54394. Collider.prototype._initialize = function (source, dir, e) {
  54395. this._velocity = dir;
  54396. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54397. this._basePoint = source;
  54398. source.multiplyToRef(this._radius, this._basePointWorld);
  54399. dir.multiplyToRef(this._radius, this._velocityWorld);
  54400. this._velocityWorldLength = this._velocityWorld.length();
  54401. this._epsilon = e;
  54402. this.collisionFound = false;
  54403. };
  54404. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54405. pa.subtractToRef(point, this._tempVector);
  54406. pb.subtractToRef(point, this._tempVector2);
  54407. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54408. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54409. if (d < 0)
  54410. return false;
  54411. pc.subtractToRef(point, this._tempVector3);
  54412. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54413. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54414. if (d < 0)
  54415. return false;
  54416. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54417. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54418. return d >= 0;
  54419. };
  54420. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54421. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54422. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54423. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54424. return false;
  54425. }
  54426. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54427. return false;
  54428. return true;
  54429. };
  54430. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54431. var t0;
  54432. var embeddedInPlane = false;
  54433. //defensive programming, actually not needed.
  54434. if (!trianglePlaneArray) {
  54435. trianglePlaneArray = [];
  54436. }
  54437. if (!trianglePlaneArray[faceIndex]) {
  54438. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54439. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54440. }
  54441. var trianglePlane = trianglePlaneArray[faceIndex];
  54442. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54443. return;
  54444. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54445. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54446. if (normalDotVelocity == 0) {
  54447. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54448. return;
  54449. embeddedInPlane = true;
  54450. t0 = 0;
  54451. }
  54452. else {
  54453. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54454. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54455. if (t0 > t1) {
  54456. var temp = t1;
  54457. t1 = t0;
  54458. t0 = temp;
  54459. }
  54460. if (t0 > 1.0 || t1 < 0.0)
  54461. return;
  54462. if (t0 < 0)
  54463. t0 = 0;
  54464. if (t0 > 1.0)
  54465. t0 = 1.0;
  54466. }
  54467. this._collisionPoint.copyFromFloats(0, 0, 0);
  54468. var found = false;
  54469. var t = 1.0;
  54470. if (!embeddedInPlane) {
  54471. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54472. this._velocity.scaleToRef(t0, this._tempVector);
  54473. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54474. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54475. found = true;
  54476. t = t0;
  54477. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54478. }
  54479. }
  54480. if (!found) {
  54481. var velocitySquaredLength = this._velocity.lengthSquared();
  54482. var a = velocitySquaredLength;
  54483. this._basePoint.subtractToRef(p1, this._tempVector);
  54484. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54485. var c = this._tempVector.lengthSquared() - 1.0;
  54486. var lowestRoot = getLowestRoot(a, b, c, t);
  54487. if (lowestRoot.found) {
  54488. t = lowestRoot.root;
  54489. found = true;
  54490. this._collisionPoint.copyFrom(p1);
  54491. }
  54492. this._basePoint.subtractToRef(p2, this._tempVector);
  54493. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54494. c = this._tempVector.lengthSquared() - 1.0;
  54495. lowestRoot = getLowestRoot(a, b, c, t);
  54496. if (lowestRoot.found) {
  54497. t = lowestRoot.root;
  54498. found = true;
  54499. this._collisionPoint.copyFrom(p2);
  54500. }
  54501. this._basePoint.subtractToRef(p3, this._tempVector);
  54502. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54503. c = this._tempVector.lengthSquared() - 1.0;
  54504. lowestRoot = getLowestRoot(a, b, c, t);
  54505. if (lowestRoot.found) {
  54506. t = lowestRoot.root;
  54507. found = true;
  54508. this._collisionPoint.copyFrom(p3);
  54509. }
  54510. p2.subtractToRef(p1, this._edge);
  54511. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54512. var edgeSquaredLength = this._edge.lengthSquared();
  54513. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54514. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54515. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54516. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54517. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54518. lowestRoot = getLowestRoot(a, b, c, t);
  54519. if (lowestRoot.found) {
  54520. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54521. if (f >= 0.0 && f <= 1.0) {
  54522. t = lowestRoot.root;
  54523. found = true;
  54524. this._edge.scaleInPlace(f);
  54525. p1.addToRef(this._edge, this._collisionPoint);
  54526. }
  54527. }
  54528. p3.subtractToRef(p2, this._edge);
  54529. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54530. edgeSquaredLength = this._edge.lengthSquared();
  54531. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54532. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54533. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54534. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54535. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54536. lowestRoot = getLowestRoot(a, b, c, t);
  54537. if (lowestRoot.found) {
  54538. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54539. if (f >= 0.0 && f <= 1.0) {
  54540. t = lowestRoot.root;
  54541. found = true;
  54542. this._edge.scaleInPlace(f);
  54543. p2.addToRef(this._edge, this._collisionPoint);
  54544. }
  54545. }
  54546. p1.subtractToRef(p3, this._edge);
  54547. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54548. edgeSquaredLength = this._edge.lengthSquared();
  54549. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54550. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54551. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54552. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54553. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54554. lowestRoot = getLowestRoot(a, b, c, t);
  54555. if (lowestRoot.found) {
  54556. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54557. if (f >= 0.0 && f <= 1.0) {
  54558. t = lowestRoot.root;
  54559. found = true;
  54560. this._edge.scaleInPlace(f);
  54561. p3.addToRef(this._edge, this._collisionPoint);
  54562. }
  54563. }
  54564. }
  54565. if (found) {
  54566. var distToCollision = t * this._velocity.length();
  54567. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54568. if (!this.intersectionPoint) {
  54569. this.intersectionPoint = this._collisionPoint.clone();
  54570. }
  54571. else {
  54572. this.intersectionPoint.copyFrom(this._collisionPoint);
  54573. }
  54574. this._nearestDistance = distToCollision;
  54575. this.collisionFound = true;
  54576. }
  54577. }
  54578. };
  54579. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54580. for (var i = indexStart; i < indexEnd; i += 3) {
  54581. var p1 = pts[indices[i] - decal];
  54582. var p2 = pts[indices[i + 1] - decal];
  54583. var p3 = pts[indices[i + 2] - decal];
  54584. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54585. }
  54586. };
  54587. Collider.prototype._getResponse = function (pos, vel) {
  54588. pos.addToRef(vel, this._destinationPoint);
  54589. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54590. this._basePoint.addToRef(vel, pos);
  54591. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54592. this._slidePlaneNormal.normalize();
  54593. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54594. pos.addInPlace(this._displacementVector);
  54595. this.intersectionPoint.addInPlace(this._displacementVector);
  54596. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54597. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54598. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54599. };
  54600. return Collider;
  54601. }());
  54602. BABYLON.Collider = Collider;
  54603. })(BABYLON || (BABYLON = {}));
  54604. //# sourceMappingURL=babylon.collider.js.map
  54605. var BABYLON;
  54606. (function (BABYLON) {
  54607. //WebWorker code will be inserted to this variable.
  54608. BABYLON.CollisionWorker = "";
  54609. /** Defines supported task for worker process */
  54610. var WorkerTaskType;
  54611. (function (WorkerTaskType) {
  54612. /** Initialization */
  54613. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54614. /** Update of geometry */
  54615. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54616. /** Evaluate collision */
  54617. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54618. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54619. /** Defines kind of replies returned by worker */
  54620. var WorkerReplyType;
  54621. (function (WorkerReplyType) {
  54622. /** Success */
  54623. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54624. /** Unkown error */
  54625. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54626. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54627. var CollisionCoordinatorWorker = /** @class */ (function () {
  54628. function CollisionCoordinatorWorker() {
  54629. var _this = this;
  54630. this._scaledPosition = BABYLON.Vector3.Zero();
  54631. this._scaledVelocity = BABYLON.Vector3.Zero();
  54632. this.onMeshUpdated = function (transformNode) {
  54633. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54634. };
  54635. this.onGeometryUpdated = function (geometry) {
  54636. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54637. };
  54638. this._afterRender = function () {
  54639. if (!_this._init)
  54640. return;
  54641. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54642. return;
  54643. }
  54644. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54645. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54646. if (_this._runningUpdated > 4) {
  54647. return;
  54648. }
  54649. ++_this._runningUpdated;
  54650. var payload = {
  54651. updatedMeshes: _this._addUpdateMeshesList,
  54652. updatedGeometries: _this._addUpdateGeometriesList,
  54653. removedGeometries: _this._toRemoveGeometryArray,
  54654. removedMeshes: _this._toRemoveMeshesArray
  54655. };
  54656. var message = {
  54657. payload: payload,
  54658. taskType: WorkerTaskType.UPDATE
  54659. };
  54660. var serializable = [];
  54661. for (var id in payload.updatedGeometries) {
  54662. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54663. //prepare transferables
  54664. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54665. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54666. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54667. }
  54668. }
  54669. _this._worker.postMessage(message, serializable);
  54670. _this._addUpdateMeshesList = {};
  54671. _this._addUpdateGeometriesList = {};
  54672. _this._toRemoveGeometryArray = [];
  54673. _this._toRemoveMeshesArray = [];
  54674. };
  54675. this._onMessageFromWorker = function (e) {
  54676. var returnData = e.data;
  54677. if (returnData.error != WorkerReplyType.SUCCESS) {
  54678. //TODO what errors can be returned from the worker?
  54679. BABYLON.Tools.Warn("error returned from worker!");
  54680. return;
  54681. }
  54682. switch (returnData.taskType) {
  54683. case WorkerTaskType.INIT:
  54684. _this._init = true;
  54685. //Update the worked with ALL of the scene's current state
  54686. _this._scene.meshes.forEach(function (mesh) {
  54687. _this.onMeshAdded(mesh);
  54688. });
  54689. _this._scene.getGeometries().forEach(function (geometry) {
  54690. _this.onGeometryAdded(geometry);
  54691. });
  54692. break;
  54693. case WorkerTaskType.UPDATE:
  54694. _this._runningUpdated--;
  54695. break;
  54696. case WorkerTaskType.COLLIDE:
  54697. var returnPayload = returnData.payload;
  54698. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54699. return;
  54700. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54701. if (callback) {
  54702. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54703. if (mesh) {
  54704. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54705. }
  54706. }
  54707. //cleanup
  54708. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54709. break;
  54710. }
  54711. };
  54712. this._collisionsCallbackArray = [];
  54713. this._init = false;
  54714. this._runningUpdated = 0;
  54715. this._addUpdateMeshesList = {};
  54716. this._addUpdateGeometriesList = {};
  54717. this._toRemoveGeometryArray = [];
  54718. this._toRemoveMeshesArray = [];
  54719. }
  54720. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54721. if (!this._init)
  54722. return;
  54723. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54724. return;
  54725. position.divideToRef(collider._radius, this._scaledPosition);
  54726. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54727. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54728. var payload = {
  54729. collider: {
  54730. position: this._scaledPosition.asArray(),
  54731. velocity: this._scaledVelocity.asArray(),
  54732. radius: collider._radius.asArray()
  54733. },
  54734. collisionId: collisionIndex,
  54735. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54736. maximumRetry: maximumRetry
  54737. };
  54738. var message = {
  54739. payload: payload,
  54740. taskType: WorkerTaskType.COLLIDE
  54741. };
  54742. this._worker.postMessage(message);
  54743. };
  54744. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54745. this._scene = scene;
  54746. this._scene.registerAfterRender(this._afterRender);
  54747. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54748. this._worker = new Worker(workerUrl);
  54749. this._worker.onmessage = this._onMessageFromWorker;
  54750. var message = {
  54751. payload: {},
  54752. taskType: WorkerTaskType.INIT
  54753. };
  54754. this._worker.postMessage(message);
  54755. };
  54756. CollisionCoordinatorWorker.prototype.destroy = function () {
  54757. this._scene.unregisterAfterRender(this._afterRender);
  54758. this._worker.terminate();
  54759. };
  54760. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54761. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54762. this.onMeshUpdated(mesh);
  54763. };
  54764. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54765. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54766. };
  54767. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54768. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54769. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54770. this.onGeometryUpdated(geometry);
  54771. };
  54772. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54773. this._toRemoveGeometryArray.push(geometry.id);
  54774. };
  54775. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54776. var submeshes = [];
  54777. if (mesh.subMeshes) {
  54778. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54779. var boundingInfo = sm.getBoundingInfo();
  54780. return {
  54781. position: idx,
  54782. verticesStart: sm.verticesStart,
  54783. verticesCount: sm.verticesCount,
  54784. indexStart: sm.indexStart,
  54785. indexCount: sm.indexCount,
  54786. hasMaterial: !!sm.getMaterial(),
  54787. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54788. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54789. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54790. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54791. };
  54792. });
  54793. }
  54794. var geometryId = null;
  54795. if (mesh instanceof BABYLON.Mesh) {
  54796. var geometry = mesh.geometry;
  54797. geometryId = geometry ? geometry.id : null;
  54798. }
  54799. else if (mesh instanceof BABYLON.InstancedMesh) {
  54800. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54801. geometryId = geometry ? geometry.id : null;
  54802. }
  54803. var boundingInfo = mesh.getBoundingInfo();
  54804. return {
  54805. uniqueId: mesh.uniqueId,
  54806. id: mesh.id,
  54807. name: mesh.name,
  54808. geometryId: geometryId,
  54809. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54810. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54811. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54812. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54813. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54814. subMeshes: submeshes,
  54815. checkCollisions: mesh.checkCollisions
  54816. };
  54817. };
  54818. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54819. return {
  54820. id: geometry.id,
  54821. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54822. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54823. indices: new Uint32Array(geometry.getIndices() || []),
  54824. };
  54825. };
  54826. return CollisionCoordinatorWorker;
  54827. }());
  54828. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54829. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54830. function CollisionCoordinatorLegacy() {
  54831. this._scaledPosition = BABYLON.Vector3.Zero();
  54832. this._scaledVelocity = BABYLON.Vector3.Zero();
  54833. this._finalPosition = BABYLON.Vector3.Zero();
  54834. }
  54835. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54836. position.divideToRef(collider._radius, this._scaledPosition);
  54837. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54838. collider.collidedMesh = null;
  54839. collider._retry = 0;
  54840. collider._initialVelocity = this._scaledVelocity;
  54841. collider._initialPosition = this._scaledPosition;
  54842. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54843. this._finalPosition.multiplyInPlace(collider._radius);
  54844. //run the callback
  54845. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54846. };
  54847. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54848. this._scene = scene;
  54849. };
  54850. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54851. //Legacy need no destruction method.
  54852. };
  54853. //No update in legacy mode
  54854. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54855. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54856. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54857. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54858. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54859. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54860. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54861. if (excludedMesh === void 0) { excludedMesh = null; }
  54862. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54863. if (collider._retry >= maximumRetry) {
  54864. finalPosition.copyFrom(position);
  54865. return;
  54866. }
  54867. // Check if this is a mesh else camera or -1
  54868. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54869. collider._initialize(position, velocity, closeDistance);
  54870. // Check all meshes
  54871. for (var index = 0; index < this._scene.meshes.length; index++) {
  54872. var mesh = this._scene.meshes[index];
  54873. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54874. mesh._checkCollision(collider);
  54875. }
  54876. }
  54877. if (!collider.collisionFound) {
  54878. position.addToRef(velocity, finalPosition);
  54879. return;
  54880. }
  54881. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54882. collider._getResponse(position, velocity);
  54883. }
  54884. if (velocity.length() <= closeDistance) {
  54885. finalPosition.copyFrom(position);
  54886. return;
  54887. }
  54888. collider._retry++;
  54889. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54890. };
  54891. return CollisionCoordinatorLegacy;
  54892. }());
  54893. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54894. })(BABYLON || (BABYLON = {}));
  54895. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54896. var BABYLON;
  54897. (function (BABYLON) {
  54898. /**
  54899. * A particle represents one of the element emitted by a particle system.
  54900. * This is mainly define by its coordinates, direction, velocity and age.
  54901. */
  54902. var Particle = /** @class */ (function () {
  54903. /**
  54904. * Creates a new instance Particle
  54905. * @param particleSystem the particle system the particle belongs to
  54906. */
  54907. function Particle(
  54908. /**
  54909. * particleSystem the particle system the particle belongs to.
  54910. */
  54911. particleSystem) {
  54912. this.particleSystem = particleSystem;
  54913. /**
  54914. * The world position of the particle in the scene.
  54915. */
  54916. this.position = BABYLON.Vector3.Zero();
  54917. /**
  54918. * The world direction of the particle in the scene.
  54919. */
  54920. this.direction = BABYLON.Vector3.Zero();
  54921. /**
  54922. * The color of the particle.
  54923. */
  54924. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54925. /**
  54926. * The color change of the particle per step.
  54927. */
  54928. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54929. /**
  54930. * Defines how long will the life of the particle be.
  54931. */
  54932. this.lifeTime = 1.0;
  54933. /**
  54934. * The current age of the particle.
  54935. */
  54936. this.age = 0;
  54937. /**
  54938. * The current size of the particle.
  54939. */
  54940. this.size = 0;
  54941. /**
  54942. * The current scale of the particle.
  54943. */
  54944. this.scale = new BABYLON.Vector2(1, 1);
  54945. /**
  54946. * The current angle of the particle.
  54947. */
  54948. this.angle = 0;
  54949. /**
  54950. * Defines how fast is the angle changing.
  54951. */
  54952. this.angularSpeed = 0;
  54953. /**
  54954. * Defines the cell index used by the particle to be rendered from a sprite.
  54955. */
  54956. this.cellIndex = 0;
  54957. /** @hidden */
  54958. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54959. /** @hidden */
  54960. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54961. /** @hidden */
  54962. this._currentSize1 = 0;
  54963. /** @hidden */
  54964. this._currentSize2 = 0;
  54965. /** @hidden */
  54966. this._currentAngularSpeed1 = 0;
  54967. /** @hidden */
  54968. this._currentAngularSpeed2 = 0;
  54969. if (!this.particleSystem.isAnimationSheetEnabled) {
  54970. return;
  54971. }
  54972. this.updateCellInfoFromSystem();
  54973. }
  54974. Particle.prototype.updateCellInfoFromSystem = function () {
  54975. this.cellIndex = this.particleSystem.startSpriteCellID;
  54976. };
  54977. /**
  54978. * Defines how the sprite cell index is updated for the particle
  54979. */
  54980. Particle.prototype.updateCellIndex = function () {
  54981. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54982. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54983. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54984. };
  54985. /**
  54986. * Copy the properties of particle to another one.
  54987. * @param other the particle to copy the information to.
  54988. */
  54989. Particle.prototype.copyTo = function (other) {
  54990. other.position.copyFrom(this.position);
  54991. if (this._initialDirection) {
  54992. if (other._initialDirection) {
  54993. other._initialDirection.copyFrom(this._initialDirection);
  54994. }
  54995. else {
  54996. other._initialDirection = this._initialDirection.clone();
  54997. }
  54998. }
  54999. else {
  55000. other._initialDirection = null;
  55001. }
  55002. other.direction.copyFrom(this.direction);
  55003. other.color.copyFrom(this.color);
  55004. other.colorStep.copyFrom(this.colorStep);
  55005. other.lifeTime = this.lifeTime;
  55006. other.age = this.age;
  55007. other.size = this.size;
  55008. other.scale.copyFrom(this.scale);
  55009. other.angle = this.angle;
  55010. other.angularSpeed = this.angularSpeed;
  55011. other.particleSystem = this.particleSystem;
  55012. other.cellIndex = this.cellIndex;
  55013. if (this._currentColorGradient) {
  55014. other._currentColorGradient = this._currentColorGradient;
  55015. other._currentColor1.copyFrom(this._currentColor1);
  55016. other._currentColor2.copyFrom(this._currentColor2);
  55017. }
  55018. if (this._currentSizeGradient) {
  55019. other._currentSizeGradient = this._currentSizeGradient;
  55020. other._currentSize1 = this._currentSize1;
  55021. other._currentSize2 = this._currentSize2;
  55022. }
  55023. if (this._currentAngularSpeedGradient) {
  55024. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55025. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55026. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55027. }
  55028. if (this.particleSystem.isAnimationSheetEnabled) {
  55029. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55030. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55031. }
  55032. };
  55033. return Particle;
  55034. }());
  55035. BABYLON.Particle = Particle;
  55036. })(BABYLON || (BABYLON = {}));
  55037. //# sourceMappingURL=babylon.particle.js.map
  55038. var BABYLON;
  55039. (function (BABYLON) {
  55040. /**
  55041. * This represents a particle system in Babylon.
  55042. * 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.
  55043. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55044. * @example https://doc.babylonjs.com/babylon101/particles
  55045. */
  55046. var ParticleSystem = /** @class */ (function () {
  55047. /**
  55048. * Instantiates a particle system.
  55049. * 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.
  55050. * @param name The name of the particle system
  55051. * @param capacity The max number of particles alive at the same time
  55052. * @param scene The scene the particle system belongs to
  55053. * @param customEffect a custom effect used to change the way particles are rendered by default
  55054. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55055. * @param epsilon Offset used to render the particles
  55056. */
  55057. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55058. if (customEffect === void 0) { customEffect = null; }
  55059. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55060. if (epsilon === void 0) { epsilon = 0.01; }
  55061. var _this = this;
  55062. /**
  55063. * List of animations used by the particle system.
  55064. */
  55065. this.animations = [];
  55066. /**
  55067. * The rendering group used by the Particle system to chose when to render.
  55068. */
  55069. this.renderingGroupId = 0;
  55070. /**
  55071. * The emitter represents the Mesh or position we are attaching the particle system to.
  55072. */
  55073. this.emitter = null;
  55074. /**
  55075. * The maximum number of particles to emit per frame
  55076. */
  55077. this.emitRate = 10;
  55078. /**
  55079. * If you want to launch only a few particles at once, that can be done, as well.
  55080. */
  55081. this.manualEmitCount = -1;
  55082. /**
  55083. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55084. */
  55085. this.updateSpeed = 0.01;
  55086. /**
  55087. * The amount of time the particle system is running (depends of the overall update speed).
  55088. */
  55089. this.targetStopDuration = 0;
  55090. /**
  55091. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55092. */
  55093. this.disposeOnStop = false;
  55094. /**
  55095. * Minimum power of emitting particles.
  55096. */
  55097. this.minEmitPower = 1;
  55098. /**
  55099. * Maximum power of emitting particles.
  55100. */
  55101. this.maxEmitPower = 1;
  55102. /**
  55103. * Minimum life time of emitting particles.
  55104. */
  55105. this.minLifeTime = 1;
  55106. /**
  55107. * Maximum life time of emitting particles.
  55108. */
  55109. this.maxLifeTime = 1;
  55110. /**
  55111. * Minimum Size of emitting particles.
  55112. */
  55113. this.minSize = 1;
  55114. /**
  55115. * Maximum Size of emitting particles.
  55116. */
  55117. this.maxSize = 1;
  55118. /**
  55119. * Minimum scale of emitting particles on X axis.
  55120. */
  55121. this.minScaleX = 1;
  55122. /**
  55123. * Maximum scale of emitting particles on X axis.
  55124. */
  55125. this.maxScaleX = 1;
  55126. /**
  55127. * Minimum scale of emitting particles on Y axis.
  55128. */
  55129. this.minScaleY = 1;
  55130. /**
  55131. * Maximum scale of emitting particles on Y axis.
  55132. */
  55133. this.maxScaleY = 1;
  55134. /**
  55135. * Gets or sets the minimal initial rotation in radians.
  55136. */
  55137. this.minInitialRotation = 0;
  55138. /**
  55139. * Gets or sets the maximal initial rotation in radians.
  55140. */
  55141. this.maxInitialRotation = 0;
  55142. /**
  55143. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55144. */
  55145. this.minAngularSpeed = 0;
  55146. /**
  55147. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55148. */
  55149. this.maxAngularSpeed = 0;
  55150. /**
  55151. * The layer mask we are rendering the particles through.
  55152. */
  55153. this.layerMask = 0x0FFFFFFF;
  55154. /**
  55155. * This can help using your own shader to render the particle system.
  55156. * The according effect will be created
  55157. */
  55158. this.customShader = null;
  55159. /**
  55160. * By default particle system starts as soon as they are created. This prevents the
  55161. * automatic start to happen and let you decide when to start emitting particles.
  55162. */
  55163. this.preventAutoStart = false;
  55164. /**
  55165. * Callback triggered when the particle animation is ending.
  55166. */
  55167. this.onAnimationEnd = null;
  55168. /**
  55169. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55170. */
  55171. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55172. /**
  55173. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55174. * to override the particles.
  55175. */
  55176. this.forceDepthWrite = false;
  55177. /**
  55178. * You can use gravity if you want to give an orientation to your particles.
  55179. */
  55180. this.gravity = BABYLON.Vector3.Zero();
  55181. this._colorGradients = null;
  55182. this._sizeGradients = null;
  55183. this._lifeTimeGradients = null;
  55184. this._angularSpeedGradients = null;
  55185. /**
  55186. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55187. */
  55188. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55189. /**
  55190. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55191. */
  55192. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55193. /**
  55194. * Color the particle will have at the end of its lifetime
  55195. */
  55196. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55197. /**
  55198. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55199. */
  55200. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55201. /**
  55202. * 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)
  55203. */
  55204. this.spriteCellChangeSpeed = 1;
  55205. /**
  55206. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55207. */
  55208. this.startSpriteCellID = 0;
  55209. /**
  55210. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55211. */
  55212. this.endSpriteCellID = 0;
  55213. /**
  55214. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55215. */
  55216. this.spriteCellWidth = 0;
  55217. /**
  55218. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55219. */
  55220. this.spriteCellHeight = 0;
  55221. /** 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 */
  55222. this.preWarmCycles = 0;
  55223. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55224. this.preWarmStepOffset = 1;
  55225. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55226. this.translationPivot = new BABYLON.Vector2(0, 0);
  55227. /**
  55228. * An event triggered when the system is disposed
  55229. */
  55230. this.onDisposeObservable = new BABYLON.Observable();
  55231. /**
  55232. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55233. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55234. */
  55235. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55236. this._particles = new Array();
  55237. this._stockParticles = new Array();
  55238. this._newPartsExcess = 0;
  55239. this._vertexBuffers = {};
  55240. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55241. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55242. this._scaledDirection = BABYLON.Vector3.Zero();
  55243. this._scaledGravity = BABYLON.Vector3.Zero();
  55244. this._currentRenderId = -1;
  55245. this._useInstancing = false;
  55246. this._started = false;
  55247. this._stopped = false;
  55248. this._actualFrame = 0;
  55249. this._isBillboardBased = true;
  55250. // start of sub system methods
  55251. /**
  55252. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55253. * Its lifetime will start back at 0.
  55254. */
  55255. this.recycleParticle = function (particle) {
  55256. var lastParticle = _this._particles.pop();
  55257. if (lastParticle !== particle) {
  55258. lastParticle.copyTo(particle);
  55259. }
  55260. _this._stockParticles.push(lastParticle);
  55261. };
  55262. this._createParticle = function () {
  55263. var particle;
  55264. if (_this._stockParticles.length !== 0) {
  55265. particle = _this._stockParticles.pop();
  55266. particle.age = 0;
  55267. particle._currentColorGradient = null;
  55268. particle.cellIndex = _this.startSpriteCellID;
  55269. }
  55270. else {
  55271. particle = new BABYLON.Particle(_this);
  55272. }
  55273. return particle;
  55274. };
  55275. this._emitFromParticle = function (particle) {
  55276. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55277. return;
  55278. }
  55279. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55280. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55281. subSystem._rootParticleSystem = _this;
  55282. _this.activeSubSystems.push(subSystem);
  55283. subSystem.start();
  55284. };
  55285. this.id = name;
  55286. this.name = name;
  55287. this._capacity = capacity;
  55288. this._epsilon = epsilon;
  55289. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55290. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55291. this._customEffect = customEffect;
  55292. scene.particleSystems.push(this);
  55293. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55294. this._createIndexBuffer();
  55295. this._createVertexBuffers();
  55296. // Default emitter type
  55297. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55298. this.updateFunction = function (particles) {
  55299. for (var index = 0; index < particles.length; index++) {
  55300. var particle = particles[index];
  55301. particle.age += _this._scaledUpdateSpeed;
  55302. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55303. _this._emitFromParticle(particle);
  55304. _this.recycleParticle(particle);
  55305. index--;
  55306. continue;
  55307. }
  55308. else {
  55309. var ratio = particle.age / particle.lifeTime;
  55310. // Color
  55311. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55312. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55313. if (currentGradient !== particle._currentColorGradient) {
  55314. particle._currentColor1.copyFrom(particle._currentColor2);
  55315. nextGradient.getColorToRef(particle._currentColor2);
  55316. particle._currentColorGradient = currentGradient;
  55317. }
  55318. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55319. });
  55320. }
  55321. else {
  55322. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55323. particle.color.addInPlace(_this._scaledColorStep);
  55324. if (particle.color.a < 0) {
  55325. particle.color.a = 0;
  55326. }
  55327. }
  55328. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55329. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55330. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55331. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55332. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55333. particle._currentAngularSpeedGradient = currentGradient;
  55334. }
  55335. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55336. });
  55337. }
  55338. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55339. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55340. particle.position.addInPlace(_this._scaledDirection);
  55341. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55342. particle.direction.addInPlace(_this._scaledGravity);
  55343. // Size
  55344. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55345. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55346. if (currentGradient !== particle._currentSizeGradient) {
  55347. particle._currentSize1 = particle._currentSize2;
  55348. particle._currentSize2 = nextGradient.getFactor();
  55349. particle._currentSizeGradient = currentGradient;
  55350. }
  55351. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55352. });
  55353. }
  55354. if (_this._isAnimationSheetEnabled) {
  55355. particle.updateCellIndex();
  55356. }
  55357. }
  55358. }
  55359. };
  55360. }
  55361. /**
  55362. * Gets the current list of color gradients.
  55363. * You must use addColorGradient and removeColorGradient to udpate this list
  55364. * @returns the list of color gradients
  55365. */
  55366. ParticleSystem.prototype.getColorGradients = function () {
  55367. return this._colorGradients;
  55368. };
  55369. /**
  55370. * Gets the current list of size gradients.
  55371. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55372. * @returns the list of size gradients
  55373. */
  55374. ParticleSystem.prototype.getSizeGradients = function () {
  55375. return this._sizeGradients;
  55376. };
  55377. /**
  55378. * Gets the current list of life time gradients.
  55379. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55380. * @returns the list of life time gradients
  55381. */
  55382. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55383. return this._lifeTimeGradients;
  55384. };
  55385. /**
  55386. * Gets the current list of angular speed gradients.
  55387. * You must use addAngularSpeedGradient and removeAngularGradient to udpate this list
  55388. * @returns the list of angular speed gradients
  55389. */
  55390. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55391. return this._angularSpeedGradients;
  55392. };
  55393. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55394. /**
  55395. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55396. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55397. */
  55398. get: function () {
  55399. if (this.particleEmitterType.direction1) {
  55400. return this.particleEmitterType.direction1;
  55401. }
  55402. return BABYLON.Vector3.Zero();
  55403. },
  55404. set: function (value) {
  55405. if (this.particleEmitterType.direction1) {
  55406. this.particleEmitterType.direction1 = value;
  55407. }
  55408. },
  55409. enumerable: true,
  55410. configurable: true
  55411. });
  55412. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55413. /**
  55414. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55415. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55416. */
  55417. get: function () {
  55418. if (this.particleEmitterType.direction2) {
  55419. return this.particleEmitterType.direction2;
  55420. }
  55421. return BABYLON.Vector3.Zero();
  55422. },
  55423. set: function (value) {
  55424. if (this.particleEmitterType.direction2) {
  55425. this.particleEmitterType.direction2 = value;
  55426. }
  55427. },
  55428. enumerable: true,
  55429. configurable: true
  55430. });
  55431. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55432. /**
  55433. * 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.
  55434. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55435. */
  55436. get: function () {
  55437. if (this.particleEmitterType.minEmitBox) {
  55438. return this.particleEmitterType.minEmitBox;
  55439. }
  55440. return BABYLON.Vector3.Zero();
  55441. },
  55442. set: function (value) {
  55443. if (this.particleEmitterType.minEmitBox) {
  55444. this.particleEmitterType.minEmitBox = value;
  55445. }
  55446. },
  55447. enumerable: true,
  55448. configurable: true
  55449. });
  55450. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55451. /**
  55452. * 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.
  55453. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55454. */
  55455. get: function () {
  55456. if (this.particleEmitterType.maxEmitBox) {
  55457. return this.particleEmitterType.maxEmitBox;
  55458. }
  55459. return BABYLON.Vector3.Zero();
  55460. },
  55461. set: function (value) {
  55462. if (this.particleEmitterType.maxEmitBox) {
  55463. this.particleEmitterType.maxEmitBox = value;
  55464. }
  55465. },
  55466. enumerable: true,
  55467. configurable: true
  55468. });
  55469. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55470. /**
  55471. * Sets a callback that will be triggered when the system is disposed
  55472. */
  55473. set: function (callback) {
  55474. if (this._onDisposeObserver) {
  55475. this.onDisposeObservable.remove(this._onDisposeObserver);
  55476. }
  55477. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55478. },
  55479. enumerable: true,
  55480. configurable: true
  55481. });
  55482. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55483. /**
  55484. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55485. */
  55486. get: function () {
  55487. return this._isAnimationSheetEnabled;
  55488. },
  55489. enumerable: true,
  55490. configurable: true
  55491. });
  55492. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55493. /**
  55494. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55495. */
  55496. get: function () {
  55497. return this._isBillboardBased;
  55498. },
  55499. set: function (value) {
  55500. if (this._isBillboardBased === value) {
  55501. return;
  55502. }
  55503. this._isBillboardBased = value;
  55504. this._resetEffect();
  55505. },
  55506. enumerable: true,
  55507. configurable: true
  55508. });
  55509. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55510. //end of Sub-emitter
  55511. /**
  55512. * Gets the current list of active particles
  55513. */
  55514. get: function () {
  55515. return this._particles;
  55516. },
  55517. enumerable: true,
  55518. configurable: true
  55519. });
  55520. /**
  55521. * Returns the string "ParticleSystem"
  55522. * @returns a string containing the class name
  55523. */
  55524. ParticleSystem.prototype.getClassName = function () {
  55525. return "ParticleSystem";
  55526. };
  55527. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55528. var newGradient = new BABYLON.FactorGradient();
  55529. newGradient.gradient = gradient;
  55530. newGradient.factor1 = factor;
  55531. newGradient.factor2 = factor2;
  55532. factorGradients.push(newGradient);
  55533. factorGradients.sort(function (a, b) {
  55534. if (a.gradient < b.gradient) {
  55535. return -1;
  55536. }
  55537. else if (a.gradient > b.gradient) {
  55538. return 1;
  55539. }
  55540. return 0;
  55541. });
  55542. };
  55543. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55544. if (!factorGradients) {
  55545. return;
  55546. }
  55547. var index = 0;
  55548. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55549. var factorGradient = factorGradients_1[_i];
  55550. if (factorGradient.gradient === gradient) {
  55551. factorGradients.splice(index, 1);
  55552. break;
  55553. }
  55554. index++;
  55555. }
  55556. };
  55557. /**
  55558. * Adds a new life time gradient
  55559. * @param gradient defines the gradient to use (between 0 and 1)
  55560. * @param factor defines the life time factor to affect to the specified gradient
  55561. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55562. * @returns the current particle system
  55563. */
  55564. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55565. if (!this._lifeTimeGradients) {
  55566. this._lifeTimeGradients = [];
  55567. }
  55568. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55569. return this;
  55570. };
  55571. /**
  55572. * Remove a specific life time gradient
  55573. * @param gradient defines the gradient to remove
  55574. * @returns the current particle system
  55575. */
  55576. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55577. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55578. return this;
  55579. };
  55580. /**
  55581. * Adds a new size gradient
  55582. * @param gradient defines the gradient to use (between 0 and 1)
  55583. * @param factor defines the size factor to affect to the specified gradient
  55584. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55585. * @returns the current particle system
  55586. */
  55587. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55588. if (!this._sizeGradients) {
  55589. this._sizeGradients = [];
  55590. }
  55591. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55592. return this;
  55593. };
  55594. /**
  55595. * Remove a specific size gradient
  55596. * @param gradient defines the gradient to remove
  55597. * @returns the current particle system
  55598. */
  55599. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55600. this._removeFactorGradient(this._sizeGradients, gradient);
  55601. return this;
  55602. };
  55603. /**
  55604. * Adds a new angular speed gradient
  55605. * @param gradient defines the gradient to use (between 0 and 1)
  55606. * @param factor defines the size factor to affect to the specified gradient
  55607. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55608. * @returns the current particle system
  55609. */
  55610. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55611. if (!this._angularSpeedGradients) {
  55612. this._angularSpeedGradients = [];
  55613. }
  55614. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55615. return this;
  55616. };
  55617. /**
  55618. * Remove a specific angular speed gradient
  55619. * @param gradient defines the gradient to remove
  55620. * @returns the current particle system
  55621. */
  55622. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55623. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55624. return this;
  55625. };
  55626. /**
  55627. * Adds a new color gradient
  55628. * @param gradient defines the gradient to use (between 0 and 1)
  55629. * @param color defines the color to affect to the specified gradient
  55630. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55631. */
  55632. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55633. if (!this._colorGradients) {
  55634. this._colorGradients = [];
  55635. }
  55636. var colorGradient = new BABYLON.ColorGradient();
  55637. colorGradient.gradient = gradient;
  55638. colorGradient.color1 = color;
  55639. colorGradient.color2 = color2;
  55640. this._colorGradients.push(colorGradient);
  55641. this._colorGradients.sort(function (a, b) {
  55642. if (a.gradient < b.gradient) {
  55643. return -1;
  55644. }
  55645. else if (a.gradient > b.gradient) {
  55646. return 1;
  55647. }
  55648. return 0;
  55649. });
  55650. return this;
  55651. };
  55652. /**
  55653. * Remove a specific color gradient
  55654. * @param gradient defines the gradient to remove
  55655. */
  55656. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55657. if (!this._colorGradients) {
  55658. return this;
  55659. }
  55660. var index = 0;
  55661. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55662. var colorGradient = _a[_i];
  55663. if (colorGradient.gradient === gradient) {
  55664. this._colorGradients.splice(index, 1);
  55665. break;
  55666. }
  55667. index++;
  55668. }
  55669. return this;
  55670. };
  55671. ParticleSystem.prototype._resetEffect = function () {
  55672. if (this._vertexBuffer) {
  55673. this._vertexBuffer.dispose();
  55674. this._vertexBuffer = null;
  55675. }
  55676. if (this._spriteBuffer) {
  55677. this._spriteBuffer.dispose();
  55678. this._spriteBuffer = null;
  55679. }
  55680. this._createVertexBuffers();
  55681. };
  55682. ParticleSystem.prototype._createVertexBuffers = function () {
  55683. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55684. if (this._isAnimationSheetEnabled) {
  55685. this._vertexBufferSize += 1;
  55686. }
  55687. if (!this._isBillboardBased) {
  55688. this._vertexBufferSize += 3;
  55689. }
  55690. var engine = this._scene.getEngine();
  55691. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55692. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55693. var dataOffset = 0;
  55694. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55695. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55696. dataOffset += 3;
  55697. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55698. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55699. dataOffset += 4;
  55700. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55701. this._vertexBuffers["angle"] = options;
  55702. dataOffset += 1;
  55703. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55704. this._vertexBuffers["size"] = size;
  55705. dataOffset += 2;
  55706. if (this._isAnimationSheetEnabled) {
  55707. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55708. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55709. dataOffset += 1;
  55710. }
  55711. if (!this._isBillboardBased) {
  55712. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55713. this._vertexBuffers["direction"] = directionBuffer;
  55714. dataOffset += 3;
  55715. }
  55716. var offsets;
  55717. if (this._useInstancing) {
  55718. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55719. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55720. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55721. }
  55722. else {
  55723. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55724. dataOffset += 2;
  55725. }
  55726. this._vertexBuffers["offset"] = offsets;
  55727. };
  55728. ParticleSystem.prototype._createIndexBuffer = function () {
  55729. if (this._useInstancing) {
  55730. return;
  55731. }
  55732. var indices = [];
  55733. var index = 0;
  55734. for (var count = 0; count < this._capacity; count++) {
  55735. indices.push(index);
  55736. indices.push(index + 1);
  55737. indices.push(index + 2);
  55738. indices.push(index);
  55739. indices.push(index + 2);
  55740. indices.push(index + 3);
  55741. index += 4;
  55742. }
  55743. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55744. };
  55745. /**
  55746. * Gets the maximum number of particles active at the same time.
  55747. * @returns The max number of active particles.
  55748. */
  55749. ParticleSystem.prototype.getCapacity = function () {
  55750. return this._capacity;
  55751. };
  55752. /**
  55753. * Gets Wether there are still active particles in the system.
  55754. * @returns True if it is alive, otherwise false.
  55755. */
  55756. ParticleSystem.prototype.isAlive = function () {
  55757. return this._alive;
  55758. };
  55759. /**
  55760. * Gets Wether the system has been started.
  55761. * @returns True if it has been started, otherwise false.
  55762. */
  55763. ParticleSystem.prototype.isStarted = function () {
  55764. return this._started;
  55765. };
  55766. /**
  55767. * Starts the particle system and begins to emit.
  55768. */
  55769. ParticleSystem.prototype.start = function () {
  55770. this._started = true;
  55771. this._stopped = false;
  55772. this._actualFrame = 0;
  55773. if (this.subEmitters && this.subEmitters.length != 0) {
  55774. this.activeSubSystems = new Array();
  55775. }
  55776. if (this.preWarmCycles) {
  55777. for (var index = 0; index < this.preWarmCycles; index++) {
  55778. this.animate(true);
  55779. }
  55780. }
  55781. };
  55782. /**
  55783. * Stops the particle system.
  55784. * @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.
  55785. */
  55786. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55787. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55788. this._stopped = true;
  55789. if (stopSubEmitters) {
  55790. this._stopSubEmitters();
  55791. }
  55792. };
  55793. // animation sheet
  55794. /**
  55795. * Remove all active particles
  55796. */
  55797. ParticleSystem.prototype.reset = function () {
  55798. this._stockParticles = [];
  55799. this._particles = [];
  55800. };
  55801. /**
  55802. * @hidden (for internal use only)
  55803. */
  55804. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55805. var offset = index * this._vertexBufferSize;
  55806. this._vertexData[offset++] = particle.position.x;
  55807. this._vertexData[offset++] = particle.position.y;
  55808. this._vertexData[offset++] = particle.position.z;
  55809. this._vertexData[offset++] = particle.color.r;
  55810. this._vertexData[offset++] = particle.color.g;
  55811. this._vertexData[offset++] = particle.color.b;
  55812. this._vertexData[offset++] = particle.color.a;
  55813. this._vertexData[offset++] = particle.angle;
  55814. this._vertexData[offset++] = particle.scale.x * particle.size;
  55815. this._vertexData[offset++] = particle.scale.y * particle.size;
  55816. if (this._isAnimationSheetEnabled) {
  55817. this._vertexData[offset++] = particle.cellIndex;
  55818. }
  55819. if (!this._isBillboardBased) {
  55820. if (particle._initialDirection) {
  55821. this._vertexData[offset++] = particle._initialDirection.x;
  55822. this._vertexData[offset++] = particle._initialDirection.y;
  55823. this._vertexData[offset++] = particle._initialDirection.z;
  55824. }
  55825. else {
  55826. this._vertexData[offset++] = particle.direction.x;
  55827. this._vertexData[offset++] = particle.direction.y;
  55828. this._vertexData[offset++] = particle.direction.z;
  55829. }
  55830. }
  55831. if (!this._useInstancing) {
  55832. if (this._isAnimationSheetEnabled) {
  55833. if (offsetX === 0)
  55834. offsetX = this._epsilon;
  55835. else if (offsetX === 1)
  55836. offsetX = 1 - this._epsilon;
  55837. if (offsetY === 0)
  55838. offsetY = this._epsilon;
  55839. else if (offsetY === 1)
  55840. offsetY = 1 - this._epsilon;
  55841. }
  55842. this._vertexData[offset++] = offsetX;
  55843. this._vertexData[offset++] = offsetY;
  55844. }
  55845. };
  55846. ParticleSystem.prototype._stopSubEmitters = function () {
  55847. if (!this.activeSubSystems) {
  55848. return;
  55849. }
  55850. this.activeSubSystems.forEach(function (subSystem) {
  55851. subSystem.stop(true);
  55852. });
  55853. this.activeSubSystems = new Array();
  55854. };
  55855. ParticleSystem.prototype._removeFromRoot = function () {
  55856. if (!this._rootParticleSystem) {
  55857. return;
  55858. }
  55859. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55860. if (index !== -1) {
  55861. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55862. }
  55863. };
  55864. // End of sub system methods
  55865. ParticleSystem.prototype._update = function (newParticles) {
  55866. // Update current
  55867. this._alive = this._particles.length > 0;
  55868. this.updateFunction(this._particles);
  55869. // Add new ones
  55870. var worldMatrix;
  55871. if (this.emitter.position) {
  55872. var emitterMesh = this.emitter;
  55873. worldMatrix = emitterMesh.getWorldMatrix();
  55874. }
  55875. else {
  55876. var emitterPosition = this.emitter;
  55877. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55878. }
  55879. var particle;
  55880. var _loop_1 = function () {
  55881. if (this_1._particles.length === this_1._capacity) {
  55882. return "break";
  55883. }
  55884. particle = this_1._createParticle();
  55885. this_1._particles.push(particle);
  55886. // Emitter
  55887. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55888. if (this_1.startPositionFunction) {
  55889. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55890. }
  55891. else {
  55892. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55893. }
  55894. if (this_1.startDirectionFunction) {
  55895. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55896. }
  55897. else {
  55898. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55899. }
  55900. if (emitPower === 0) {
  55901. if (!particle._initialDirection) {
  55902. particle._initialDirection = particle.direction.clone();
  55903. }
  55904. else {
  55905. particle._initialDirection.copyFrom(particle.direction);
  55906. }
  55907. }
  55908. else {
  55909. particle._initialDirection = null;
  55910. }
  55911. particle.direction.scaleInPlace(emitPower);
  55912. // Life time
  55913. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55914. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55915. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55916. var factorGradient1 = currentGradient;
  55917. var factorGradient2 = nextGradient;
  55918. var lifeTime1 = factorGradient1.getFactor();
  55919. var lifeTime2 = factorGradient2.getFactor();
  55920. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55921. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55922. });
  55923. }
  55924. else {
  55925. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55926. }
  55927. // Size
  55928. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55929. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55930. }
  55931. else {
  55932. particle._currentSizeGradient = this_1._sizeGradients[0];
  55933. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55934. particle.size = particle._currentSize1;
  55935. if (this_1._sizeGradients.length > 1) {
  55936. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55937. }
  55938. else {
  55939. particle._currentSize2 = particle._currentSize1;
  55940. }
  55941. }
  55942. // Size and scale
  55943. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55944. // Angle
  55945. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55946. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55947. }
  55948. else {
  55949. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55950. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55951. particle._currentAngularSpeed1 = particle.angularSpeed;
  55952. if (this_1._angularSpeedGradients.length > 1) {
  55953. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55954. }
  55955. else {
  55956. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55957. }
  55958. }
  55959. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55960. // Color
  55961. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55962. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55963. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55964. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55965. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55966. }
  55967. else {
  55968. particle._currentColorGradient = this_1._colorGradients[0];
  55969. particle._currentColorGradient.getColorToRef(particle.color);
  55970. particle._currentColor1.copyFrom(particle.color);
  55971. if (this_1._colorGradients.length > 1) {
  55972. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55973. }
  55974. else {
  55975. particle._currentColor2.copyFrom(particle.color);
  55976. }
  55977. }
  55978. // Sheet
  55979. if (this_1._isAnimationSheetEnabled) {
  55980. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55981. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55982. }
  55983. };
  55984. var this_1 = this, step;
  55985. for (var index = 0; index < newParticles; index++) {
  55986. var state_1 = _loop_1();
  55987. if (state_1 === "break")
  55988. break;
  55989. }
  55990. };
  55991. /** @hidden */
  55992. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55993. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55994. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55995. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55996. if (isAnimationSheetEnabled) {
  55997. attributeNamesOrOptions.push("cellIndex");
  55998. }
  55999. if (!isBillboardBased) {
  56000. attributeNamesOrOptions.push("direction");
  56001. }
  56002. return attributeNamesOrOptions;
  56003. };
  56004. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56005. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56006. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  56007. if (isAnimationSheetEnabled) {
  56008. effectCreationOption.push("particlesInfos");
  56009. }
  56010. return effectCreationOption;
  56011. };
  56012. ParticleSystem.prototype._getEffect = function () {
  56013. if (this._customEffect) {
  56014. return this._customEffect;
  56015. }
  56016. ;
  56017. var defines = [];
  56018. if (this._scene.clipPlane) {
  56019. defines.push("#define CLIPPLANE");
  56020. }
  56021. if (this._isAnimationSheetEnabled) {
  56022. defines.push("#define ANIMATESHEET");
  56023. }
  56024. if (this._isBillboardBased) {
  56025. defines.push("#define BILLBOARD");
  56026. switch (this.billboardMode) {
  56027. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56028. defines.push("#define BILLBOARDY");
  56029. break;
  56030. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56031. default:
  56032. break;
  56033. }
  56034. }
  56035. // Effect
  56036. var join = defines.join("\n");
  56037. if (this._cachedDefines !== join) {
  56038. this._cachedDefines = join;
  56039. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56040. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56041. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56042. }
  56043. return this._effect;
  56044. };
  56045. /**
  56046. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56047. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56048. */
  56049. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56050. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56051. if (!this._started)
  56052. return;
  56053. if (!preWarmOnly) {
  56054. var effect = this._getEffect();
  56055. // Check
  56056. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56057. return;
  56058. if (this._currentRenderId === this._scene.getRenderId()) {
  56059. return;
  56060. }
  56061. this._currentRenderId = this._scene.getRenderId();
  56062. }
  56063. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56064. // determine the number of particles we need to create
  56065. var newParticles;
  56066. if (this.manualEmitCount > -1) {
  56067. newParticles = this.manualEmitCount;
  56068. this._newPartsExcess = 0;
  56069. this.manualEmitCount = 0;
  56070. }
  56071. else {
  56072. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56073. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56074. }
  56075. if (this._newPartsExcess > 1.0) {
  56076. newParticles += this._newPartsExcess >> 0;
  56077. this._newPartsExcess -= this._newPartsExcess >> 0;
  56078. }
  56079. this._alive = false;
  56080. if (!this._stopped) {
  56081. this._actualFrame += this._scaledUpdateSpeed;
  56082. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56083. this.stop();
  56084. }
  56085. else {
  56086. newParticles = 0;
  56087. }
  56088. this._update(newParticles);
  56089. // Stopped?
  56090. if (this._stopped) {
  56091. if (!this._alive) {
  56092. this._started = false;
  56093. if (this.onAnimationEnd) {
  56094. this.onAnimationEnd();
  56095. }
  56096. if (this.disposeOnStop) {
  56097. this._scene._toBeDisposed.push(this);
  56098. }
  56099. }
  56100. }
  56101. if (!preWarmOnly) {
  56102. // Update VBO
  56103. var offset = 0;
  56104. for (var index = 0; index < this._particles.length; index++) {
  56105. var particle = this._particles[index];
  56106. this._appendParticleVertices(offset, particle);
  56107. offset += this._useInstancing ? 1 : 4;
  56108. }
  56109. if (this._vertexBuffer) {
  56110. this._vertexBuffer.update(this._vertexData);
  56111. }
  56112. }
  56113. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56114. this.stop();
  56115. }
  56116. };
  56117. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56118. this._appendParticleVertex(offset++, particle, 0, 0);
  56119. if (!this._useInstancing) {
  56120. this._appendParticleVertex(offset++, particle, 1, 0);
  56121. this._appendParticleVertex(offset++, particle, 1, 1);
  56122. this._appendParticleVertex(offset++, particle, 0, 1);
  56123. }
  56124. };
  56125. /**
  56126. * Rebuilds the particle system.
  56127. */
  56128. ParticleSystem.prototype.rebuild = function () {
  56129. this._createIndexBuffer();
  56130. if (this._vertexBuffer) {
  56131. this._vertexBuffer._rebuild();
  56132. }
  56133. };
  56134. /**
  56135. * Is this system ready to be used/rendered
  56136. * @return true if the system is ready
  56137. */
  56138. ParticleSystem.prototype.isReady = function () {
  56139. var effect = this._getEffect();
  56140. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56141. return false;
  56142. }
  56143. return true;
  56144. };
  56145. /**
  56146. * Renders the particle system in its current state.
  56147. * @returns the current number of particles
  56148. */
  56149. ParticleSystem.prototype.render = function () {
  56150. var effect = this._getEffect();
  56151. // Check
  56152. if (!this.isReady() || !this._particles.length) {
  56153. return 0;
  56154. }
  56155. var engine = this._scene.getEngine();
  56156. // Render
  56157. engine.enableEffect(effect);
  56158. engine.setState(false);
  56159. var viewMatrix = this._scene.getViewMatrix();
  56160. effect.setTexture("diffuseSampler", this.particleTexture);
  56161. effect.setMatrix("view", viewMatrix);
  56162. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56163. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56164. var baseSize = this.particleTexture.getBaseSize();
  56165. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56166. }
  56167. effect.setVector2("translationPivot", this.translationPivot);
  56168. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56169. if (this._isBillboardBased) {
  56170. var camera = this._scene.activeCamera;
  56171. effect.setVector3("eyePosition", camera.globalPosition);
  56172. }
  56173. if (this._scene.clipPlane) {
  56174. var clipPlane = this._scene.clipPlane;
  56175. var invView = viewMatrix.clone();
  56176. invView.invert();
  56177. effect.setMatrix("invView", invView);
  56178. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56179. }
  56180. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56181. // Draw order
  56182. switch (this.blendMode) {
  56183. case ParticleSystem.BLENDMODE_ADD:
  56184. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56185. break;
  56186. case ParticleSystem.BLENDMODE_ONEONE:
  56187. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56188. break;
  56189. case ParticleSystem.BLENDMODE_STANDARD:
  56190. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56191. break;
  56192. }
  56193. if (this.forceDepthWrite) {
  56194. engine.setDepthWrite(true);
  56195. }
  56196. if (this._useInstancing) {
  56197. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56198. engine.unbindInstanceAttributes();
  56199. }
  56200. else {
  56201. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56202. }
  56203. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56204. return this._particles.length;
  56205. };
  56206. /**
  56207. * Disposes the particle system and free the associated resources
  56208. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56209. */
  56210. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56211. if (disposeTexture === void 0) { disposeTexture = true; }
  56212. if (this._vertexBuffer) {
  56213. this._vertexBuffer.dispose();
  56214. this._vertexBuffer = null;
  56215. }
  56216. if (this._spriteBuffer) {
  56217. this._spriteBuffer.dispose();
  56218. this._spriteBuffer = null;
  56219. }
  56220. if (this._indexBuffer) {
  56221. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56222. this._indexBuffer = null;
  56223. }
  56224. if (disposeTexture && this.particleTexture) {
  56225. this.particleTexture.dispose();
  56226. this.particleTexture = null;
  56227. }
  56228. this._removeFromRoot();
  56229. // Remove from scene
  56230. var index = this._scene.particleSystems.indexOf(this);
  56231. if (index > -1) {
  56232. this._scene.particleSystems.splice(index, 1);
  56233. }
  56234. // Callback
  56235. this.onDisposeObservable.notifyObservers(this);
  56236. this.onDisposeObservable.clear();
  56237. };
  56238. /**
  56239. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56240. * @param radius The radius of the sphere to emit from
  56241. * @returns the emitter
  56242. */
  56243. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56244. if (radius === void 0) { radius = 1; }
  56245. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56246. this.particleEmitterType = particleEmitter;
  56247. return particleEmitter;
  56248. };
  56249. /**
  56250. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56251. * @param radius The radius of the sphere to emit from
  56252. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56253. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56254. * @returns the emitter
  56255. */
  56256. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56257. if (radius === void 0) { radius = 1; }
  56258. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56259. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56260. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56261. this.particleEmitterType = particleEmitter;
  56262. return particleEmitter;
  56263. };
  56264. /**
  56265. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56266. * @param radius The radius of the cone to emit from
  56267. * @param angle The base angle of the cone
  56268. * @returns the emitter
  56269. */
  56270. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56271. if (radius === void 0) { radius = 1; }
  56272. if (angle === void 0) { angle = Math.PI / 4; }
  56273. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56274. this.particleEmitterType = particleEmitter;
  56275. return particleEmitter;
  56276. };
  56277. // 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.
  56278. /**
  56279. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56280. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56281. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56282. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56283. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56284. * @returns the emitter
  56285. */
  56286. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56287. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56288. this.particleEmitterType = particleEmitter;
  56289. this.direction1 = direction1;
  56290. this.direction2 = direction2;
  56291. this.minEmitBox = minEmitBox;
  56292. this.maxEmitBox = maxEmitBox;
  56293. return particleEmitter;
  56294. };
  56295. // Clone
  56296. /**
  56297. * Clones the particle system.
  56298. * @param name The name of the cloned object
  56299. * @param newEmitter The new emitter to use
  56300. * @returns the cloned particle system
  56301. */
  56302. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56303. var custom = null;
  56304. var program = null;
  56305. if (this.customShader != null) {
  56306. program = this.customShader;
  56307. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56308. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56309. }
  56310. else if (this._customEffect) {
  56311. custom = this._customEffect;
  56312. }
  56313. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56314. result.customShader = program;
  56315. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56316. if (newEmitter === undefined) {
  56317. newEmitter = this.emitter;
  56318. }
  56319. result.emitter = newEmitter;
  56320. if (this.particleTexture) {
  56321. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56322. }
  56323. if (!this.preventAutoStart) {
  56324. result.start();
  56325. }
  56326. return result;
  56327. };
  56328. /**
  56329. * Serializes the particle system to a JSON object.
  56330. * @returns the JSON object
  56331. */
  56332. ParticleSystem.prototype.serialize = function () {
  56333. var serializationObject = {};
  56334. ParticleSystem._Serialize(serializationObject, this);
  56335. serializationObject.textureMask = this.textureMask.asArray();
  56336. serializationObject.customShader = this.customShader;
  56337. serializationObject.preventAutoStart = this.preventAutoStart;
  56338. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56339. return serializationObject;
  56340. };
  56341. /** @hidden */
  56342. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56343. serializationObject.name = particleSystem.name;
  56344. serializationObject.id = particleSystem.id;
  56345. serializationObject.capacity = particleSystem.getCapacity();
  56346. // Emitter
  56347. if (particleSystem.emitter.position) {
  56348. var emitterMesh = particleSystem.emitter;
  56349. serializationObject.emitterId = emitterMesh.id;
  56350. }
  56351. else {
  56352. var emitterPosition = particleSystem.emitter;
  56353. serializationObject.emitter = emitterPosition.asArray();
  56354. }
  56355. // Emitter
  56356. if (particleSystem.particleEmitterType) {
  56357. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56358. }
  56359. if (particleSystem.particleTexture) {
  56360. serializationObject.textureName = particleSystem.particleTexture.name;
  56361. }
  56362. // Animations
  56363. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56364. // Particle system
  56365. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56366. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56367. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56368. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56369. serializationObject.minSize = particleSystem.minSize;
  56370. serializationObject.maxSize = particleSystem.maxSize;
  56371. serializationObject.minScaleX = particleSystem.minScaleX;
  56372. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56373. serializationObject.minScaleY = particleSystem.minScaleY;
  56374. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56375. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56376. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56377. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56378. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56379. serializationObject.emitRate = particleSystem.emitRate;
  56380. serializationObject.gravity = particleSystem.gravity.asArray();
  56381. serializationObject.color1 = particleSystem.color1.asArray();
  56382. serializationObject.color2 = particleSystem.color2.asArray();
  56383. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56384. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56385. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56386. serializationObject.blendMode = particleSystem.blendMode;
  56387. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56388. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56389. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56390. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56391. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56392. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56393. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56394. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56395. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56396. var colorGradients = particleSystem.getColorGradients();
  56397. if (colorGradients) {
  56398. serializationObject.colorGradients = [];
  56399. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56400. var colorGradient = colorGradients_1[_i];
  56401. var serializedGradient = {
  56402. gradient: colorGradient.gradient,
  56403. color1: colorGradient.color1.asArray()
  56404. };
  56405. if (colorGradient.color2) {
  56406. serializedGradient.color2 = colorGradient.color2.asArray();
  56407. }
  56408. serializationObject.colorGradients.push(serializedGradient);
  56409. }
  56410. }
  56411. var sizeGradients = particleSystem.getSizeGradients();
  56412. if (sizeGradients) {
  56413. serializationObject.sizeGradients = [];
  56414. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56415. var sizeGradient = sizeGradients_1[_a];
  56416. var serializedGradient = {
  56417. gradient: sizeGradient.gradient,
  56418. factor1: sizeGradient.factor1
  56419. };
  56420. if (sizeGradient.factor2 !== undefined) {
  56421. serializedGradient.factor2 = sizeGradient.factor2;
  56422. }
  56423. serializationObject.sizeGradients.push(serializedGradient);
  56424. }
  56425. }
  56426. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56427. if (angularSpeedGradients) {
  56428. serializationObject.angularSpeedGradients = [];
  56429. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56430. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56431. var serializedGradient = {
  56432. gradient: angularSpeedGradient.gradient,
  56433. factor1: angularSpeedGradient.factor1
  56434. };
  56435. if (angularSpeedGradient.factor2 !== undefined) {
  56436. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56437. }
  56438. serializationObject.angularSpeedGradients.push(serializedGradient);
  56439. }
  56440. }
  56441. };
  56442. /** @hidden */
  56443. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56444. // Texture
  56445. if (parsedParticleSystem.textureName) {
  56446. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56447. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56448. }
  56449. // Emitter
  56450. if (parsedParticleSystem.emitterId === undefined) {
  56451. particleSystem.emitter = BABYLON.Vector3.Zero();
  56452. }
  56453. else if (parsedParticleSystem.emitterId) {
  56454. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56455. }
  56456. else {
  56457. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56458. }
  56459. // Misc.
  56460. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56461. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56462. }
  56463. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56464. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56465. }
  56466. // Animations
  56467. if (parsedParticleSystem.animations) {
  56468. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56469. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56470. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56471. }
  56472. }
  56473. if (parsedParticleSystem.autoAnimate) {
  56474. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56475. }
  56476. // Particle system
  56477. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56478. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56479. particleSystem.minSize = parsedParticleSystem.minSize;
  56480. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56481. if (parsedParticleSystem.minScaleX) {
  56482. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56483. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56484. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56485. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56486. }
  56487. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56488. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56489. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56490. }
  56491. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56492. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56493. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56494. }
  56495. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56496. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56497. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56498. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56499. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56500. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56501. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56502. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56503. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56504. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56505. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56506. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56507. if (parsedParticleSystem.colorGradients) {
  56508. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56509. var colorGradient = _a[_i];
  56510. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56511. }
  56512. }
  56513. if (parsedParticleSystem.sizeGradients) {
  56514. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56515. var sizeGradient = _c[_b];
  56516. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56517. }
  56518. }
  56519. if (parsedParticleSystem.angularSpeedGradients) {
  56520. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56521. var angularSpeedGradient = _e[_d];
  56522. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56523. }
  56524. }
  56525. // Emitter
  56526. var emitterType;
  56527. if (parsedParticleSystem.particleEmitterType) {
  56528. switch (parsedParticleSystem.particleEmitterType.type) {
  56529. case "SphereParticleEmitter":
  56530. emitterType = new BABYLON.SphereParticleEmitter();
  56531. break;
  56532. case "SphereDirectedParticleEmitter":
  56533. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56534. break;
  56535. case "ConeEmitter":
  56536. case "ConeParticleEmitter":
  56537. emitterType = new BABYLON.ConeParticleEmitter();
  56538. break;
  56539. case "BoxEmitter":
  56540. case "BoxParticleEmitter":
  56541. default:
  56542. emitterType = new BABYLON.BoxParticleEmitter();
  56543. break;
  56544. }
  56545. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56546. }
  56547. else {
  56548. emitterType = new BABYLON.BoxParticleEmitter();
  56549. emitterType.parse(parsedParticleSystem);
  56550. }
  56551. particleSystem.particleEmitterType = emitterType;
  56552. // Animation sheet
  56553. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56554. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56555. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56556. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56557. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56558. };
  56559. /**
  56560. * Parses a JSON object to create a particle system.
  56561. * @param parsedParticleSystem The JSON object to parse
  56562. * @param scene The scene to create the particle system in
  56563. * @param rootUrl The root url to use to load external dependencies like texture
  56564. * @returns the Parsed particle system
  56565. */
  56566. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56567. var name = parsedParticleSystem.name;
  56568. var custom = null;
  56569. var program = null;
  56570. if (parsedParticleSystem.customShader) {
  56571. program = parsedParticleSystem.customShader;
  56572. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56573. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56574. }
  56575. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56576. particleSystem.customShader = program;
  56577. if (parsedParticleSystem.id) {
  56578. particleSystem.id = parsedParticleSystem.id;
  56579. }
  56580. // Auto start
  56581. if (parsedParticleSystem.preventAutoStart) {
  56582. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56583. }
  56584. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56585. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56586. if (!particleSystem.preventAutoStart) {
  56587. particleSystem.start();
  56588. }
  56589. return particleSystem;
  56590. };
  56591. /**
  56592. * Source color is added to the destination color without alpha affecting the result.
  56593. */
  56594. ParticleSystem.BLENDMODE_ONEONE = 0;
  56595. /**
  56596. * Blend current color and particle color using particle’s alpha.
  56597. */
  56598. ParticleSystem.BLENDMODE_STANDARD = 1;
  56599. /**
  56600. * Add current color and particle color multiplied by particle’s alpha.
  56601. */
  56602. ParticleSystem.BLENDMODE_ADD = 2;
  56603. return ParticleSystem;
  56604. }());
  56605. BABYLON.ParticleSystem = ParticleSystem;
  56606. })(BABYLON || (BABYLON = {}));
  56607. //# sourceMappingURL=babylon.particleSystem.js.map
  56608. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56609. var BABYLON;
  56610. (function (BABYLON) {
  56611. /**
  56612. * Particle emitter emitting particles from the inside of a box.
  56613. * It emits the particles randomly between 2 given directions.
  56614. */
  56615. var BoxParticleEmitter = /** @class */ (function () {
  56616. /**
  56617. * Creates a new instance BoxParticleEmitter
  56618. */
  56619. function BoxParticleEmitter() {
  56620. /**
  56621. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56622. */
  56623. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56624. /**
  56625. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56626. */
  56627. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56628. /**
  56629. * 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.
  56630. */
  56631. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56632. /**
  56633. * 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.
  56634. */
  56635. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56636. }
  56637. /**
  56638. * Called by the particle System when the direction is computed for the created particle.
  56639. * @param worldMatrix is the world matrix of the particle system
  56640. * @param directionToUpdate is the direction vector to update with the result
  56641. * @param particle is the particle we are computed the direction for
  56642. */
  56643. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56644. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56645. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56646. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56647. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56648. };
  56649. /**
  56650. * Called by the particle System when the position is computed for the created particle.
  56651. * @param worldMatrix is the world matrix of the particle system
  56652. * @param positionToUpdate is the position vector to update with the result
  56653. * @param particle is the particle we are computed the position for
  56654. */
  56655. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56656. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56657. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56658. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56659. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56660. };
  56661. /**
  56662. * Clones the current emitter and returns a copy of it
  56663. * @returns the new emitter
  56664. */
  56665. BoxParticleEmitter.prototype.clone = function () {
  56666. var newOne = new BoxParticleEmitter();
  56667. BABYLON.Tools.DeepCopy(this, newOne);
  56668. return newOne;
  56669. };
  56670. /**
  56671. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56672. * @param effect defines the update shader
  56673. */
  56674. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56675. effect.setVector3("direction1", this.direction1);
  56676. effect.setVector3("direction2", this.direction2);
  56677. effect.setVector3("minEmitBox", this.minEmitBox);
  56678. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56679. };
  56680. /**
  56681. * Returns a string to use to update the GPU particles update shader
  56682. * @returns a string containng the defines string
  56683. */
  56684. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56685. return "#define BOXEMITTER";
  56686. };
  56687. /**
  56688. * Returns the string "BoxParticleEmitter"
  56689. * @returns a string containing the class name
  56690. */
  56691. BoxParticleEmitter.prototype.getClassName = function () {
  56692. return "BoxParticleEmitter";
  56693. };
  56694. /**
  56695. * Serializes the particle system to a JSON object.
  56696. * @returns the JSON object
  56697. */
  56698. BoxParticleEmitter.prototype.serialize = function () {
  56699. var serializationObject = {};
  56700. serializationObject.type = this.getClassName();
  56701. serializationObject.direction1 = this.direction1.asArray();
  56702. serializationObject.direction2 = this.direction2.asArray();
  56703. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56704. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56705. return serializationObject;
  56706. };
  56707. /**
  56708. * Parse properties from a JSON object
  56709. * @param serializationObject defines the JSON object
  56710. */
  56711. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56712. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56713. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56714. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56715. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56716. };
  56717. return BoxParticleEmitter;
  56718. }());
  56719. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56720. })(BABYLON || (BABYLON = {}));
  56721. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56722. var BABYLON;
  56723. (function (BABYLON) {
  56724. /**
  56725. * Particle emitter emitting particles from the inside of a cone.
  56726. * It emits the particles alongside the cone volume from the base to the particle.
  56727. * The emission direction might be randomized.
  56728. */
  56729. var ConeParticleEmitter = /** @class */ (function () {
  56730. /**
  56731. * Creates a new instance ConeParticleEmitter
  56732. * @param radius the radius of the emission cone (1 by default)
  56733. * @param angles the cone base angle (PI by default)
  56734. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56735. */
  56736. function ConeParticleEmitter(radius, angle,
  56737. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56738. directionRandomizer) {
  56739. if (radius === void 0) { radius = 1; }
  56740. if (angle === void 0) { angle = Math.PI; }
  56741. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56742. this.directionRandomizer = directionRandomizer;
  56743. /**
  56744. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56745. */
  56746. this.radiusRange = 1;
  56747. /**
  56748. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56749. */
  56750. this.heightRange = 1;
  56751. this.angle = angle;
  56752. this.radius = radius;
  56753. }
  56754. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56755. /**
  56756. * Gets or sets the radius of the emission cone
  56757. */
  56758. get: function () {
  56759. return this._radius;
  56760. },
  56761. set: function (value) {
  56762. this._radius = value;
  56763. this._buildHeight();
  56764. },
  56765. enumerable: true,
  56766. configurable: true
  56767. });
  56768. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56769. /**
  56770. * Gets or sets the angle of the emission cone
  56771. */
  56772. get: function () {
  56773. return this._angle;
  56774. },
  56775. set: function (value) {
  56776. this._angle = value;
  56777. this._buildHeight();
  56778. },
  56779. enumerable: true,
  56780. configurable: true
  56781. });
  56782. ConeParticleEmitter.prototype._buildHeight = function () {
  56783. if (this._angle !== 0) {
  56784. this._height = this._radius / Math.tan(this._angle / 2);
  56785. }
  56786. else {
  56787. this._height = 1;
  56788. }
  56789. };
  56790. /**
  56791. * Called by the particle System when the direction is computed for the created particle.
  56792. * @param worldMatrix is the world matrix of the particle system
  56793. * @param directionToUpdate is the direction vector to update with the result
  56794. * @param particle is the particle we are computed the direction for
  56795. */
  56796. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56797. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56798. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56799. }
  56800. else {
  56801. // measure the direction Vector from the emitter to the particle.
  56802. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56803. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56804. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56805. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56806. direction.x += randX;
  56807. direction.y += randY;
  56808. direction.z += randZ;
  56809. direction.normalize();
  56810. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56811. }
  56812. };
  56813. /**
  56814. * Called by the particle System when the position is computed for the created particle.
  56815. * @param worldMatrix is the world matrix of the particle system
  56816. * @param positionToUpdate is the position vector to update with the result
  56817. * @param particle is the particle we are computed the position for
  56818. */
  56819. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56820. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56821. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56822. // Better distribution in a cone at normal angles.
  56823. h = 1 - h * h;
  56824. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56825. radius = radius * h;
  56826. var randX = radius * Math.sin(s);
  56827. var randZ = radius * Math.cos(s);
  56828. var randY = h * this._height;
  56829. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56830. };
  56831. /**
  56832. * Clones the current emitter and returns a copy of it
  56833. * @returns the new emitter
  56834. */
  56835. ConeParticleEmitter.prototype.clone = function () {
  56836. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56837. BABYLON.Tools.DeepCopy(this, newOne);
  56838. return newOne;
  56839. };
  56840. /**
  56841. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56842. * @param effect defines the update shader
  56843. */
  56844. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56845. effect.setFloat2("radius", this._radius, this.radiusRange);
  56846. effect.setFloat("coneAngle", this._angle);
  56847. effect.setFloat2("height", this._height, this.heightRange);
  56848. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56849. };
  56850. /**
  56851. * Returns a string to use to update the GPU particles update shader
  56852. * @returns a string containng the defines string
  56853. */
  56854. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56855. return "#define CONEEMITTER";
  56856. };
  56857. /**
  56858. * Returns the string "ConeParticleEmitter"
  56859. * @returns a string containing the class name
  56860. */
  56861. ConeParticleEmitter.prototype.getClassName = function () {
  56862. return "ConeParticleEmitter";
  56863. };
  56864. /**
  56865. * Serializes the particle system to a JSON object.
  56866. * @returns the JSON object
  56867. */
  56868. ConeParticleEmitter.prototype.serialize = function () {
  56869. var serializationObject = {};
  56870. serializationObject.type = this.getClassName();
  56871. serializationObject.radius = this._radius;
  56872. serializationObject.angle = this._angle;
  56873. serializationObject.directionRandomizer = this.directionRandomizer;
  56874. return serializationObject;
  56875. };
  56876. /**
  56877. * Parse properties from a JSON object
  56878. * @param serializationObject defines the JSON object
  56879. */
  56880. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56881. this.radius = serializationObject.radius;
  56882. this.angle = serializationObject.angle;
  56883. this.directionRandomizer = serializationObject.directionRandomizer;
  56884. };
  56885. return ConeParticleEmitter;
  56886. }());
  56887. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56888. })(BABYLON || (BABYLON = {}));
  56889. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56890. var BABYLON;
  56891. (function (BABYLON) {
  56892. /**
  56893. * Particle emitter emitting particles from the inside of a sphere.
  56894. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56895. */
  56896. var SphereParticleEmitter = /** @class */ (function () {
  56897. /**
  56898. * Creates a new instance SphereParticleEmitter
  56899. * @param radius the radius of the emission sphere (1 by default)
  56900. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56901. */
  56902. function SphereParticleEmitter(
  56903. /**
  56904. * The radius of the emission sphere.
  56905. */
  56906. radius,
  56907. /**
  56908. * How much to randomize the particle direction [0-1].
  56909. */
  56910. directionRandomizer) {
  56911. if (radius === void 0) { radius = 1; }
  56912. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56913. this.radius = radius;
  56914. this.directionRandomizer = directionRandomizer;
  56915. /**
  56916. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56917. */
  56918. this.radiusRange = 1;
  56919. }
  56920. /**
  56921. * Called by the particle System when the direction is computed for the created particle.
  56922. * @param worldMatrix is the world matrix of the particle system
  56923. * @param directionToUpdate is the direction vector to update with the result
  56924. * @param particle is the particle we are computed the direction for
  56925. */
  56926. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56927. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56928. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56929. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56930. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56931. direction.x += randX;
  56932. direction.y += randY;
  56933. direction.z += randZ;
  56934. direction.normalize();
  56935. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56936. };
  56937. /**
  56938. * Called by the particle System when the position is computed for the created particle.
  56939. * @param worldMatrix is the world matrix of the particle system
  56940. * @param positionToUpdate is the position vector to update with the result
  56941. * @param particle is the particle we are computed the position for
  56942. */
  56943. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56944. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56945. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56946. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56947. var theta = Math.acos(2 * v - 1);
  56948. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56949. var randY = randRadius * Math.cos(theta);
  56950. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56951. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56952. };
  56953. /**
  56954. * Clones the current emitter and returns a copy of it
  56955. * @returns the new emitter
  56956. */
  56957. SphereParticleEmitter.prototype.clone = function () {
  56958. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56959. BABYLON.Tools.DeepCopy(this, newOne);
  56960. return newOne;
  56961. };
  56962. /**
  56963. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56964. * @param effect defines the update shader
  56965. */
  56966. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56967. effect.setFloat("radius", this.radius);
  56968. effect.setFloat("radiusRange", this.radiusRange);
  56969. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56970. };
  56971. /**
  56972. * Returns a string to use to update the GPU particles update shader
  56973. * @returns a string containng the defines string
  56974. */
  56975. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56976. return "#define SPHEREEMITTER";
  56977. };
  56978. /**
  56979. * Returns the string "SphereParticleEmitter"
  56980. * @returns a string containing the class name
  56981. */
  56982. SphereParticleEmitter.prototype.getClassName = function () {
  56983. return "SphereParticleEmitter";
  56984. };
  56985. /**
  56986. * Serializes the particle system to a JSON object.
  56987. * @returns the JSON object
  56988. */
  56989. SphereParticleEmitter.prototype.serialize = function () {
  56990. var serializationObject = {};
  56991. serializationObject.type = this.getClassName();
  56992. serializationObject.radius = this.radius;
  56993. serializationObject.radiusRange = this.radiusRange;
  56994. serializationObject.directionRandomizer = this.directionRandomizer;
  56995. return serializationObject;
  56996. };
  56997. /**
  56998. * Parse properties from a JSON object
  56999. * @param serializationObject defines the JSON object
  57000. */
  57001. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57002. this.radius = serializationObject.radius;
  57003. this.radiusRange = serializationObject.radiusRange;
  57004. this.directionRandomizer = serializationObject.directionRandomizer;
  57005. };
  57006. return SphereParticleEmitter;
  57007. }());
  57008. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57009. /**
  57010. * Particle emitter emitting particles from the inside of a sphere.
  57011. * It emits the particles randomly between two vectors.
  57012. */
  57013. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57014. __extends(SphereDirectedParticleEmitter, _super);
  57015. /**
  57016. * Creates a new instance SphereDirectedParticleEmitter
  57017. * @param radius the radius of the emission sphere (1 by default)
  57018. * @param direction1 the min limit of the emission direction (up vector by default)
  57019. * @param direction2 the max limit of the emission direction (up vector by default)
  57020. */
  57021. function SphereDirectedParticleEmitter(radius,
  57022. /**
  57023. * The min limit of the emission direction.
  57024. */
  57025. direction1,
  57026. /**
  57027. * The max limit of the emission direction.
  57028. */
  57029. direction2) {
  57030. if (radius === void 0) { radius = 1; }
  57031. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57032. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57033. var _this = _super.call(this, radius) || this;
  57034. _this.direction1 = direction1;
  57035. _this.direction2 = direction2;
  57036. return _this;
  57037. }
  57038. /**
  57039. * Called by the particle System when the direction is computed for the created particle.
  57040. * @param worldMatrix is the world matrix of the particle system
  57041. * @param directionToUpdate is the direction vector to update with the result
  57042. * @param particle is the particle we are computed the direction for
  57043. */
  57044. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57045. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57046. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57047. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57048. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57049. };
  57050. /**
  57051. * Clones the current emitter and returns a copy of it
  57052. * @returns the new emitter
  57053. */
  57054. SphereDirectedParticleEmitter.prototype.clone = function () {
  57055. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57056. BABYLON.Tools.DeepCopy(this, newOne);
  57057. return newOne;
  57058. };
  57059. /**
  57060. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57061. * @param effect defines the update shader
  57062. */
  57063. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57064. effect.setFloat("radius", this.radius);
  57065. effect.setFloat("radiusRange", this.radiusRange);
  57066. effect.setVector3("direction1", this.direction1);
  57067. effect.setVector3("direction2", this.direction2);
  57068. };
  57069. /**
  57070. * Returns a string to use to update the GPU particles update shader
  57071. * @returns a string containng the defines string
  57072. */
  57073. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57074. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57075. };
  57076. /**
  57077. * Returns the string "SphereDirectedParticleEmitter"
  57078. * @returns a string containing the class name
  57079. */
  57080. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57081. return "SphereDirectedParticleEmitter";
  57082. };
  57083. /**
  57084. * Serializes the particle system to a JSON object.
  57085. * @returns the JSON object
  57086. */
  57087. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57088. var serializationObject = _super.prototype.serialize.call(this);
  57089. serializationObject.direction1 = this.direction1.asArray();
  57090. serializationObject.direction2 = this.direction2.asArray();
  57091. return serializationObject;
  57092. };
  57093. /**
  57094. * Parse properties from a JSON object
  57095. * @param serializationObject defines the JSON object
  57096. */
  57097. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57098. _super.prototype.parse.call(this, serializationObject);
  57099. this.direction1.copyFrom(serializationObject.direction1);
  57100. this.direction2.copyFrom(serializationObject.direction2);
  57101. };
  57102. return SphereDirectedParticleEmitter;
  57103. }(SphereParticleEmitter));
  57104. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57105. })(BABYLON || (BABYLON = {}));
  57106. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57107. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57108. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57109. s = arguments[i];
  57110. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57111. t[p] = s[p];
  57112. }
  57113. return t;
  57114. };
  57115. var BABYLON;
  57116. (function (BABYLON) {
  57117. /**
  57118. * This represents a GPU particle system in Babylon
  57119. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57120. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57121. */
  57122. var GPUParticleSystem = /** @class */ (function () {
  57123. /**
  57124. * Instantiates a GPU particle system.
  57125. * 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.
  57126. * @param name The name of the particle system
  57127. * @param options The options used to create the system
  57128. * @param scene The scene the particle system belongs to
  57129. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57130. */
  57131. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  57132. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57133. /**
  57134. * The emitter represents the Mesh or position we are attaching the particle system to.
  57135. */
  57136. this.emitter = null;
  57137. /**
  57138. * The rendering group used by the Particle system to chose when to render.
  57139. */
  57140. this.renderingGroupId = 0;
  57141. /**
  57142. * The layer mask we are rendering the particles through.
  57143. */
  57144. this.layerMask = 0x0FFFFFFF;
  57145. this._accumulatedCount = 0;
  57146. this._targetIndex = 0;
  57147. this._currentRenderId = -1;
  57148. this._started = false;
  57149. this._stopped = false;
  57150. this._timeDelta = 0;
  57151. this._attributesStrideSize = 21;
  57152. this._actualFrame = 0;
  57153. this._rawTextureWidth = 256;
  57154. /**
  57155. * List of animations used by the particle system.
  57156. */
  57157. this.animations = [];
  57158. /**
  57159. * An event triggered when the system is disposed.
  57160. */
  57161. this.onDisposeObservable = new BABYLON.Observable();
  57162. /**
  57163. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57164. */
  57165. this.updateSpeed = 0.01;
  57166. /**
  57167. * The amount of time the particle system is running (depends of the overall update speed).
  57168. */
  57169. this.targetStopDuration = 0;
  57170. /**
  57171. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57172. */
  57173. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57174. /**
  57175. * Minimum life time of emitting particles.
  57176. */
  57177. this.minLifeTime = 1;
  57178. /**
  57179. * Maximum life time of emitting particles.
  57180. */
  57181. this.maxLifeTime = 1;
  57182. /**
  57183. * Minimum Size of emitting particles.
  57184. */
  57185. this.minSize = 1;
  57186. /**
  57187. * Maximum Size of emitting particles.
  57188. */
  57189. this.maxSize = 1;
  57190. /**
  57191. * Minimum scale of emitting particles on X axis.
  57192. */
  57193. this.minScaleX = 1;
  57194. /**
  57195. * Maximum scale of emitting particles on X axis.
  57196. */
  57197. this.maxScaleX = 1;
  57198. /**
  57199. * Minimum scale of emitting particles on Y axis.
  57200. */
  57201. this.minScaleY = 1;
  57202. /**
  57203. * Maximum scale of emitting particles on Y axis.
  57204. */
  57205. this.maxScaleY = 1;
  57206. /**
  57207. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57208. */
  57209. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57210. /**
  57211. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57212. */
  57213. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57214. /**
  57215. * Color the particle will have at the end of its lifetime.
  57216. */
  57217. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57218. /**
  57219. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57220. */
  57221. this.emitRate = 100;
  57222. /**
  57223. * You can use gravity if you want to give an orientation to your particles.
  57224. */
  57225. this.gravity = BABYLON.Vector3.Zero();
  57226. /**
  57227. * Minimum power of emitting particles.
  57228. */
  57229. this.minEmitPower = 1;
  57230. /**
  57231. * Maximum power of emitting particles.
  57232. */
  57233. this.maxEmitPower = 1;
  57234. /**
  57235. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57236. */
  57237. this.minAngularSpeed = 0;
  57238. /**
  57239. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57240. */
  57241. this.maxAngularSpeed = 0;
  57242. /**
  57243. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57244. * to override the particles.
  57245. */
  57246. this.forceDepthWrite = false;
  57247. this._preWarmDone = false;
  57248. /** 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 */
  57249. this.preWarmCycles = 0;
  57250. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57251. this.preWarmStepOffset = 1;
  57252. /**
  57253. * Gets or sets the minimal initial rotation in radians.
  57254. */
  57255. this.minInitialRotation = 0;
  57256. /**
  57257. * Gets or sets the maximal initial rotation in radians.
  57258. */
  57259. this.maxInitialRotation = 0;
  57260. /**
  57261. * 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)
  57262. */
  57263. this.spriteCellChangeSpeed = 1;
  57264. /**
  57265. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57266. */
  57267. this.startSpriteCellID = 0;
  57268. /**
  57269. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57270. */
  57271. this.endSpriteCellID = 0;
  57272. /**
  57273. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57274. */
  57275. this.spriteCellWidth = 0;
  57276. /**
  57277. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57278. */
  57279. this.spriteCellHeight = 0;
  57280. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57281. this.translationPivot = new BABYLON.Vector2(0, 0);
  57282. /**
  57283. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57284. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  57285. */
  57286. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  57287. this._isBillboardBased = true;
  57288. this._colorGradients = null;
  57289. this._angularSpeedGradients = null;
  57290. this._sizeGradients = null;
  57291. this.id = name;
  57292. this.name = name;
  57293. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57294. this._engine = this._scene.getEngine();
  57295. if (!options.randomTextureSize) {
  57296. delete options.randomTextureSize;
  57297. }
  57298. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57299. var optionsAsNumber = options;
  57300. if (isFinite(optionsAsNumber)) {
  57301. fullOptions.capacity = optionsAsNumber;
  57302. }
  57303. this._capacity = fullOptions.capacity;
  57304. this._activeCount = fullOptions.capacity;
  57305. this._currentActiveCount = 0;
  57306. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57307. this._scene.particleSystems.push(this);
  57308. this._updateEffectOptions = {
  57309. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  57310. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57311. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57312. "angleRange", "radiusRange", "cellInfos"],
  57313. uniformBuffersNames: [],
  57314. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler"],
  57315. defines: "",
  57316. fallbacks: null,
  57317. onCompiled: null,
  57318. onError: null,
  57319. indexParameters: null,
  57320. maxSimultaneousLights: 0,
  57321. transformFeedbackVaryings: []
  57322. };
  57323. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57324. // Random data
  57325. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57326. var d = [];
  57327. for (var i = 0; i < maxTextureSize; ++i) {
  57328. d.push(Math.random());
  57329. d.push(Math.random());
  57330. d.push(Math.random());
  57331. d.push(Math.random());
  57332. }
  57333. 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);
  57334. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57335. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57336. d = [];
  57337. for (var i = 0; i < maxTextureSize; ++i) {
  57338. d.push(Math.random());
  57339. d.push(Math.random());
  57340. d.push(Math.random());
  57341. d.push(Math.random());
  57342. }
  57343. 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);
  57344. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57345. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57346. this._randomTextureSize = maxTextureSize;
  57347. }
  57348. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57349. /**
  57350. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57351. */
  57352. get: function () {
  57353. if (!BABYLON.Engine.LastCreatedEngine) {
  57354. return false;
  57355. }
  57356. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57357. },
  57358. enumerable: true,
  57359. configurable: true
  57360. });
  57361. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57362. /**
  57363. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57364. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57365. */
  57366. get: function () {
  57367. if (this.particleEmitterType.direction1) {
  57368. return this.particleEmitterType.direction1;
  57369. }
  57370. return BABYLON.Vector3.Zero();
  57371. },
  57372. set: function (value) {
  57373. if (this.particleEmitterType.direction1) {
  57374. this.particleEmitterType.direction1 = value;
  57375. }
  57376. },
  57377. enumerable: true,
  57378. configurable: true
  57379. });
  57380. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57381. /**
  57382. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57383. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57384. */
  57385. get: function () {
  57386. if (this.particleEmitterType.direction2) {
  57387. return this.particleEmitterType.direction2;
  57388. }
  57389. return BABYLON.Vector3.Zero();
  57390. },
  57391. set: function (value) {
  57392. if (this.particleEmitterType.direction2) {
  57393. this.particleEmitterType.direction2 = value;
  57394. }
  57395. },
  57396. enumerable: true,
  57397. configurable: true
  57398. });
  57399. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57400. /**
  57401. * 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.
  57402. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57403. */
  57404. get: function () {
  57405. if (this.particleEmitterType.minEmitBox) {
  57406. return this.particleEmitterType.minEmitBox;
  57407. }
  57408. return BABYLON.Vector3.Zero();
  57409. },
  57410. set: function (value) {
  57411. if (this.particleEmitterType.minEmitBox) {
  57412. this.particleEmitterType.minEmitBox = value;
  57413. }
  57414. },
  57415. enumerable: true,
  57416. configurable: true
  57417. });
  57418. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57419. /**
  57420. * 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.
  57421. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57422. */
  57423. get: function () {
  57424. if (this.particleEmitterType.maxEmitBox) {
  57425. return this.particleEmitterType.maxEmitBox;
  57426. }
  57427. return BABYLON.Vector3.Zero();
  57428. },
  57429. set: function (value) {
  57430. if (this.particleEmitterType.maxEmitBox) {
  57431. this.particleEmitterType.maxEmitBox = value;
  57432. }
  57433. },
  57434. enumerable: true,
  57435. configurable: true
  57436. });
  57437. /**
  57438. * Gets the maximum number of particles active at the same time.
  57439. * @returns The max number of active particles.
  57440. */
  57441. GPUParticleSystem.prototype.getCapacity = function () {
  57442. return this._capacity;
  57443. };
  57444. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57445. /**
  57446. * Gets or set the number of active particles
  57447. */
  57448. get: function () {
  57449. return this._activeCount;
  57450. },
  57451. set: function (value) {
  57452. this._activeCount = Math.min(value, this._capacity);
  57453. },
  57454. enumerable: true,
  57455. configurable: true
  57456. });
  57457. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  57458. /**
  57459. * Gets whether an animation sprite sheet is enabled or not on the particle system
  57460. */
  57461. get: function () {
  57462. return this._isAnimationSheetEnabled;
  57463. },
  57464. enumerable: true,
  57465. configurable: true
  57466. });
  57467. /**
  57468. * Is this system ready to be used/rendered
  57469. * @return true if the system is ready
  57470. */
  57471. GPUParticleSystem.prototype.isReady = function () {
  57472. if (!this._updateEffect) {
  57473. this._recreateUpdateEffect();
  57474. this._recreateRenderEffect();
  57475. return false;
  57476. }
  57477. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57478. return false;
  57479. }
  57480. return true;
  57481. };
  57482. /**
  57483. * Gets Wether the system has been started.
  57484. * @returns True if it has been started, otherwise false.
  57485. */
  57486. GPUParticleSystem.prototype.isStarted = function () {
  57487. return this._started;
  57488. };
  57489. /**
  57490. * Starts the particle system and begins to emit.
  57491. */
  57492. GPUParticleSystem.prototype.start = function () {
  57493. this._started = true;
  57494. this._stopped = false;
  57495. this._preWarmDone = false;
  57496. };
  57497. /**
  57498. * Stops the particle system.
  57499. */
  57500. GPUParticleSystem.prototype.stop = function () {
  57501. this._stopped = true;
  57502. };
  57503. /**
  57504. * Remove all active particles
  57505. */
  57506. GPUParticleSystem.prototype.reset = function () {
  57507. this._releaseBuffers();
  57508. this._releaseVAOs();
  57509. this._currentActiveCount = 0;
  57510. this._targetIndex = 0;
  57511. };
  57512. /**
  57513. * Returns the string "GPUParticleSystem"
  57514. * @returns a string containing the class name
  57515. */
  57516. GPUParticleSystem.prototype.getClassName = function () {
  57517. return "GPUParticleSystem";
  57518. };
  57519. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57520. /**
  57521. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57522. */
  57523. get: function () {
  57524. return this._isBillboardBased;
  57525. },
  57526. set: function (value) {
  57527. if (this._isBillboardBased === value) {
  57528. return;
  57529. }
  57530. this._isBillboardBased = value;
  57531. this._releaseBuffers();
  57532. },
  57533. enumerable: true,
  57534. configurable: true
  57535. });
  57536. /**
  57537. * Gets the current list of color gradients.
  57538. * You must use addColorGradient and removeColorGradient to udpate this list
  57539. * @returns the list of color gradients
  57540. */
  57541. GPUParticleSystem.prototype.getColorGradients = function () {
  57542. return this._colorGradients;
  57543. };
  57544. /**
  57545. * Gets the current list of size gradients.
  57546. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57547. * @returns the list of size gradients
  57548. */
  57549. GPUParticleSystem.prototype.getSizeGradients = function () {
  57550. return this._sizeGradients;
  57551. };
  57552. /**
  57553. * Gets the current list of angular speed gradients.
  57554. * You must use addAngularSpeedGradient and removeAngularGradient to udpate this list
  57555. * @returns the list of angular speed gradients
  57556. */
  57557. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  57558. return this._angularSpeedGradients;
  57559. };
  57560. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  57561. if (!gradients) {
  57562. return this;
  57563. }
  57564. var index = 0;
  57565. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57566. var valueGradient = gradients_1[_i];
  57567. if (valueGradient.gradient === gradient) {
  57568. gradients.splice(index, 1);
  57569. break;
  57570. }
  57571. index++;
  57572. }
  57573. if (texture) {
  57574. texture.dispose();
  57575. }
  57576. this._releaseBuffers();
  57577. return this;
  57578. };
  57579. /**
  57580. * Adds a new color gradient
  57581. * @param gradient defines the gradient to use (between 0 and 1)
  57582. * @param color defines the color to affect to the specified gradient
  57583. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57584. * @returns the current particle system
  57585. */
  57586. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57587. if (!this._colorGradients) {
  57588. this._colorGradients = [];
  57589. }
  57590. var colorGradient = new BABYLON.ColorGradient();
  57591. colorGradient.gradient = gradient;
  57592. colorGradient.color1 = color1;
  57593. this._colorGradients.push(colorGradient);
  57594. this._colorGradients.sort(function (a, b) {
  57595. if (a.gradient < b.gradient) {
  57596. return -1;
  57597. }
  57598. else if (a.gradient > b.gradient) {
  57599. return 1;
  57600. }
  57601. return 0;
  57602. });
  57603. if (this._colorGradientsTexture) {
  57604. this._colorGradientsTexture.dispose();
  57605. this._colorGradientsTexture = null;
  57606. }
  57607. this._releaseBuffers();
  57608. return this;
  57609. };
  57610. /**
  57611. * Remove a specific color gradient
  57612. * @param gradient defines the gradient to remove
  57613. * @returns the current particle system
  57614. */
  57615. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57616. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  57617. this._colorGradientsTexture = null;
  57618. return this;
  57619. };
  57620. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  57621. var valueGradient = new BABYLON.FactorGradient();
  57622. valueGradient.gradient = gradient;
  57623. valueGradient.factor1 = factor;
  57624. factorGradients.push(valueGradient);
  57625. factorGradients.sort(function (a, b) {
  57626. if (a.gradient < b.gradient) {
  57627. return -1;
  57628. }
  57629. else if (a.gradient > b.gradient) {
  57630. return 1;
  57631. }
  57632. return 0;
  57633. });
  57634. this._releaseBuffers();
  57635. };
  57636. /**
  57637. * Adds a new size gradient
  57638. * @param gradient defines the gradient to use (between 0 and 1)
  57639. * @param factor defines the size factor to affect to the specified gradient
  57640. * @returns the current particle system
  57641. */
  57642. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57643. if (!this._sizeGradients) {
  57644. this._sizeGradients = [];
  57645. }
  57646. this._addFactorGradient(this._sizeGradients, gradient, factor);
  57647. if (this._sizeGradientsTexture) {
  57648. this._sizeGradientsTexture.dispose();
  57649. this._sizeGradientsTexture = null;
  57650. }
  57651. this._releaseBuffers();
  57652. return this;
  57653. };
  57654. /**
  57655. * Remove a specific size gradient
  57656. * @param gradient defines the gradient to remove
  57657. * @returns the current particle system
  57658. */
  57659. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57660. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  57661. this._sizeGradientsTexture = null;
  57662. return this;
  57663. };
  57664. /**
  57665. * Adds a new angular speed gradient
  57666. * @param gradient defines the gradient to use (between 0 and 1)
  57667. * @param factor defines the size factor to affect to the specified gradient
  57668. * @returns the current particle system
  57669. */
  57670. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  57671. if (!this._angularSpeedGradients) {
  57672. this._angularSpeedGradients = [];
  57673. }
  57674. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  57675. if (this._angularSpeedGradientsTexture) {
  57676. this._angularSpeedGradientsTexture.dispose();
  57677. this._angularSpeedGradientsTexture = null;
  57678. }
  57679. this._releaseBuffers();
  57680. return this;
  57681. };
  57682. /**
  57683. * Remove a specific angular speed gradient
  57684. * @param gradient defines the gradient to remove
  57685. * @returns the current particle system
  57686. */
  57687. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57688. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  57689. this._angularSpeedGradientsTexture = null;
  57690. return this;
  57691. };
  57692. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57693. var updateVertexBuffers = {};
  57694. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57695. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57696. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57697. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57698. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57699. var offset = 12;
  57700. if (!this._colorGradientsTexture) {
  57701. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57702. offset += 4;
  57703. }
  57704. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57705. offset += 3;
  57706. if (!this._isBillboardBased) {
  57707. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57708. offset += 3;
  57709. }
  57710. if (this._angularSpeedGradientsTexture) {
  57711. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  57712. offset += 1;
  57713. }
  57714. else {
  57715. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57716. offset += 2;
  57717. }
  57718. if (this._isAnimationSheetEnabled) {
  57719. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  57720. offset += 1;
  57721. }
  57722. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57723. this._engine.bindArrayBuffer(null);
  57724. return vao;
  57725. };
  57726. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57727. var renderVertexBuffers = {};
  57728. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57729. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57730. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57731. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57732. var offset = 12;
  57733. if (!this._colorGradientsTexture) {
  57734. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57735. offset += 4;
  57736. }
  57737. offset += 3; // Direction
  57738. if (!this._isBillboardBased) {
  57739. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57740. offset += 3;
  57741. }
  57742. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  57743. if (this._angularSpeedGradientsTexture) {
  57744. offset++;
  57745. }
  57746. else {
  57747. offset += 2;
  57748. }
  57749. if (this._isAnimationSheetEnabled) {
  57750. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  57751. offset += 1;
  57752. }
  57753. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57754. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57755. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57756. this._engine.bindArrayBuffer(null);
  57757. return vao;
  57758. };
  57759. GPUParticleSystem.prototype._initialize = function (force) {
  57760. if (force === void 0) { force = false; }
  57761. if (this._buffer0 && !force) {
  57762. return;
  57763. }
  57764. var engine = this._scene.getEngine();
  57765. var data = new Array();
  57766. if (!this.isBillboardBased) {
  57767. this._attributesStrideSize += 3;
  57768. }
  57769. if (this._colorGradientsTexture) {
  57770. this._attributesStrideSize -= 4;
  57771. }
  57772. if (this._angularSpeedGradientsTexture) {
  57773. this._attributesStrideSize -= 1;
  57774. }
  57775. if (this._isAnimationSheetEnabled) {
  57776. this._attributesStrideSize += 1;
  57777. }
  57778. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57779. // position
  57780. data.push(0.0);
  57781. data.push(0.0);
  57782. data.push(0.0);
  57783. // Age and life
  57784. data.push(0.0); // create the particle as a dead one to create a new one at start
  57785. data.push(0.0);
  57786. // Seed
  57787. data.push(Math.random());
  57788. data.push(Math.random());
  57789. data.push(Math.random());
  57790. data.push(Math.random());
  57791. // Size
  57792. data.push(0.0);
  57793. data.push(0.0);
  57794. data.push(0.0);
  57795. if (!this._colorGradientsTexture) {
  57796. // color
  57797. data.push(0.0);
  57798. data.push(0.0);
  57799. data.push(0.0);
  57800. data.push(0.0);
  57801. }
  57802. // direction
  57803. data.push(0.0);
  57804. data.push(0.0);
  57805. data.push(0.0);
  57806. if (!this.isBillboardBased) {
  57807. // initialDirection
  57808. data.push(0.0);
  57809. data.push(0.0);
  57810. data.push(0.0);
  57811. }
  57812. // angle
  57813. data.push(0.0);
  57814. if (!this._angularSpeedGradientsTexture) {
  57815. data.push(0.0);
  57816. }
  57817. if (this._isAnimationSheetEnabled) {
  57818. data.push(0.0);
  57819. }
  57820. }
  57821. // Sprite data
  57822. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57823. -0.5, 0.5, 0, 1,
  57824. -0.5, -0.5, 0, 0,
  57825. 0.5, -0.5, 1, 0]);
  57826. // Buffers
  57827. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57828. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57829. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57830. // Update VAO
  57831. this._updateVAO = [];
  57832. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57833. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57834. // Render VAO
  57835. this._renderVAO = [];
  57836. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57837. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57838. // Links
  57839. this._sourceBuffer = this._buffer0;
  57840. this._targetBuffer = this._buffer1;
  57841. };
  57842. /** @hidden */
  57843. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57844. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57845. if (this._isBillboardBased) {
  57846. defines += "\n#define BILLBOARD";
  57847. }
  57848. if (this._colorGradientsTexture) {
  57849. defines += "\n#define COLORGRADIENTS";
  57850. }
  57851. if (this._sizeGradientsTexture) {
  57852. defines += "\n#define SIZEGRADIENTS";
  57853. }
  57854. if (this._angularSpeedGradientsTexture) {
  57855. defines += "\n#define ANGULARSPEEDGRADIENTS";
  57856. }
  57857. if (this.isAnimationSheetEnabled) {
  57858. defines += "\n#define ANIMATESHEET";
  57859. }
  57860. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57861. return;
  57862. }
  57863. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57864. if (!this._colorGradientsTexture) {
  57865. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57866. }
  57867. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57868. if (!this._isBillboardBased) {
  57869. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57870. }
  57871. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57872. if (this.isAnimationSheetEnabled) {
  57873. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  57874. }
  57875. this._updateEffectOptions.defines = defines;
  57876. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57877. };
  57878. /** @hidden */
  57879. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57880. var defines = "";
  57881. if (this._scene.clipPlane) {
  57882. defines = "\n#define CLIPPLANE";
  57883. }
  57884. if (this._isBillboardBased) {
  57885. defines += "\n#define BILLBOARD";
  57886. switch (this.billboardMode) {
  57887. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57888. defines += "\n#define BILLBOARDY";
  57889. break;
  57890. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57891. default:
  57892. break;
  57893. }
  57894. }
  57895. if (this._colorGradientsTexture) {
  57896. defines += "\n#define COLORGRADIENTS";
  57897. }
  57898. if (this.isAnimationSheetEnabled) {
  57899. defines += "\n#define ANIMATESHEET";
  57900. }
  57901. if (this._renderEffect && this._renderEffect.defines === defines) {
  57902. return;
  57903. }
  57904. 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);
  57905. };
  57906. /**
  57907. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57908. * @param preWarm defines if we are in the pre-warmimg phase
  57909. */
  57910. GPUParticleSystem.prototype.animate = function (preWarm) {
  57911. if (preWarm === void 0) { preWarm = false; }
  57912. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57913. this._actualFrame += this._timeDelta;
  57914. if (!this._stopped) {
  57915. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57916. this.stop();
  57917. }
  57918. }
  57919. };
  57920. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  57921. var texture = this[textureName];
  57922. if (!factorGradients || !factorGradients.length || texture) {
  57923. return;
  57924. }
  57925. var data = new Float32Array(this._rawTextureWidth);
  57926. for (var x = 0; x < this._rawTextureWidth; x++) {
  57927. var ratio = x / this._rawTextureWidth;
  57928. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  57929. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57930. });
  57931. }
  57932. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57933. };
  57934. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57935. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  57936. };
  57937. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  57938. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  57939. };
  57940. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57941. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57942. return;
  57943. }
  57944. var data = new Uint8Array(this._rawTextureWidth * 4);
  57945. var tmpColor = BABYLON.Tmp.Color4[0];
  57946. for (var x = 0; x < this._rawTextureWidth; x++) {
  57947. var ratio = x / this._rawTextureWidth;
  57948. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57949. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  57950. data[x * 4] = tmpColor.r * 255;
  57951. data[x * 4 + 1] = tmpColor.g * 255;
  57952. data[x * 4 + 2] = tmpColor.b * 255;
  57953. data[x * 4 + 3] = tmpColor.a * 255;
  57954. });
  57955. }
  57956. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57957. };
  57958. /**
  57959. * Renders the particle system in its current state
  57960. * @param preWarm defines if the system should only update the particles but not render them
  57961. * @returns the current number of particles
  57962. */
  57963. GPUParticleSystem.prototype.render = function (preWarm) {
  57964. if (preWarm === void 0) { preWarm = false; }
  57965. if (!this._started) {
  57966. return 0;
  57967. }
  57968. this._createColorGradientTexture();
  57969. this._createSizeGradientTexture();
  57970. this._createAngularSpeedGradientTexture();
  57971. this._recreateUpdateEffect();
  57972. this._recreateRenderEffect();
  57973. if (!this.isReady()) {
  57974. return 0;
  57975. }
  57976. if (!preWarm) {
  57977. if (!this._preWarmDone && this.preWarmCycles) {
  57978. for (var index = 0; index < this.preWarmCycles; index++) {
  57979. this.animate(true);
  57980. this.render(true);
  57981. }
  57982. this._preWarmDone = true;
  57983. }
  57984. if (this._currentRenderId === this._scene.getRenderId()) {
  57985. return 0;
  57986. }
  57987. this._currentRenderId = this._scene.getRenderId();
  57988. }
  57989. // Get everything ready to render
  57990. this._initialize();
  57991. this._accumulatedCount += this.emitRate * this._timeDelta;
  57992. if (this._accumulatedCount > 1) {
  57993. var intPart = this._accumulatedCount | 0;
  57994. this._accumulatedCount -= intPart;
  57995. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57996. }
  57997. if (!this._currentActiveCount) {
  57998. return 0;
  57999. }
  58000. // Enable update effect
  58001. this._engine.enableEffect(this._updateEffect);
  58002. this._engine.setState(false);
  58003. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58004. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58005. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58006. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58007. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  58008. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58009. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58010. if (!this._colorGradientsTexture) {
  58011. this._updateEffect.setDirectColor4("color1", this.color1);
  58012. this._updateEffect.setDirectColor4("color2", this.color2);
  58013. }
  58014. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58015. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  58016. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  58017. this._updateEffect.setVector3("gravity", this.gravity);
  58018. if (this._sizeGradientsTexture) {
  58019. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  58020. }
  58021. if (this._angularSpeedGradientsTexture) {
  58022. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  58023. }
  58024. if (this.particleEmitterType) {
  58025. this.particleEmitterType.applyToShader(this._updateEffect);
  58026. }
  58027. if (this._isAnimationSheetEnabled) {
  58028. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  58029. }
  58030. var emitterWM;
  58031. if (this.emitter.position) {
  58032. var emitterMesh = this.emitter;
  58033. emitterWM = emitterMesh.getWorldMatrix();
  58034. }
  58035. else {
  58036. var emitterPosition = this.emitter;
  58037. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58038. }
  58039. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58040. // Bind source VAO
  58041. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58042. // Update
  58043. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58044. this._engine.setRasterizerState(false);
  58045. this._engine.beginTransformFeedback();
  58046. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58047. this._engine.endTransformFeedback();
  58048. this._engine.setRasterizerState(true);
  58049. this._engine.bindTransformFeedbackBuffer(null);
  58050. if (!preWarm) {
  58051. // Enable render effect
  58052. this._engine.enableEffect(this._renderEffect);
  58053. var viewMatrix = this._scene.getViewMatrix();
  58054. this._renderEffect.setMatrix("view", viewMatrix);
  58055. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58056. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58057. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  58058. if (this._colorGradientsTexture) {
  58059. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  58060. }
  58061. else {
  58062. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58063. }
  58064. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58065. var baseSize = this.particleTexture.getBaseSize();
  58066. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58067. }
  58068. if (this._isBillboardBased) {
  58069. var camera = this._scene.activeCamera;
  58070. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  58071. }
  58072. if (this._scene.clipPlane) {
  58073. var clipPlane = this._scene.clipPlane;
  58074. var invView = viewMatrix.clone();
  58075. invView.invert();
  58076. this._renderEffect.setMatrix("invView", invView);
  58077. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58078. }
  58079. // Draw order
  58080. switch (this.blendMode) {
  58081. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  58082. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58083. break;
  58084. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  58085. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58086. break;
  58087. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  58088. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58089. break;
  58090. }
  58091. if (this.forceDepthWrite) {
  58092. this._engine.setDepthWrite(true);
  58093. }
  58094. // Bind source VAO
  58095. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58096. // Render
  58097. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58098. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58099. }
  58100. // Switch VAOs
  58101. this._targetIndex++;
  58102. if (this._targetIndex === 2) {
  58103. this._targetIndex = 0;
  58104. }
  58105. // Switch buffers
  58106. var tmpBuffer = this._sourceBuffer;
  58107. this._sourceBuffer = this._targetBuffer;
  58108. this._targetBuffer = tmpBuffer;
  58109. return this._currentActiveCount;
  58110. };
  58111. /**
  58112. * Rebuilds the particle system
  58113. */
  58114. GPUParticleSystem.prototype.rebuild = function () {
  58115. this._initialize(true);
  58116. };
  58117. GPUParticleSystem.prototype._releaseBuffers = function () {
  58118. if (this._buffer0) {
  58119. this._buffer0.dispose();
  58120. this._buffer0 = null;
  58121. }
  58122. if (this._buffer1) {
  58123. this._buffer1.dispose();
  58124. this._buffer1 = null;
  58125. }
  58126. if (this._spriteBuffer) {
  58127. this._spriteBuffer.dispose();
  58128. this._spriteBuffer = null;
  58129. }
  58130. };
  58131. GPUParticleSystem.prototype._releaseVAOs = function () {
  58132. if (!this._updateVAO) {
  58133. return;
  58134. }
  58135. for (var index = 0; index < this._updateVAO.length; index++) {
  58136. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58137. }
  58138. this._updateVAO = [];
  58139. for (var index = 0; index < this._renderVAO.length; index++) {
  58140. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58141. }
  58142. this._renderVAO = [];
  58143. };
  58144. /**
  58145. * Disposes the particle system and free the associated resources
  58146. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58147. */
  58148. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58149. if (disposeTexture === void 0) { disposeTexture = true; }
  58150. var index = this._scene.particleSystems.indexOf(this);
  58151. if (index > -1) {
  58152. this._scene.particleSystems.splice(index, 1);
  58153. }
  58154. this._releaseBuffers();
  58155. this._releaseVAOs();
  58156. if (this._colorGradientsTexture) {
  58157. this._colorGradientsTexture.dispose();
  58158. this._colorGradientsTexture = null;
  58159. }
  58160. if (this._sizeGradientsTexture) {
  58161. this._sizeGradientsTexture.dispose();
  58162. this._sizeGradientsTexture = null;
  58163. }
  58164. if (this._angularSpeedGradientsTexture) {
  58165. this._angularSpeedGradientsTexture.dispose();
  58166. this._angularSpeedGradientsTexture = null;
  58167. }
  58168. if (this._randomTexture) {
  58169. this._randomTexture.dispose();
  58170. this._randomTexture = null;
  58171. }
  58172. if (this._randomTexture2) {
  58173. this._randomTexture2.dispose();
  58174. this._randomTexture2 = null;
  58175. }
  58176. if (disposeTexture && this.particleTexture) {
  58177. this.particleTexture.dispose();
  58178. this.particleTexture = null;
  58179. }
  58180. // Callback
  58181. this.onDisposeObservable.notifyObservers(this);
  58182. this.onDisposeObservable.clear();
  58183. };
  58184. /**
  58185. * Clones the particle system.
  58186. * @param name The name of the cloned object
  58187. * @param newEmitter The new emitter to use
  58188. * @returns the cloned particle system
  58189. */
  58190. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58191. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58192. BABYLON.Tools.DeepCopy(this, result);
  58193. if (newEmitter === undefined) {
  58194. newEmitter = this.emitter;
  58195. }
  58196. result.emitter = newEmitter;
  58197. if (this.particleTexture) {
  58198. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58199. }
  58200. return result;
  58201. };
  58202. /**
  58203. * Serializes the particle system to a JSON object.
  58204. * @returns the JSON object
  58205. */
  58206. GPUParticleSystem.prototype.serialize = function () {
  58207. var serializationObject = {};
  58208. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  58209. serializationObject.activeParticleCount = this.activeParticleCount;
  58210. return serializationObject;
  58211. };
  58212. /**
  58213. * Parses a JSON object to create a GPU particle system.
  58214. * @param parsedParticleSystem The JSON object to parse
  58215. * @param scene The scene to create the particle system in
  58216. * @param rootUrl The root url to use to load external dependencies like texture
  58217. * @returns the parsed GPU particle system
  58218. */
  58219. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58220. var name = parsedParticleSystem.name;
  58221. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58222. if (parsedParticleSystem.activeParticleCount) {
  58223. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58224. }
  58225. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58226. return particleSystem;
  58227. };
  58228. return GPUParticleSystem;
  58229. }());
  58230. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58231. })(BABYLON || (BABYLON = {}));
  58232. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58233. var BABYLON;
  58234. (function (BABYLON) {
  58235. /**
  58236. * Represents one particle of a solid particle system.
  58237. */
  58238. var SolidParticle = /** @class */ (function () {
  58239. /**
  58240. * Creates a Solid Particle object.
  58241. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58242. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58243. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58244. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58245. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58246. * @param shapeId (integer) is the model shape identifier in the SPS.
  58247. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58248. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58249. */
  58250. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58251. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58252. /**
  58253. * particle global index
  58254. */
  58255. this.idx = 0;
  58256. /**
  58257. * The color of the particle
  58258. */
  58259. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58260. /**
  58261. * The world space position of the particle.
  58262. */
  58263. this.position = BABYLON.Vector3.Zero();
  58264. /**
  58265. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58266. */
  58267. this.rotation = BABYLON.Vector3.Zero();
  58268. /**
  58269. * The scaling of the particle.
  58270. */
  58271. this.scaling = BABYLON.Vector3.One();
  58272. /**
  58273. * The uvs of the particle.
  58274. */
  58275. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58276. /**
  58277. * The current speed of the particle.
  58278. */
  58279. this.velocity = BABYLON.Vector3.Zero();
  58280. /**
  58281. * The pivot point in the particle local space.
  58282. */
  58283. this.pivot = BABYLON.Vector3.Zero();
  58284. /**
  58285. * Must the particle be translated from its pivot point in its local space ?
  58286. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58287. * Default : false
  58288. */
  58289. this.translateFromPivot = false;
  58290. /**
  58291. * Is the particle active or not ?
  58292. */
  58293. this.alive = true;
  58294. /**
  58295. * Is the particle visible or not ?
  58296. */
  58297. this.isVisible = true;
  58298. /**
  58299. * Index of this particle in the global "positions" array (Internal use)
  58300. */
  58301. this._pos = 0;
  58302. /**
  58303. * Index of this particle in the global "indices" array (Internal use)
  58304. */
  58305. this._ind = 0;
  58306. /**
  58307. * ModelShape id of this particle
  58308. */
  58309. this.shapeId = 0;
  58310. /**
  58311. * Index of the particle in its shape id (Internal use)
  58312. */
  58313. this.idxInShape = 0;
  58314. /**
  58315. * Still set as invisible in order to skip useless computations (Internal use)
  58316. */
  58317. this._stillInvisible = false;
  58318. /**
  58319. * Last computed particle rotation matrix
  58320. */
  58321. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58322. /**
  58323. * Parent particle Id, if any.
  58324. * Default null.
  58325. */
  58326. this.parentId = null;
  58327. /**
  58328. * Internal global position in the SPS.
  58329. */
  58330. this._globalPosition = BABYLON.Vector3.Zero();
  58331. this.idx = particleIndex;
  58332. this._pos = positionIndex;
  58333. this._ind = indiceIndex;
  58334. this._model = model;
  58335. this.shapeId = shapeId;
  58336. this.idxInShape = idxInShape;
  58337. this._sps = sps;
  58338. if (modelBoundingInfo) {
  58339. this._modelBoundingInfo = modelBoundingInfo;
  58340. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58341. }
  58342. }
  58343. Object.defineProperty(SolidParticle.prototype, "scale", {
  58344. /**
  58345. * Legacy support, changed scale to scaling
  58346. */
  58347. get: function () {
  58348. return this.scaling;
  58349. },
  58350. /**
  58351. * Legacy support, changed scale to scaling
  58352. */
  58353. set: function (scale) {
  58354. this.scaling = scale;
  58355. },
  58356. enumerable: true,
  58357. configurable: true
  58358. });
  58359. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58360. /**
  58361. * Legacy support, changed quaternion to rotationQuaternion
  58362. */
  58363. get: function () {
  58364. return this.rotationQuaternion;
  58365. },
  58366. /**
  58367. * Legacy support, changed quaternion to rotationQuaternion
  58368. */
  58369. set: function (q) {
  58370. this.rotationQuaternion = q;
  58371. },
  58372. enumerable: true,
  58373. configurable: true
  58374. });
  58375. /**
  58376. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58377. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58378. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58379. * @returns true if it intersects
  58380. */
  58381. SolidParticle.prototype.intersectsMesh = function (target) {
  58382. if (!this._boundingInfo || !target._boundingInfo) {
  58383. return false;
  58384. }
  58385. if (this._sps._bSphereOnly) {
  58386. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58387. }
  58388. return this._boundingInfo.intersects(target._boundingInfo, false);
  58389. };
  58390. return SolidParticle;
  58391. }());
  58392. BABYLON.SolidParticle = SolidParticle;
  58393. /**
  58394. * Represents the shape of the model used by one particle of a solid particle system.
  58395. * SPS internal tool, don't use it manually.
  58396. */
  58397. var ModelShape = /** @class */ (function () {
  58398. /**
  58399. * 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.
  58400. * SPS internal tool, don't use it manually.
  58401. * @hidden
  58402. */
  58403. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58404. /**
  58405. * length of the shape in the model indices array (internal use)
  58406. */
  58407. this._indicesLength = 0;
  58408. this.shapeID = id;
  58409. this._shape = shape;
  58410. this._indicesLength = indicesLength;
  58411. this._shapeUV = shapeUV;
  58412. this._positionFunction = posFunction;
  58413. this._vertexFunction = vtxFunction;
  58414. }
  58415. return ModelShape;
  58416. }());
  58417. BABYLON.ModelShape = ModelShape;
  58418. /**
  58419. * Represents a Depth Sorted Particle in the solid particle system.
  58420. */
  58421. var DepthSortedParticle = /** @class */ (function () {
  58422. function DepthSortedParticle() {
  58423. /**
  58424. * Index of the particle in the "indices" array
  58425. */
  58426. this.ind = 0;
  58427. /**
  58428. * Length of the particle shape in the "indices" array
  58429. */
  58430. this.indicesLength = 0;
  58431. /**
  58432. * Squared distance from the particle to the camera
  58433. */
  58434. this.sqDistance = 0.0;
  58435. }
  58436. return DepthSortedParticle;
  58437. }());
  58438. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58439. })(BABYLON || (BABYLON = {}));
  58440. //# sourceMappingURL=babylon.solidParticle.js.map
  58441. var BABYLON;
  58442. (function (BABYLON) {
  58443. /**
  58444. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58445. *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.
  58446. * The SPS is also a particle system. It provides some methods to manage the particles.
  58447. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58448. *
  58449. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58450. */
  58451. var SolidParticleSystem = /** @class */ (function () {
  58452. /**
  58453. * Creates a SPS (Solid Particle System) object.
  58454. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58455. * @param scene (Scene) is the scene in which the SPS is added.
  58456. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58457. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58458. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58459. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58460. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58461. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58462. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58463. */
  58464. function SolidParticleSystem(name, scene, options) {
  58465. /**
  58466. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58467. * Example : var p = SPS.particles[i];
  58468. */
  58469. this.particles = new Array();
  58470. /**
  58471. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58472. */
  58473. this.nbParticles = 0;
  58474. /**
  58475. * If the particles must ever face the camera (default false). Useful for planar particles.
  58476. */
  58477. this.billboard = false;
  58478. /**
  58479. * Recompute normals when adding a shape
  58480. */
  58481. this.recomputeNormals = true;
  58482. /**
  58483. * This a counter ofr your own usage. It's not set by any SPS functions.
  58484. */
  58485. this.counter = 0;
  58486. /**
  58487. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58488. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58489. */
  58490. this.vars = {};
  58491. /**
  58492. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58493. */
  58494. this._bSphereOnly = false;
  58495. /**
  58496. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58497. */
  58498. this._bSphereRadiusFactor = 1.0;
  58499. this._positions = new Array();
  58500. this._indices = new Array();
  58501. this._normals = new Array();
  58502. this._colors = new Array();
  58503. this._uvs = new Array();
  58504. this._index = 0; // indices index
  58505. this._updatable = true;
  58506. this._pickable = false;
  58507. this._isVisibilityBoxLocked = false;
  58508. this._alwaysVisible = false;
  58509. this._depthSort = false;
  58510. this._shapeCounter = 0;
  58511. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58512. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58513. this._computeParticleColor = true;
  58514. this._computeParticleTexture = true;
  58515. this._computeParticleRotation = true;
  58516. this._computeParticleVertex = false;
  58517. this._computeBoundingBox = false;
  58518. this._depthSortParticles = true;
  58519. this._cam_axisZ = BABYLON.Vector3.Zero();
  58520. this._cam_axisY = BABYLON.Vector3.Zero();
  58521. this._cam_axisX = BABYLON.Vector3.Zero();
  58522. this._axisZ = BABYLON.Axis.Z;
  58523. this._camDir = BABYLON.Vector3.Zero();
  58524. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58525. this._rotMatrix = new BABYLON.Matrix();
  58526. this._invertMatrix = new BABYLON.Matrix();
  58527. this._rotated = BABYLON.Vector3.Zero();
  58528. this._quaternion = new BABYLON.Quaternion();
  58529. this._vertex = BABYLON.Vector3.Zero();
  58530. this._normal = BABYLON.Vector3.Zero();
  58531. this._yaw = 0.0;
  58532. this._pitch = 0.0;
  58533. this._roll = 0.0;
  58534. this._halfroll = 0.0;
  58535. this._halfpitch = 0.0;
  58536. this._halfyaw = 0.0;
  58537. this._sinRoll = 0.0;
  58538. this._cosRoll = 0.0;
  58539. this._sinPitch = 0.0;
  58540. this._cosPitch = 0.0;
  58541. this._sinYaw = 0.0;
  58542. this._cosYaw = 0.0;
  58543. this._mustUnrotateFixedNormals = false;
  58544. this._minimum = BABYLON.Vector3.Zero();
  58545. this._maximum = BABYLON.Vector3.Zero();
  58546. this._minBbox = BABYLON.Vector3.Zero();
  58547. this._maxBbox = BABYLON.Vector3.Zero();
  58548. this._particlesIntersect = false;
  58549. this._depthSortFunction = function (p1, p2) {
  58550. return (p2.sqDistance - p1.sqDistance);
  58551. };
  58552. this._needs32Bits = false;
  58553. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58554. this._scaledPivot = BABYLON.Vector3.Zero();
  58555. this._particleHasParent = false;
  58556. this.name = name;
  58557. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58558. this._camera = scene.activeCamera;
  58559. this._pickable = options ? options.isPickable : false;
  58560. this._depthSort = options ? options.enableDepthSort : false;
  58561. this._particlesIntersect = options ? options.particleIntersection : false;
  58562. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58563. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58564. if (options && options.updatable !== undefined) {
  58565. this._updatable = options.updatable;
  58566. }
  58567. else {
  58568. this._updatable = true;
  58569. }
  58570. if (this._pickable) {
  58571. this.pickedParticles = [];
  58572. }
  58573. if (this._depthSort) {
  58574. this.depthSortedParticles = [];
  58575. }
  58576. }
  58577. /**
  58578. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58579. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58580. * @returns the created mesh
  58581. */
  58582. SolidParticleSystem.prototype.buildMesh = function () {
  58583. if (this.nbParticles === 0) {
  58584. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58585. this.addShape(triangle, 1);
  58586. triangle.dispose();
  58587. }
  58588. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58589. this._positions32 = new Float32Array(this._positions);
  58590. this._uvs32 = new Float32Array(this._uvs);
  58591. this._colors32 = new Float32Array(this._colors);
  58592. if (this.recomputeNormals) {
  58593. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58594. }
  58595. this._normals32 = new Float32Array(this._normals);
  58596. this._fixedNormal32 = new Float32Array(this._normals);
  58597. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58598. this._unrotateFixedNormals();
  58599. }
  58600. var vertexData = new BABYLON.VertexData();
  58601. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58602. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58603. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58604. if (this._uvs32.length > 0) {
  58605. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58606. }
  58607. if (this._colors32.length > 0) {
  58608. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58609. }
  58610. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58611. vertexData.applyToMesh(mesh, this._updatable);
  58612. this.mesh = mesh;
  58613. this.mesh.isPickable = this._pickable;
  58614. // free memory
  58615. if (!this._depthSort) {
  58616. this._indices = null;
  58617. }
  58618. this._positions = null;
  58619. this._normals = null;
  58620. this._uvs = null;
  58621. this._colors = null;
  58622. if (!this._updatable) {
  58623. this.particles.length = 0;
  58624. }
  58625. return mesh;
  58626. };
  58627. /**
  58628. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58629. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58630. * Thus the particles generated from `digest()` have their property `position` set yet.
  58631. * @param mesh ( Mesh ) is the mesh to be digested
  58632. * @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
  58633. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58634. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58635. * @returns the current SPS
  58636. */
  58637. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58638. var size = (options && options.facetNb) || 1;
  58639. var number = (options && options.number) || 0;
  58640. var delta = (options && options.delta) || 0;
  58641. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58642. var meshInd = mesh.getIndices();
  58643. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58644. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58645. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58646. var f = 0; // facet counter
  58647. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58648. // compute size from number
  58649. if (number) {
  58650. number = (number > totalFacets) ? totalFacets : number;
  58651. size = Math.round(totalFacets / number);
  58652. delta = 0;
  58653. }
  58654. else {
  58655. size = (size > totalFacets) ? totalFacets : size;
  58656. }
  58657. var facetPos = []; // submesh positions
  58658. var facetInd = []; // submesh indices
  58659. var facetUV = []; // submesh UV
  58660. var facetCol = []; // submesh colors
  58661. var barycenter = BABYLON.Vector3.Zero();
  58662. var sizeO = size;
  58663. while (f < totalFacets) {
  58664. size = sizeO + Math.floor((1 + delta) * Math.random());
  58665. if (f > totalFacets - size) {
  58666. size = totalFacets - f;
  58667. }
  58668. // reset temp arrays
  58669. facetPos.length = 0;
  58670. facetInd.length = 0;
  58671. facetUV.length = 0;
  58672. facetCol.length = 0;
  58673. // iterate over "size" facets
  58674. var fi = 0;
  58675. for (var j = f * 3; j < (f + size) * 3; j++) {
  58676. facetInd.push(fi);
  58677. var i = meshInd[j];
  58678. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58679. if (meshUV) {
  58680. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58681. }
  58682. if (meshCol) {
  58683. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58684. }
  58685. fi++;
  58686. }
  58687. // create a model shape for each single particle
  58688. var idx = this.nbParticles;
  58689. var shape = this._posToShape(facetPos);
  58690. var shapeUV = this._uvsToShapeUV(facetUV);
  58691. // compute the barycenter of the shape
  58692. var v;
  58693. for (v = 0; v < shape.length; v++) {
  58694. barycenter.addInPlace(shape[v]);
  58695. }
  58696. barycenter.scaleInPlace(1 / shape.length);
  58697. // shift the shape from its barycenter to the origin
  58698. for (v = 0; v < shape.length; v++) {
  58699. shape[v].subtractInPlace(barycenter);
  58700. }
  58701. var bInfo;
  58702. if (this._particlesIntersect) {
  58703. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58704. }
  58705. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58706. // add the particle in the SPS
  58707. var currentPos = this._positions.length;
  58708. var currentInd = this._indices.length;
  58709. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58710. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58711. // initialize the particle position
  58712. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58713. this._index += shape.length;
  58714. idx++;
  58715. this.nbParticles++;
  58716. this._shapeCounter++;
  58717. f += size;
  58718. }
  58719. return this;
  58720. };
  58721. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58722. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58723. var index = 0;
  58724. var idx = 0;
  58725. for (var p = 0; p < this.particles.length; p++) {
  58726. this._particle = this.particles[p];
  58727. this._shape = this._particle._model._shape;
  58728. if (this._particle.rotationQuaternion) {
  58729. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58730. }
  58731. else {
  58732. this._yaw = this._particle.rotation.y;
  58733. this._pitch = this._particle.rotation.x;
  58734. this._roll = this._particle.rotation.z;
  58735. this._quaternionRotationYPR();
  58736. }
  58737. this._quaternionToRotationMatrix();
  58738. this._rotMatrix.invertToRef(this._invertMatrix);
  58739. for (var pt = 0; pt < this._shape.length; pt++) {
  58740. idx = index + pt * 3;
  58741. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58742. this._fixedNormal32[idx] = this._normal.x;
  58743. this._fixedNormal32[idx + 1] = this._normal.y;
  58744. this._fixedNormal32[idx + 2] = this._normal.z;
  58745. }
  58746. index = idx + 3;
  58747. }
  58748. };
  58749. //reset copy
  58750. SolidParticleSystem.prototype._resetCopy = function () {
  58751. this._copy.position.x = 0;
  58752. this._copy.position.y = 0;
  58753. this._copy.position.z = 0;
  58754. this._copy.rotation.x = 0;
  58755. this._copy.rotation.y = 0;
  58756. this._copy.rotation.z = 0;
  58757. this._copy.rotationQuaternion = null;
  58758. this._copy.scaling.x = 1.0;
  58759. this._copy.scaling.y = 1.0;
  58760. this._copy.scaling.z = 1.0;
  58761. this._copy.uvs.x = 0;
  58762. this._copy.uvs.y = 0;
  58763. this._copy.uvs.z = 1.0;
  58764. this._copy.uvs.w = 1.0;
  58765. this._copy.color = null;
  58766. this._copy.translateFromPivot = false;
  58767. };
  58768. // _meshBuilder : inserts the shape model in the global SPS mesh
  58769. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58770. var i;
  58771. var u = 0;
  58772. var c = 0;
  58773. var n = 0;
  58774. this._resetCopy();
  58775. if (options && options.positionFunction) { // call to custom positionFunction
  58776. options.positionFunction(this._copy, idx, idxInShape);
  58777. this._mustUnrotateFixedNormals = true;
  58778. }
  58779. if (this._copy.rotationQuaternion) {
  58780. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58781. }
  58782. else {
  58783. this._yaw = this._copy.rotation.y;
  58784. this._pitch = this._copy.rotation.x;
  58785. this._roll = this._copy.rotation.z;
  58786. this._quaternionRotationYPR();
  58787. }
  58788. this._quaternionToRotationMatrix();
  58789. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58790. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58791. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58792. if (this._copy.translateFromPivot) {
  58793. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58794. }
  58795. else {
  58796. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58797. }
  58798. for (i = 0; i < shape.length; i++) {
  58799. this._vertex.x = shape[i].x;
  58800. this._vertex.y = shape[i].y;
  58801. this._vertex.z = shape[i].z;
  58802. if (options && options.vertexFunction) {
  58803. options.vertexFunction(this._copy, this._vertex, i);
  58804. }
  58805. this._vertex.x *= this._copy.scaling.x;
  58806. this._vertex.y *= this._copy.scaling.y;
  58807. this._vertex.z *= this._copy.scaling.z;
  58808. this._vertex.x -= this._scaledPivot.x;
  58809. this._vertex.y -= this._scaledPivot.y;
  58810. this._vertex.z -= this._scaledPivot.z;
  58811. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58812. this._rotated.addInPlace(this._pivotBackTranslation);
  58813. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58814. if (meshUV) {
  58815. 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);
  58816. u += 2;
  58817. }
  58818. if (this._copy.color) {
  58819. this._color = this._copy.color;
  58820. }
  58821. else if (meshCol && meshCol[c] !== undefined) {
  58822. this._color.r = meshCol[c];
  58823. this._color.g = meshCol[c + 1];
  58824. this._color.b = meshCol[c + 2];
  58825. this._color.a = meshCol[c + 3];
  58826. }
  58827. else {
  58828. this._color.r = 1.0;
  58829. this._color.g = 1.0;
  58830. this._color.b = 1.0;
  58831. this._color.a = 1.0;
  58832. }
  58833. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58834. c += 4;
  58835. if (!this.recomputeNormals && meshNor) {
  58836. this._normal.x = meshNor[n];
  58837. this._normal.y = meshNor[n + 1];
  58838. this._normal.z = meshNor[n + 2];
  58839. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58840. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58841. n += 3;
  58842. }
  58843. }
  58844. for (i = 0; i < meshInd.length; i++) {
  58845. var current_ind = p + meshInd[i];
  58846. indices.push(current_ind);
  58847. if (current_ind > 65535) {
  58848. this._needs32Bits = true;
  58849. }
  58850. }
  58851. if (this._pickable) {
  58852. var nbfaces = meshInd.length / 3;
  58853. for (i = 0; i < nbfaces; i++) {
  58854. this.pickedParticles.push({ idx: idx, faceId: i });
  58855. }
  58856. }
  58857. if (this._depthSort) {
  58858. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58859. }
  58860. return this._copy;
  58861. };
  58862. // returns a shape array from positions array
  58863. SolidParticleSystem.prototype._posToShape = function (positions) {
  58864. var shape = [];
  58865. for (var i = 0; i < positions.length; i += 3) {
  58866. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58867. }
  58868. return shape;
  58869. };
  58870. // returns a shapeUV array from a Vector4 uvs
  58871. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58872. var shapeUV = [];
  58873. if (uvs) {
  58874. for (var i = 0; i < uvs.length; i++)
  58875. shapeUV.push(uvs[i]);
  58876. }
  58877. return shapeUV;
  58878. };
  58879. // adds a new particle object in the particles array
  58880. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58881. if (bInfo === void 0) { bInfo = null; }
  58882. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58883. this.particles.push(sp);
  58884. return sp;
  58885. };
  58886. /**
  58887. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58888. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58889. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58890. * @param nb (positive integer) the number of particles to be created from this model
  58891. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58892. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58893. * @returns the number of shapes in the system
  58894. */
  58895. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58896. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58897. var meshInd = mesh.getIndices();
  58898. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58899. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58900. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58901. var bbInfo;
  58902. if (this._particlesIntersect) {
  58903. bbInfo = mesh.getBoundingInfo();
  58904. }
  58905. var shape = this._posToShape(meshPos);
  58906. var shapeUV = this._uvsToShapeUV(meshUV);
  58907. var posfunc = options ? options.positionFunction : null;
  58908. var vtxfunc = options ? options.vertexFunction : null;
  58909. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58910. // particles
  58911. var sp;
  58912. var currentCopy;
  58913. var idx = this.nbParticles;
  58914. for (var i = 0; i < nb; i++) {
  58915. var currentPos = this._positions.length;
  58916. var currentInd = this._indices.length;
  58917. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58918. if (this._updatable) {
  58919. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58920. sp.position.copyFrom(currentCopy.position);
  58921. sp.rotation.copyFrom(currentCopy.rotation);
  58922. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58923. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58924. }
  58925. if (currentCopy.color && sp.color) {
  58926. sp.color.copyFrom(currentCopy.color);
  58927. }
  58928. sp.scaling.copyFrom(currentCopy.scaling);
  58929. sp.uvs.copyFrom(currentCopy.uvs);
  58930. }
  58931. this._index += shape.length;
  58932. idx++;
  58933. }
  58934. this.nbParticles += nb;
  58935. this._shapeCounter++;
  58936. return this._shapeCounter - 1;
  58937. };
  58938. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58939. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58940. this._resetCopy();
  58941. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58942. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58943. }
  58944. if (this._copy.rotationQuaternion) {
  58945. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58946. }
  58947. else {
  58948. this._yaw = this._copy.rotation.y;
  58949. this._pitch = this._copy.rotation.x;
  58950. this._roll = this._copy.rotation.z;
  58951. this._quaternionRotationYPR();
  58952. }
  58953. this._quaternionToRotationMatrix();
  58954. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58955. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58956. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58957. if (this._copy.translateFromPivot) {
  58958. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58959. }
  58960. else {
  58961. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58962. }
  58963. this._shape = particle._model._shape;
  58964. for (var pt = 0; pt < this._shape.length; pt++) {
  58965. this._vertex.x = this._shape[pt].x;
  58966. this._vertex.y = this._shape[pt].y;
  58967. this._vertex.z = this._shape[pt].z;
  58968. if (particle._model._vertexFunction) {
  58969. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58970. }
  58971. this._vertex.x *= this._copy.scaling.x;
  58972. this._vertex.y *= this._copy.scaling.y;
  58973. this._vertex.z *= this._copy.scaling.z;
  58974. this._vertex.x -= this._scaledPivot.x;
  58975. this._vertex.y -= this._scaledPivot.y;
  58976. this._vertex.z -= this._scaledPivot.z;
  58977. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58978. this._rotated.addInPlace(this._pivotBackTranslation);
  58979. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58980. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58981. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58982. }
  58983. particle.position.x = 0.0;
  58984. particle.position.y = 0.0;
  58985. particle.position.z = 0.0;
  58986. particle.rotation.x = 0.0;
  58987. particle.rotation.y = 0.0;
  58988. particle.rotation.z = 0.0;
  58989. particle.rotationQuaternion = null;
  58990. particle.scaling.x = 1.0;
  58991. particle.scaling.y = 1.0;
  58992. particle.scaling.z = 1.0;
  58993. particle.uvs.x = 0.0;
  58994. particle.uvs.y = 0.0;
  58995. particle.uvs.z = 1.0;
  58996. particle.uvs.w = 1.0;
  58997. particle.pivot.x = 0.0;
  58998. particle.pivot.y = 0.0;
  58999. particle.pivot.z = 0.0;
  59000. particle.translateFromPivot = false;
  59001. particle.parentId = null;
  59002. };
  59003. /**
  59004. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59005. * @returns the SPS.
  59006. */
  59007. SolidParticleSystem.prototype.rebuildMesh = function () {
  59008. for (var p = 0; p < this.particles.length; p++) {
  59009. this._rebuildParticle(this.particles[p]);
  59010. }
  59011. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59012. return this;
  59013. };
  59014. /**
  59015. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59016. * This method calls `updateParticle()` for each particle of the SPS.
  59017. * For an animated SPS, it is usually called within the render loop.
  59018. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59019. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59020. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59021. * @returns the SPS.
  59022. */
  59023. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59024. if (start === void 0) { start = 0; }
  59025. if (end === void 0) { end = this.nbParticles - 1; }
  59026. if (update === void 0) { update = true; }
  59027. if (!this._updatable) {
  59028. return this;
  59029. }
  59030. // custom beforeUpdate
  59031. this.beforeUpdateParticles(start, end, update);
  59032. this._cam_axisX.x = 1.0;
  59033. this._cam_axisX.y = 0.0;
  59034. this._cam_axisX.z = 0.0;
  59035. this._cam_axisY.x = 0.0;
  59036. this._cam_axisY.y = 1.0;
  59037. this._cam_axisY.z = 0.0;
  59038. this._cam_axisZ.x = 0.0;
  59039. this._cam_axisZ.y = 0.0;
  59040. this._cam_axisZ.z = 1.0;
  59041. // cases when the World Matrix is to be computed first
  59042. if (this.billboard || this._depthSort) {
  59043. this.mesh.computeWorldMatrix(true);
  59044. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59045. }
  59046. // if the particles will always face the camera
  59047. if (this.billboard) {
  59048. // compute the camera position and un-rotate it by the current mesh rotation
  59049. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59050. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59051. this._cam_axisZ.normalize();
  59052. // same for camera up vector extracted from the cam view matrix
  59053. var view = this._camera.getViewMatrix(true);
  59054. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59055. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59056. this._cam_axisY.normalize();
  59057. this._cam_axisX.normalize();
  59058. }
  59059. // if depthSort, compute the camera global position in the mesh local system
  59060. if (this._depthSort) {
  59061. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59062. }
  59063. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59064. var idx = 0; // current position index in the global array positions32
  59065. var index = 0; // position start index in the global array positions32 of the current particle
  59066. var colidx = 0; // current color index in the global array colors32
  59067. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59068. var uvidx = 0; // current uv index in the global array uvs32
  59069. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59070. var pt = 0; // current index in the particle model shape
  59071. if (this.mesh.isFacetDataEnabled) {
  59072. this._computeBoundingBox = true;
  59073. }
  59074. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59075. if (this._computeBoundingBox) {
  59076. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59077. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59078. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59079. }
  59080. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59081. if (this.mesh._boundingInfo) {
  59082. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59083. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59084. }
  59085. }
  59086. }
  59087. // particle loop
  59088. index = this.particles[start]._pos;
  59089. var vpos = (index / 3) | 0;
  59090. colorIndex = vpos * 4;
  59091. uvIndex = vpos * 2;
  59092. for (var p = start; p <= end; p++) {
  59093. this._particle = this.particles[p];
  59094. this._shape = this._particle._model._shape;
  59095. this._shapeUV = this._particle._model._shapeUV;
  59096. // call to custom user function to update the particle properties
  59097. this.updateParticle(this._particle);
  59098. // camera-particle distance for depth sorting
  59099. if (this._depthSort && this._depthSortParticles) {
  59100. var dsp = this.depthSortedParticles[p];
  59101. dsp.ind = this._particle._ind;
  59102. dsp.indicesLength = this._particle._model._indicesLength;
  59103. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59104. }
  59105. // skip the computations for inactive or already invisible particles
  59106. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59107. // increment indexes for the next particle
  59108. pt = this._shape.length;
  59109. index += pt * 3;
  59110. colorIndex += pt * 4;
  59111. uvIndex += pt * 2;
  59112. continue;
  59113. }
  59114. if (this._particle.isVisible) {
  59115. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59116. this._particleHasParent = (this._particle.parentId !== null);
  59117. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59118. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59119. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59120. // particle rotation matrix
  59121. if (this.billboard) {
  59122. this._particle.rotation.x = 0.0;
  59123. this._particle.rotation.y = 0.0;
  59124. }
  59125. if (this._computeParticleRotation || this.billboard) {
  59126. if (this._particle.rotationQuaternion) {
  59127. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59128. }
  59129. else {
  59130. this._yaw = this._particle.rotation.y;
  59131. this._pitch = this._particle.rotation.x;
  59132. this._roll = this._particle.rotation.z;
  59133. this._quaternionRotationYPR();
  59134. }
  59135. this._quaternionToRotationMatrix();
  59136. }
  59137. if (this._particleHasParent) {
  59138. this._parent = this.particles[this._particle.parentId];
  59139. 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];
  59140. 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];
  59141. 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];
  59142. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59143. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59144. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59145. if (this._computeParticleRotation || this.billboard) {
  59146. 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];
  59147. 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];
  59148. 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];
  59149. 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];
  59150. 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];
  59151. 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];
  59152. 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];
  59153. 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];
  59154. 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];
  59155. }
  59156. }
  59157. else {
  59158. this._particle._globalPosition.x = this._particle.position.x;
  59159. this._particle._globalPosition.y = this._particle.position.y;
  59160. this._particle._globalPosition.z = this._particle.position.z;
  59161. if (this._computeParticleRotation || this.billboard) {
  59162. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59163. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59164. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59165. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59166. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59167. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59168. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59169. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59170. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59171. }
  59172. }
  59173. if (this._particle.translateFromPivot) {
  59174. this._pivotBackTranslation.x = 0.0;
  59175. this._pivotBackTranslation.y = 0.0;
  59176. this._pivotBackTranslation.z = 0.0;
  59177. }
  59178. else {
  59179. this._pivotBackTranslation.x = this._scaledPivot.x;
  59180. this._pivotBackTranslation.y = this._scaledPivot.y;
  59181. this._pivotBackTranslation.z = this._scaledPivot.z;
  59182. }
  59183. // particle vertex loop
  59184. for (pt = 0; pt < this._shape.length; pt++) {
  59185. idx = index + pt * 3;
  59186. colidx = colorIndex + pt * 4;
  59187. uvidx = uvIndex + pt * 2;
  59188. this._vertex.x = this._shape[pt].x;
  59189. this._vertex.y = this._shape[pt].y;
  59190. this._vertex.z = this._shape[pt].z;
  59191. if (this._computeParticleVertex) {
  59192. this.updateParticleVertex(this._particle, this._vertex, pt);
  59193. }
  59194. // positions
  59195. this._vertex.x *= this._particle.scaling.x;
  59196. this._vertex.y *= this._particle.scaling.y;
  59197. this._vertex.z *= this._particle.scaling.z;
  59198. this._vertex.x -= this._scaledPivot.x;
  59199. this._vertex.y -= this._scaledPivot.y;
  59200. this._vertex.z -= this._scaledPivot.z;
  59201. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59202. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59203. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59204. this._rotated.x += this._pivotBackTranslation.x;
  59205. this._rotated.y += this._pivotBackTranslation.y;
  59206. this._rotated.z += this._pivotBackTranslation.z;
  59207. 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;
  59208. 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;
  59209. 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;
  59210. if (this._computeBoundingBox) {
  59211. if (this._positions32[idx] < this._minimum.x) {
  59212. this._minimum.x = this._positions32[idx];
  59213. }
  59214. if (this._positions32[idx] > this._maximum.x) {
  59215. this._maximum.x = this._positions32[idx];
  59216. }
  59217. if (this._positions32[idx + 1] < this._minimum.y) {
  59218. this._minimum.y = this._positions32[idx + 1];
  59219. }
  59220. if (this._positions32[idx + 1] > this._maximum.y) {
  59221. this._maximum.y = this._positions32[idx + 1];
  59222. }
  59223. if (this._positions32[idx + 2] < this._minimum.z) {
  59224. this._minimum.z = this._positions32[idx + 2];
  59225. }
  59226. if (this._positions32[idx + 2] > this._maximum.z) {
  59227. this._maximum.z = this._positions32[idx + 2];
  59228. }
  59229. }
  59230. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59231. if (!this._computeParticleVertex) {
  59232. this._normal.x = this._fixedNormal32[idx];
  59233. this._normal.y = this._fixedNormal32[idx + 1];
  59234. this._normal.z = this._fixedNormal32[idx + 2];
  59235. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59236. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59237. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59238. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59239. 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;
  59240. 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;
  59241. }
  59242. if (this._computeParticleColor && this._particle.color) {
  59243. this._colors32[colidx] = this._particle.color.r;
  59244. this._colors32[colidx + 1] = this._particle.color.g;
  59245. this._colors32[colidx + 2] = this._particle.color.b;
  59246. this._colors32[colidx + 3] = this._particle.color.a;
  59247. }
  59248. if (this._computeParticleTexture) {
  59249. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59250. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59251. }
  59252. }
  59253. }
  59254. // particle just set invisible : scaled to zero and positioned at the origin
  59255. else {
  59256. this._particle._stillInvisible = true; // mark the particle as invisible
  59257. for (pt = 0; pt < this._shape.length; pt++) {
  59258. idx = index + pt * 3;
  59259. colidx = colorIndex + pt * 4;
  59260. uvidx = uvIndex + pt * 2;
  59261. this._positions32[idx] = 0.0;
  59262. this._positions32[idx + 1] = 0.0;
  59263. this._positions32[idx + 2] = 0.0;
  59264. this._normals32[idx] = 0.0;
  59265. this._normals32[idx + 1] = 0.0;
  59266. this._normals32[idx + 2] = 0.0;
  59267. if (this._computeParticleColor && this._particle.color) {
  59268. this._colors32[colidx] = this._particle.color.r;
  59269. this._colors32[colidx + 1] = this._particle.color.g;
  59270. this._colors32[colidx + 2] = this._particle.color.b;
  59271. this._colors32[colidx + 3] = this._particle.color.a;
  59272. }
  59273. if (this._computeParticleTexture) {
  59274. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59275. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59276. }
  59277. }
  59278. }
  59279. // if the particle intersections must be computed : update the bbInfo
  59280. if (this._particlesIntersect) {
  59281. var bInfo = this._particle._boundingInfo;
  59282. var bBox = bInfo.boundingBox;
  59283. var bSphere = bInfo.boundingSphere;
  59284. if (!this._bSphereOnly) {
  59285. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59286. for (var b = 0; b < bBox.vectors.length; b++) {
  59287. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59288. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59289. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59290. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59291. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59292. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59293. 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;
  59294. 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;
  59295. 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;
  59296. }
  59297. bBox._update(this.mesh._worldMatrix);
  59298. }
  59299. // place and scale the particle bouding sphere in the SPS local system, then update it
  59300. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59301. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59302. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59303. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59304. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59305. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59306. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59307. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59308. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59309. 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));
  59310. bSphere._update(this.mesh._worldMatrix);
  59311. }
  59312. // increment indexes for the next particle
  59313. index = idx + 3;
  59314. colorIndex = colidx + 4;
  59315. uvIndex = uvidx + 2;
  59316. }
  59317. // if the VBO must be updated
  59318. if (update) {
  59319. if (this._computeParticleColor) {
  59320. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59321. }
  59322. if (this._computeParticleTexture) {
  59323. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59324. }
  59325. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59326. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59327. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59328. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59329. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59330. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59331. for (var i = 0; i < this._normals32.length; i++) {
  59332. this._fixedNormal32[i] = this._normals32[i];
  59333. }
  59334. }
  59335. if (!this.mesh.areNormalsFrozen) {
  59336. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59337. }
  59338. }
  59339. if (this._depthSort && this._depthSortParticles) {
  59340. this.depthSortedParticles.sort(this._depthSortFunction);
  59341. var dspl = this.depthSortedParticles.length;
  59342. var sorted = 0;
  59343. var lind = 0;
  59344. var sind = 0;
  59345. var sid = 0;
  59346. for (sorted = 0; sorted < dspl; sorted++) {
  59347. lind = this.depthSortedParticles[sorted].indicesLength;
  59348. sind = this.depthSortedParticles[sorted].ind;
  59349. for (var i = 0; i < lind; i++) {
  59350. this._indices32[sid] = this._indices[sind + i];
  59351. sid++;
  59352. }
  59353. }
  59354. this.mesh.updateIndices(this._indices32);
  59355. }
  59356. }
  59357. if (this._computeBoundingBox) {
  59358. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59359. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59360. }
  59361. this.afterUpdateParticles(start, end, update);
  59362. return this;
  59363. };
  59364. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59365. this._halfroll = this._roll * 0.5;
  59366. this._halfpitch = this._pitch * 0.5;
  59367. this._halfyaw = this._yaw * 0.5;
  59368. this._sinRoll = Math.sin(this._halfroll);
  59369. this._cosRoll = Math.cos(this._halfroll);
  59370. this._sinPitch = Math.sin(this._halfpitch);
  59371. this._cosPitch = Math.cos(this._halfpitch);
  59372. this._sinYaw = Math.sin(this._halfyaw);
  59373. this._cosYaw = Math.cos(this._halfyaw);
  59374. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59375. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59376. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59377. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59378. };
  59379. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59380. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59381. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59382. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59383. this._rotMatrix.m[3] = 0;
  59384. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59385. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59386. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59387. this._rotMatrix.m[7] = 0;
  59388. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59389. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59390. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59391. this._rotMatrix.m[11] = 0;
  59392. this._rotMatrix.m[12] = 0;
  59393. this._rotMatrix.m[13] = 0;
  59394. this._rotMatrix.m[14] = 0;
  59395. this._rotMatrix.m[15] = 1.0;
  59396. };
  59397. /**
  59398. * Disposes the SPS.
  59399. */
  59400. SolidParticleSystem.prototype.dispose = function () {
  59401. this.mesh.dispose();
  59402. this.vars = null;
  59403. // drop references to internal big arrays for the GC
  59404. this._positions = null;
  59405. this._indices = null;
  59406. this._normals = null;
  59407. this._uvs = null;
  59408. this._colors = null;
  59409. this._indices32 = null;
  59410. this._positions32 = null;
  59411. this._normals32 = null;
  59412. this._fixedNormal32 = null;
  59413. this._uvs32 = null;
  59414. this._colors32 = null;
  59415. this.pickedParticles = null;
  59416. };
  59417. /**
  59418. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59419. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59420. * @returns the SPS.
  59421. */
  59422. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59423. if (!this._isVisibilityBoxLocked) {
  59424. this.mesh.refreshBoundingInfo();
  59425. }
  59426. return this;
  59427. };
  59428. /**
  59429. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59430. * @param size the size (float) of the visibility box
  59431. * note : this doesn't lock the SPS mesh bounding box.
  59432. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59433. */
  59434. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59435. var vis = size / 2;
  59436. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59437. };
  59438. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59439. /**
  59440. * Gets whether the SPS as always visible or not
  59441. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59442. */
  59443. get: function () {
  59444. return this._alwaysVisible;
  59445. },
  59446. /**
  59447. * Sets the SPS as always visible or not
  59448. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59449. */
  59450. set: function (val) {
  59451. this._alwaysVisible = val;
  59452. this.mesh.alwaysSelectAsActiveMesh = val;
  59453. },
  59454. enumerable: true,
  59455. configurable: true
  59456. });
  59457. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59458. /**
  59459. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59460. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59461. */
  59462. get: function () {
  59463. return this._isVisibilityBoxLocked;
  59464. },
  59465. /**
  59466. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59467. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59468. */
  59469. set: function (val) {
  59470. this._isVisibilityBoxLocked = val;
  59471. var boundingInfo = this.mesh.getBoundingInfo();
  59472. boundingInfo.isLocked = val;
  59473. },
  59474. enumerable: true,
  59475. configurable: true
  59476. });
  59477. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59478. /**
  59479. * Gets if `setParticles()` computes the particle rotations or not.
  59480. * Default value : true. The SPS is faster when it's set to false.
  59481. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59482. */
  59483. get: function () {
  59484. return this._computeParticleRotation;
  59485. },
  59486. /**
  59487. * Tells to `setParticles()` to compute the particle rotations or not.
  59488. * Default value : true. The SPS is faster when it's set to false.
  59489. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59490. */
  59491. set: function (val) {
  59492. this._computeParticleRotation = val;
  59493. },
  59494. enumerable: true,
  59495. configurable: true
  59496. });
  59497. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59498. /**
  59499. * Gets if `setParticles()` computes the particle colors or not.
  59500. * Default value : true. The SPS is faster when it's set to false.
  59501. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59502. */
  59503. get: function () {
  59504. return this._computeParticleColor;
  59505. },
  59506. /**
  59507. * Tells to `setParticles()` to compute the particle colors or not.
  59508. * Default value : true. The SPS is faster when it's set to false.
  59509. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59510. */
  59511. set: function (val) {
  59512. this._computeParticleColor = val;
  59513. },
  59514. enumerable: true,
  59515. configurable: true
  59516. });
  59517. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59518. /**
  59519. * Gets if `setParticles()` computes the particle textures or not.
  59520. * Default value : true. The SPS is faster when it's set to false.
  59521. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59522. */
  59523. get: function () {
  59524. return this._computeParticleTexture;
  59525. },
  59526. set: function (val) {
  59527. this._computeParticleTexture = val;
  59528. },
  59529. enumerable: true,
  59530. configurable: true
  59531. });
  59532. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59533. /**
  59534. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59535. * Default value : false. The SPS is faster when it's set to false.
  59536. * Note : the particle custom vertex positions aren't stored values.
  59537. */
  59538. get: function () {
  59539. return this._computeParticleVertex;
  59540. },
  59541. /**
  59542. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59543. * Default value : false. The SPS is faster when it's set to false.
  59544. * Note : the particle custom vertex positions aren't stored values.
  59545. */
  59546. set: function (val) {
  59547. this._computeParticleVertex = val;
  59548. },
  59549. enumerable: true,
  59550. configurable: true
  59551. });
  59552. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59553. /**
  59554. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59555. */
  59556. get: function () {
  59557. return this._computeBoundingBox;
  59558. },
  59559. /**
  59560. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59561. */
  59562. set: function (val) {
  59563. this._computeBoundingBox = val;
  59564. },
  59565. enumerable: true,
  59566. configurable: true
  59567. });
  59568. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59569. /**
  59570. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59571. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59572. * Default : `true`
  59573. */
  59574. get: function () {
  59575. return this._depthSortParticles;
  59576. },
  59577. /**
  59578. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59579. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59580. * Default : `true`
  59581. */
  59582. set: function (val) {
  59583. this._depthSortParticles = val;
  59584. },
  59585. enumerable: true,
  59586. configurable: true
  59587. });
  59588. // =======================================================================
  59589. // Particle behavior logic
  59590. // these following methods may be overwritten by the user to fit his needs
  59591. /**
  59592. * This function does nothing. It may be overwritten to set all the particle first values.
  59593. * The SPS doesn't call this function, you may have to call it by your own.
  59594. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59595. */
  59596. SolidParticleSystem.prototype.initParticles = function () {
  59597. };
  59598. /**
  59599. * This function does nothing. It may be overwritten to recycle a particle.
  59600. * The SPS doesn't call this function, you may have to call it by your own.
  59601. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59602. * @param particle The particle to recycle
  59603. * @returns the recycled particle
  59604. */
  59605. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59606. return particle;
  59607. };
  59608. /**
  59609. * Updates a particle : this function should be overwritten by the user.
  59610. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59611. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59612. * @example : just set a particle position or velocity and recycle conditions
  59613. * @param particle The particle to update
  59614. * @returns the updated particle
  59615. */
  59616. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59617. return particle;
  59618. };
  59619. /**
  59620. * Updates a vertex of a particle : it can be overwritten by the user.
  59621. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59622. * @param particle the current particle
  59623. * @param vertex the current index of the current particle
  59624. * @param pt the index of the current vertex in the particle shape
  59625. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59626. * @example : just set a vertex particle position
  59627. * @returns the updated vertex
  59628. */
  59629. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59630. return vertex;
  59631. };
  59632. /**
  59633. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59634. * This does nothing and may be overwritten by the user.
  59635. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59636. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59637. * @param update the boolean update value actually passed to setParticles()
  59638. */
  59639. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59640. };
  59641. /**
  59642. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59643. * This will be passed three parameters.
  59644. * This does nothing and may be overwritten by the user.
  59645. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59646. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59647. * @param update the boolean update value actually passed to setParticles()
  59648. */
  59649. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59650. };
  59651. return SolidParticleSystem;
  59652. }());
  59653. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59654. })(BABYLON || (BABYLON = {}));
  59655. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59656. var BABYLON;
  59657. (function (BABYLON) {
  59658. var ShaderMaterial = /** @class */ (function (_super) {
  59659. __extends(ShaderMaterial, _super);
  59660. function ShaderMaterial(name, scene, shaderPath, options) {
  59661. var _this = _super.call(this, name, scene) || this;
  59662. _this._textures = {};
  59663. _this._textureArrays = {};
  59664. _this._floats = {};
  59665. _this._ints = {};
  59666. _this._floatsArrays = {};
  59667. _this._colors3 = {};
  59668. _this._colors3Arrays = {};
  59669. _this._colors4 = {};
  59670. _this._vectors2 = {};
  59671. _this._vectors3 = {};
  59672. _this._vectors4 = {};
  59673. _this._matrices = {};
  59674. _this._matrices3x3 = {};
  59675. _this._matrices2x2 = {};
  59676. _this._vectors2Arrays = {};
  59677. _this._vectors3Arrays = {};
  59678. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59679. _this._shaderPath = shaderPath;
  59680. options.needAlphaBlending = options.needAlphaBlending || false;
  59681. options.needAlphaTesting = options.needAlphaTesting || false;
  59682. options.attributes = options.attributes || ["position", "normal", "uv"];
  59683. options.uniforms = options.uniforms || ["worldViewProjection"];
  59684. options.uniformBuffers = options.uniformBuffers || [];
  59685. options.samplers = options.samplers || [];
  59686. options.defines = options.defines || [];
  59687. _this._options = options;
  59688. return _this;
  59689. }
  59690. ShaderMaterial.prototype.getClassName = function () {
  59691. return "ShaderMaterial";
  59692. };
  59693. ShaderMaterial.prototype.needAlphaBlending = function () {
  59694. return this._options.needAlphaBlending;
  59695. };
  59696. ShaderMaterial.prototype.needAlphaTesting = function () {
  59697. return this._options.needAlphaTesting;
  59698. };
  59699. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59700. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59701. this._options.uniforms.push(uniformName);
  59702. }
  59703. };
  59704. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59705. if (this._options.samplers.indexOf(name) === -1) {
  59706. this._options.samplers.push(name);
  59707. }
  59708. this._textures[name] = texture;
  59709. return this;
  59710. };
  59711. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59712. if (this._options.samplers.indexOf(name) === -1) {
  59713. this._options.samplers.push(name);
  59714. }
  59715. this._checkUniform(name);
  59716. this._textureArrays[name] = textures;
  59717. return this;
  59718. };
  59719. ShaderMaterial.prototype.setFloat = function (name, value) {
  59720. this._checkUniform(name);
  59721. this._floats[name] = value;
  59722. return this;
  59723. };
  59724. ShaderMaterial.prototype.setInt = function (name, value) {
  59725. this._checkUniform(name);
  59726. this._ints[name] = value;
  59727. return this;
  59728. };
  59729. ShaderMaterial.prototype.setFloats = function (name, value) {
  59730. this._checkUniform(name);
  59731. this._floatsArrays[name] = value;
  59732. return this;
  59733. };
  59734. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59735. this._checkUniform(name);
  59736. this._colors3[name] = value;
  59737. return this;
  59738. };
  59739. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59740. this._checkUniform(name);
  59741. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59742. color.toArray(arr, arr.length);
  59743. return arr;
  59744. }, []);
  59745. return this;
  59746. };
  59747. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59748. this._checkUniform(name);
  59749. this._colors4[name] = value;
  59750. return this;
  59751. };
  59752. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59753. this._checkUniform(name);
  59754. this._vectors2[name] = value;
  59755. return this;
  59756. };
  59757. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59758. this._checkUniform(name);
  59759. this._vectors3[name] = value;
  59760. return this;
  59761. };
  59762. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59763. this._checkUniform(name);
  59764. this._vectors4[name] = value;
  59765. return this;
  59766. };
  59767. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59768. this._checkUniform(name);
  59769. this._matrices[name] = value;
  59770. return this;
  59771. };
  59772. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59773. this._checkUniform(name);
  59774. this._matrices3x3[name] = value;
  59775. return this;
  59776. };
  59777. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59778. this._checkUniform(name);
  59779. this._matrices2x2[name] = value;
  59780. return this;
  59781. };
  59782. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59783. this._checkUniform(name);
  59784. this._vectors2Arrays[name] = value;
  59785. return this;
  59786. };
  59787. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59788. this._checkUniform(name);
  59789. this._vectors3Arrays[name] = value;
  59790. return this;
  59791. };
  59792. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59793. if (!mesh) {
  59794. return true;
  59795. }
  59796. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59797. return false;
  59798. }
  59799. return false;
  59800. };
  59801. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59802. var scene = this.getScene();
  59803. var engine = scene.getEngine();
  59804. if (!this.checkReadyOnEveryCall) {
  59805. if (this._renderId === scene.getRenderId()) {
  59806. if (this._checkCache(scene, mesh, useInstances)) {
  59807. return true;
  59808. }
  59809. }
  59810. }
  59811. // Instances
  59812. var defines = [];
  59813. var attribs = [];
  59814. var fallbacks = new BABYLON.EffectFallbacks();
  59815. if (useInstances) {
  59816. defines.push("#define INSTANCES");
  59817. }
  59818. for (var index = 0; index < this._options.defines.length; index++) {
  59819. defines.push(this._options.defines[index]);
  59820. }
  59821. for (var index = 0; index < this._options.attributes.length; index++) {
  59822. attribs.push(this._options.attributes[index]);
  59823. }
  59824. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59825. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59826. defines.push("#define VERTEXCOLOR");
  59827. }
  59828. // Bones
  59829. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59830. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59831. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59832. if (mesh.numBoneInfluencers > 4) {
  59833. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59834. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59835. }
  59836. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59837. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59838. fallbacks.addCPUSkinningFallback(0, mesh);
  59839. if (this._options.uniforms.indexOf("mBones") === -1) {
  59840. this._options.uniforms.push("mBones");
  59841. }
  59842. }
  59843. else {
  59844. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59845. }
  59846. // Textures
  59847. for (var name in this._textures) {
  59848. if (!this._textures[name].isReady()) {
  59849. return false;
  59850. }
  59851. }
  59852. // Alpha test
  59853. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59854. defines.push("#define ALPHATEST");
  59855. }
  59856. var previousEffect = this._effect;
  59857. var join = defines.join("\n");
  59858. this._effect = engine.createEffect(this._shaderPath, {
  59859. attributes: attribs,
  59860. uniformsNames: this._options.uniforms,
  59861. uniformBuffersNames: this._options.uniformBuffers,
  59862. samplers: this._options.samplers,
  59863. defines: join,
  59864. fallbacks: fallbacks,
  59865. onCompiled: this.onCompiled,
  59866. onError: this.onError
  59867. }, engine);
  59868. if (!this._effect.isReady()) {
  59869. return false;
  59870. }
  59871. if (previousEffect !== this._effect) {
  59872. scene.resetCachedMaterial();
  59873. }
  59874. this._renderId = scene.getRenderId();
  59875. return true;
  59876. };
  59877. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59878. var scene = this.getScene();
  59879. if (!this._effect) {
  59880. return;
  59881. }
  59882. if (this._options.uniforms.indexOf("world") !== -1) {
  59883. this._effect.setMatrix("world", world);
  59884. }
  59885. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59886. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59887. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59888. }
  59889. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59890. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59891. }
  59892. };
  59893. ShaderMaterial.prototype.bind = function (world, mesh) {
  59894. // Std values
  59895. this.bindOnlyWorldMatrix(world);
  59896. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59897. if (this._options.uniforms.indexOf("view") !== -1) {
  59898. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59899. }
  59900. if (this._options.uniforms.indexOf("projection") !== -1) {
  59901. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59902. }
  59903. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59904. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59905. }
  59906. // Bones
  59907. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59908. var name;
  59909. // Texture
  59910. for (name in this._textures) {
  59911. this._effect.setTexture(name, this._textures[name]);
  59912. }
  59913. // Texture arrays
  59914. for (name in this._textureArrays) {
  59915. this._effect.setTextureArray(name, this._textureArrays[name]);
  59916. }
  59917. // Int
  59918. for (name in this._ints) {
  59919. this._effect.setInt(name, this._ints[name]);
  59920. }
  59921. // Float
  59922. for (name in this._floats) {
  59923. this._effect.setFloat(name, this._floats[name]);
  59924. }
  59925. // Floats
  59926. for (name in this._floatsArrays) {
  59927. this._effect.setArray(name, this._floatsArrays[name]);
  59928. }
  59929. // Color3
  59930. for (name in this._colors3) {
  59931. this._effect.setColor3(name, this._colors3[name]);
  59932. }
  59933. for (name in this._colors3Arrays) {
  59934. this._effect.setArray3(name, this._colors3Arrays[name]);
  59935. }
  59936. // Color4
  59937. for (name in this._colors4) {
  59938. var color = this._colors4[name];
  59939. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59940. }
  59941. // Vector2
  59942. for (name in this._vectors2) {
  59943. this._effect.setVector2(name, this._vectors2[name]);
  59944. }
  59945. // Vector3
  59946. for (name in this._vectors3) {
  59947. this._effect.setVector3(name, this._vectors3[name]);
  59948. }
  59949. // Vector4
  59950. for (name in this._vectors4) {
  59951. this._effect.setVector4(name, this._vectors4[name]);
  59952. }
  59953. // Matrix
  59954. for (name in this._matrices) {
  59955. this._effect.setMatrix(name, this._matrices[name]);
  59956. }
  59957. // Matrix 3x3
  59958. for (name in this._matrices3x3) {
  59959. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59960. }
  59961. // Matrix 2x2
  59962. for (name in this._matrices2x2) {
  59963. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59964. }
  59965. // Vector2Array
  59966. for (name in this._vectors2Arrays) {
  59967. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59968. }
  59969. // Vector3Array
  59970. for (name in this._vectors3Arrays) {
  59971. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59972. }
  59973. }
  59974. this._afterBind(mesh);
  59975. };
  59976. ShaderMaterial.prototype.getActiveTextures = function () {
  59977. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59978. for (var name in this._textures) {
  59979. activeTextures.push(this._textures[name]);
  59980. }
  59981. for (var name in this._textureArrays) {
  59982. var array = this._textureArrays[name];
  59983. for (var index = 0; index < array.length; index++) {
  59984. activeTextures.push(array[index]);
  59985. }
  59986. }
  59987. return activeTextures;
  59988. };
  59989. ShaderMaterial.prototype.hasTexture = function (texture) {
  59990. if (_super.prototype.hasTexture.call(this, texture)) {
  59991. return true;
  59992. }
  59993. for (var name in this._textures) {
  59994. if (this._textures[name] === texture) {
  59995. return true;
  59996. }
  59997. }
  59998. for (var name in this._textureArrays) {
  59999. var array = this._textureArrays[name];
  60000. for (var index = 0; index < array.length; index++) {
  60001. if (array[index] === texture) {
  60002. return true;
  60003. }
  60004. }
  60005. }
  60006. return false;
  60007. };
  60008. ShaderMaterial.prototype.clone = function (name) {
  60009. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60010. return newShaderMaterial;
  60011. };
  60012. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60013. if (forceDisposeTextures) {
  60014. var name;
  60015. for (name in this._textures) {
  60016. this._textures[name].dispose();
  60017. }
  60018. for (name in this._textureArrays) {
  60019. var array = this._textureArrays[name];
  60020. for (var index = 0; index < array.length; index++) {
  60021. array[index].dispose();
  60022. }
  60023. }
  60024. }
  60025. this._textures = {};
  60026. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60027. };
  60028. ShaderMaterial.prototype.serialize = function () {
  60029. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60030. serializationObject.customType = "BABYLON.ShaderMaterial";
  60031. serializationObject.options = this._options;
  60032. serializationObject.shaderPath = this._shaderPath;
  60033. var name;
  60034. // Texture
  60035. serializationObject.textures = {};
  60036. for (name in this._textures) {
  60037. serializationObject.textures[name] = this._textures[name].serialize();
  60038. }
  60039. // Texture arrays
  60040. serializationObject.textureArrays = {};
  60041. for (name in this._textureArrays) {
  60042. serializationObject.textureArrays[name] = [];
  60043. var array = this._textureArrays[name];
  60044. for (var index = 0; index < array.length; index++) {
  60045. serializationObject.textureArrays[name].push(array[index].serialize());
  60046. }
  60047. }
  60048. // Float
  60049. serializationObject.floats = {};
  60050. for (name in this._floats) {
  60051. serializationObject.floats[name] = this._floats[name];
  60052. }
  60053. // Float s
  60054. serializationObject.FloatArrays = {};
  60055. for (name in this._floatsArrays) {
  60056. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60057. }
  60058. // Color3
  60059. serializationObject.colors3 = {};
  60060. for (name in this._colors3) {
  60061. serializationObject.colors3[name] = this._colors3[name].asArray();
  60062. }
  60063. // Color3 array
  60064. serializationObject.colors3Arrays = {};
  60065. for (name in this._colors3Arrays) {
  60066. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60067. }
  60068. // Color4
  60069. serializationObject.colors4 = {};
  60070. for (name in this._colors4) {
  60071. serializationObject.colors4[name] = this._colors4[name].asArray();
  60072. }
  60073. // Vector2
  60074. serializationObject.vectors2 = {};
  60075. for (name in this._vectors2) {
  60076. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60077. }
  60078. // Vector3
  60079. serializationObject.vectors3 = {};
  60080. for (name in this._vectors3) {
  60081. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60082. }
  60083. // Vector4
  60084. serializationObject.vectors4 = {};
  60085. for (name in this._vectors4) {
  60086. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60087. }
  60088. // Matrix
  60089. serializationObject.matrices = {};
  60090. for (name in this._matrices) {
  60091. serializationObject.matrices[name] = this._matrices[name].asArray();
  60092. }
  60093. // Matrix 3x3
  60094. serializationObject.matrices3x3 = {};
  60095. for (name in this._matrices3x3) {
  60096. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60097. }
  60098. // Matrix 2x2
  60099. serializationObject.matrices2x2 = {};
  60100. for (name in this._matrices2x2) {
  60101. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60102. }
  60103. // Vector2Array
  60104. serializationObject.vectors2Arrays = {};
  60105. for (name in this._vectors2Arrays) {
  60106. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60107. }
  60108. // Vector3Array
  60109. serializationObject.vectors3Arrays = {};
  60110. for (name in this._vectors3Arrays) {
  60111. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60112. }
  60113. return serializationObject;
  60114. };
  60115. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60116. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60117. var name;
  60118. // Texture
  60119. for (name in source.textures) {
  60120. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60121. }
  60122. // Texture arrays
  60123. for (name in source.textureArrays) {
  60124. var array = source.textureArrays[name];
  60125. var textureArray = new Array();
  60126. for (var index = 0; index < array.length; index++) {
  60127. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60128. }
  60129. material.setTextureArray(name, textureArray);
  60130. }
  60131. // Float
  60132. for (name in source.floats) {
  60133. material.setFloat(name, source.floats[name]);
  60134. }
  60135. // Float s
  60136. for (name in source.floatsArrays) {
  60137. material.setFloats(name, source.floatsArrays[name]);
  60138. }
  60139. // Color3
  60140. for (name in source.colors3) {
  60141. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60142. }
  60143. // Color3 arrays
  60144. for (name in source.colors3Arrays) {
  60145. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60146. if (i % 3 === 0) {
  60147. arr.push([num]);
  60148. }
  60149. else {
  60150. arr[arr.length - 1].push(num);
  60151. }
  60152. return arr;
  60153. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60154. material.setColor3Array(name, colors);
  60155. }
  60156. // Color4
  60157. for (name in source.colors4) {
  60158. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60159. }
  60160. // Vector2
  60161. for (name in source.vectors2) {
  60162. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60163. }
  60164. // Vector3
  60165. for (name in source.vectors3) {
  60166. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60167. }
  60168. // Vector4
  60169. for (name in source.vectors4) {
  60170. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60171. }
  60172. // Matrix
  60173. for (name in source.matrices) {
  60174. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60175. }
  60176. // Matrix 3x3
  60177. for (name in source.matrices3x3) {
  60178. material.setMatrix3x3(name, source.matrices3x3[name]);
  60179. }
  60180. // Matrix 2x2
  60181. for (name in source.matrices2x2) {
  60182. material.setMatrix2x2(name, source.matrices2x2[name]);
  60183. }
  60184. // Vector2Array
  60185. for (name in source.vectors2Arrays) {
  60186. material.setArray2(name, source.vectors2Arrays[name]);
  60187. }
  60188. // Vector3Array
  60189. for (name in source.vectors3Arrays) {
  60190. material.setArray3(name, source.vectors3Arrays[name]);
  60191. }
  60192. return material;
  60193. };
  60194. return ShaderMaterial;
  60195. }(BABYLON.Material));
  60196. BABYLON.ShaderMaterial = ShaderMaterial;
  60197. })(BABYLON || (BABYLON = {}));
  60198. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60199. var BABYLON;
  60200. (function (BABYLON) {
  60201. var GroundMesh = /** @class */ (function (_super) {
  60202. __extends(GroundMesh, _super);
  60203. function GroundMesh(name, scene) {
  60204. var _this = _super.call(this, name, scene) || this;
  60205. _this.generateOctree = false;
  60206. return _this;
  60207. }
  60208. GroundMesh.prototype.getClassName = function () {
  60209. return "GroundMesh";
  60210. };
  60211. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60212. get: function () {
  60213. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60214. },
  60215. enumerable: true,
  60216. configurable: true
  60217. });
  60218. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60219. get: function () {
  60220. return this._subdivisionsX;
  60221. },
  60222. enumerable: true,
  60223. configurable: true
  60224. });
  60225. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60226. get: function () {
  60227. return this._subdivisionsY;
  60228. },
  60229. enumerable: true,
  60230. configurable: true
  60231. });
  60232. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60233. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60234. this._subdivisionsX = chunksCount;
  60235. this._subdivisionsY = chunksCount;
  60236. this.subdivide(chunksCount);
  60237. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60238. };
  60239. /**
  60240. * Returns a height (y) value in the Worl system :
  60241. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60242. * Returns the ground y position if (x, z) are outside the ground surface.
  60243. */
  60244. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60245. var world = this.getWorldMatrix();
  60246. var invMat = BABYLON.Tmp.Matrix[5];
  60247. world.invertToRef(invMat);
  60248. var tmpVect = BABYLON.Tmp.Vector3[8];
  60249. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60250. x = tmpVect.x;
  60251. z = tmpVect.z;
  60252. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60253. return this.position.y;
  60254. }
  60255. if (!this._heightQuads || this._heightQuads.length == 0) {
  60256. this._initHeightQuads();
  60257. this._computeHeightQuads();
  60258. }
  60259. var facet = this._getFacetAt(x, z);
  60260. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60261. // return y in the World system
  60262. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60263. return tmpVect.y;
  60264. };
  60265. /**
  60266. * Returns a normalized vector (Vector3) orthogonal to the ground
  60267. * at the ground coordinates (x, z) expressed in the World system.
  60268. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60269. */
  60270. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60271. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60272. this.getNormalAtCoordinatesToRef(x, z, normal);
  60273. return normal;
  60274. };
  60275. /**
  60276. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60277. * at the ground coordinates (x, z) expressed in the World system.
  60278. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60279. * Returns the GroundMesh.
  60280. */
  60281. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60282. var world = this.getWorldMatrix();
  60283. var tmpMat = BABYLON.Tmp.Matrix[5];
  60284. world.invertToRef(tmpMat);
  60285. var tmpVect = BABYLON.Tmp.Vector3[8];
  60286. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60287. x = tmpVect.x;
  60288. z = tmpVect.z;
  60289. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60290. return this;
  60291. }
  60292. if (!this._heightQuads || this._heightQuads.length == 0) {
  60293. this._initHeightQuads();
  60294. this._computeHeightQuads();
  60295. }
  60296. var facet = this._getFacetAt(x, z);
  60297. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60298. return this;
  60299. };
  60300. /**
  60301. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60302. * if the ground has been updated.
  60303. * This can be used in the render loop.
  60304. * Returns the GroundMesh.
  60305. */
  60306. GroundMesh.prototype.updateCoordinateHeights = function () {
  60307. if (!this._heightQuads || this._heightQuads.length == 0) {
  60308. this._initHeightQuads();
  60309. }
  60310. this._computeHeightQuads();
  60311. return this;
  60312. };
  60313. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60314. GroundMesh.prototype._getFacetAt = function (x, z) {
  60315. // retrieve col and row from x, z coordinates in the ground local system
  60316. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60317. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60318. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60319. var facet;
  60320. if (z < quad.slope.x * x + quad.slope.y) {
  60321. facet = quad.facet1;
  60322. }
  60323. else {
  60324. facet = quad.facet2;
  60325. }
  60326. return facet;
  60327. };
  60328. // Creates and populates the heightMap array with "facet" elements :
  60329. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60330. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60331. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60332. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60333. // Returns the GroundMesh.
  60334. GroundMesh.prototype._initHeightQuads = function () {
  60335. var subdivisionsX = this._subdivisionsX;
  60336. var subdivisionsY = this._subdivisionsY;
  60337. this._heightQuads = new Array();
  60338. for (var row = 0; row < subdivisionsY; row++) {
  60339. for (var col = 0; col < subdivisionsX; col++) {
  60340. 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) };
  60341. this._heightQuads[row * subdivisionsX + col] = quad;
  60342. }
  60343. }
  60344. return this;
  60345. };
  60346. // Compute each quad element values and update the the heightMap array :
  60347. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60348. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60349. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60350. // Returns the GroundMesh.
  60351. GroundMesh.prototype._computeHeightQuads = function () {
  60352. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60353. if (!positions) {
  60354. return this;
  60355. }
  60356. var v1 = BABYLON.Tmp.Vector3[3];
  60357. var v2 = BABYLON.Tmp.Vector3[2];
  60358. var v3 = BABYLON.Tmp.Vector3[1];
  60359. var v4 = BABYLON.Tmp.Vector3[0];
  60360. var v1v2 = BABYLON.Tmp.Vector3[4];
  60361. var v1v3 = BABYLON.Tmp.Vector3[5];
  60362. var v1v4 = BABYLON.Tmp.Vector3[6];
  60363. var norm1 = BABYLON.Tmp.Vector3[7];
  60364. var norm2 = BABYLON.Tmp.Vector3[8];
  60365. var i = 0;
  60366. var j = 0;
  60367. var k = 0;
  60368. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60369. var h = 0;
  60370. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60371. var d2 = 0;
  60372. var subdivisionsX = this._subdivisionsX;
  60373. var subdivisionsY = this._subdivisionsY;
  60374. for (var row = 0; row < subdivisionsY; row++) {
  60375. for (var col = 0; col < subdivisionsX; col++) {
  60376. i = col * 3;
  60377. j = row * (subdivisionsX + 1) * 3;
  60378. k = (row + 1) * (subdivisionsX + 1) * 3;
  60379. v1.x = positions[j + i];
  60380. v1.y = positions[j + i + 1];
  60381. v1.z = positions[j + i + 2];
  60382. v2.x = positions[j + i + 3];
  60383. v2.y = positions[j + i + 4];
  60384. v2.z = positions[j + i + 5];
  60385. v3.x = positions[k + i];
  60386. v3.y = positions[k + i + 1];
  60387. v3.z = positions[k + i + 2];
  60388. v4.x = positions[k + i + 3];
  60389. v4.y = positions[k + i + 4];
  60390. v4.z = positions[k + i + 5];
  60391. // 2D slope V1V4
  60392. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60393. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60394. // facet equations :
  60395. // we compute each facet normal vector
  60396. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60397. // we compute the value d by applying the equation to v1 which belongs to the plane
  60398. // then we store the facet equation in a Vector4
  60399. v2.subtractToRef(v1, v1v2);
  60400. v3.subtractToRef(v1, v1v3);
  60401. v4.subtractToRef(v1, v1v4);
  60402. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60403. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60404. norm1.normalize();
  60405. norm2.normalize();
  60406. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60407. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60408. var quad = this._heightQuads[row * subdivisionsX + col];
  60409. quad.slope.copyFromFloats(cd, h);
  60410. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60411. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60412. }
  60413. }
  60414. return this;
  60415. };
  60416. GroundMesh.prototype.serialize = function (serializationObject) {
  60417. _super.prototype.serialize.call(this, serializationObject);
  60418. serializationObject.subdivisionsX = this._subdivisionsX;
  60419. serializationObject.subdivisionsY = this._subdivisionsY;
  60420. serializationObject.minX = this._minX;
  60421. serializationObject.maxX = this._maxX;
  60422. serializationObject.minZ = this._minZ;
  60423. serializationObject.maxZ = this._maxZ;
  60424. serializationObject.width = this._width;
  60425. serializationObject.height = this._height;
  60426. };
  60427. GroundMesh.Parse = function (parsedMesh, scene) {
  60428. var result = new GroundMesh(parsedMesh.name, scene);
  60429. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60430. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60431. result._minX = parsedMesh.minX;
  60432. result._maxX = parsedMesh.maxX;
  60433. result._minZ = parsedMesh.minZ;
  60434. result._maxZ = parsedMesh.maxZ;
  60435. result._width = parsedMesh.width;
  60436. result._height = parsedMesh.height;
  60437. return result;
  60438. };
  60439. return GroundMesh;
  60440. }(BABYLON.Mesh));
  60441. BABYLON.GroundMesh = GroundMesh;
  60442. })(BABYLON || (BABYLON = {}));
  60443. //# sourceMappingURL=babylon.groundMesh.js.map
  60444. var BABYLON;
  60445. (function (BABYLON) {
  60446. /**
  60447. * Creates an instance based on a source mesh.
  60448. */
  60449. var InstancedMesh = /** @class */ (function (_super) {
  60450. __extends(InstancedMesh, _super);
  60451. function InstancedMesh(name, source) {
  60452. var _this = _super.call(this, name, source.getScene()) || this;
  60453. source.instances.push(_this);
  60454. _this._sourceMesh = source;
  60455. _this.position.copyFrom(source.position);
  60456. _this.rotation.copyFrom(source.rotation);
  60457. _this.scaling.copyFrom(source.scaling);
  60458. if (source.rotationQuaternion) {
  60459. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60460. }
  60461. _this.infiniteDistance = source.infiniteDistance;
  60462. _this.setPivotMatrix(source.getPivotMatrix());
  60463. _this.refreshBoundingInfo();
  60464. _this._syncSubMeshes();
  60465. return _this;
  60466. }
  60467. /**
  60468. * Returns the string "InstancedMesh".
  60469. */
  60470. InstancedMesh.prototype.getClassName = function () {
  60471. return "InstancedMesh";
  60472. };
  60473. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60474. // Methods
  60475. get: function () {
  60476. return this._sourceMesh.receiveShadows;
  60477. },
  60478. enumerable: true,
  60479. configurable: true
  60480. });
  60481. Object.defineProperty(InstancedMesh.prototype, "material", {
  60482. get: function () {
  60483. return this._sourceMesh.material;
  60484. },
  60485. enumerable: true,
  60486. configurable: true
  60487. });
  60488. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60489. get: function () {
  60490. return this._sourceMesh.visibility;
  60491. },
  60492. enumerable: true,
  60493. configurable: true
  60494. });
  60495. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60496. get: function () {
  60497. return this._sourceMesh.skeleton;
  60498. },
  60499. enumerable: true,
  60500. configurable: true
  60501. });
  60502. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60503. get: function () {
  60504. return this._sourceMesh.renderingGroupId;
  60505. },
  60506. set: function (value) {
  60507. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60508. return;
  60509. }
  60510. //no-op with warning
  60511. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60512. },
  60513. enumerable: true,
  60514. configurable: true
  60515. });
  60516. /**
  60517. * Returns the total number of vertices (integer).
  60518. */
  60519. InstancedMesh.prototype.getTotalVertices = function () {
  60520. return this._sourceMesh.getTotalVertices();
  60521. };
  60522. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60523. get: function () {
  60524. return this._sourceMesh;
  60525. },
  60526. enumerable: true,
  60527. configurable: true
  60528. });
  60529. /**
  60530. * Is this node ready to be used/rendered
  60531. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60532. * @return {boolean} is it ready
  60533. */
  60534. InstancedMesh.prototype.isReady = function (completeCheck) {
  60535. if (completeCheck === void 0) { completeCheck = false; }
  60536. return this._sourceMesh.isReady(completeCheck, true);
  60537. };
  60538. /**
  60539. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60540. */
  60541. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60542. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60543. };
  60544. /**
  60545. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60546. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60547. * The `data` are either a numeric array either a Float32Array.
  60548. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60549. * 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).
  60550. * Note that a new underlying VertexBuffer object is created each call.
  60551. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60552. *
  60553. * Possible `kind` values :
  60554. * - BABYLON.VertexBuffer.PositionKind
  60555. * - BABYLON.VertexBuffer.UVKind
  60556. * - BABYLON.VertexBuffer.UV2Kind
  60557. * - BABYLON.VertexBuffer.UV3Kind
  60558. * - BABYLON.VertexBuffer.UV4Kind
  60559. * - BABYLON.VertexBuffer.UV5Kind
  60560. * - BABYLON.VertexBuffer.UV6Kind
  60561. * - BABYLON.VertexBuffer.ColorKind
  60562. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60563. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60564. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60565. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60566. *
  60567. * Returns the Mesh.
  60568. */
  60569. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60570. if (this.sourceMesh) {
  60571. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60572. }
  60573. return this.sourceMesh;
  60574. };
  60575. /**
  60576. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60577. * If the mesh has no geometry, it is simply returned as it is.
  60578. * The `data` are either a numeric array either a Float32Array.
  60579. * No new underlying VertexBuffer object is created.
  60580. * 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.
  60581. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60582. *
  60583. * Possible `kind` values :
  60584. * - BABYLON.VertexBuffer.PositionKind
  60585. * - BABYLON.VertexBuffer.UVKind
  60586. * - BABYLON.VertexBuffer.UV2Kind
  60587. * - BABYLON.VertexBuffer.UV3Kind
  60588. * - BABYLON.VertexBuffer.UV4Kind
  60589. * - BABYLON.VertexBuffer.UV5Kind
  60590. * - BABYLON.VertexBuffer.UV6Kind
  60591. * - BABYLON.VertexBuffer.ColorKind
  60592. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60593. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60594. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60595. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60596. *
  60597. * Returns the Mesh.
  60598. */
  60599. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60600. if (this.sourceMesh) {
  60601. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60602. }
  60603. return this.sourceMesh;
  60604. };
  60605. /**
  60606. * Sets the mesh indices.
  60607. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60608. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60609. * This method creates a new index buffer each call.
  60610. * Returns the Mesh.
  60611. */
  60612. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60613. if (totalVertices === void 0) { totalVertices = null; }
  60614. if (this.sourceMesh) {
  60615. this.sourceMesh.setIndices(indices, totalVertices);
  60616. }
  60617. return this.sourceMesh;
  60618. };
  60619. /**
  60620. * Boolean : True if the mesh owns the requested kind of data.
  60621. */
  60622. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60623. return this._sourceMesh.isVerticesDataPresent(kind);
  60624. };
  60625. /**
  60626. * Returns an array of indices (IndicesArray).
  60627. */
  60628. InstancedMesh.prototype.getIndices = function () {
  60629. return this._sourceMesh.getIndices();
  60630. };
  60631. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60632. get: function () {
  60633. return this._sourceMesh._positions;
  60634. },
  60635. enumerable: true,
  60636. configurable: true
  60637. });
  60638. /**
  60639. * Sets a new updated BoundingInfo to the mesh.
  60640. * Returns the mesh.
  60641. */
  60642. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60643. var meshBB = this._sourceMesh.getBoundingInfo();
  60644. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60645. this._updateBoundingInfo();
  60646. return this;
  60647. };
  60648. InstancedMesh.prototype._preActivate = function () {
  60649. if (this._currentLOD) {
  60650. this._currentLOD._preActivate();
  60651. }
  60652. return this;
  60653. };
  60654. InstancedMesh.prototype._activate = function (renderId) {
  60655. if (this._currentLOD) {
  60656. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60657. }
  60658. return this;
  60659. };
  60660. /**
  60661. * Returns the current associated LOD AbstractMesh.
  60662. */
  60663. InstancedMesh.prototype.getLOD = function (camera) {
  60664. if (!camera) {
  60665. return this;
  60666. }
  60667. var boundingInfo = this.getBoundingInfo();
  60668. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60669. if (this._currentLOD === this.sourceMesh) {
  60670. return this;
  60671. }
  60672. return this._currentLOD;
  60673. };
  60674. InstancedMesh.prototype._syncSubMeshes = function () {
  60675. this.releaseSubMeshes();
  60676. if (this._sourceMesh.subMeshes) {
  60677. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60678. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60679. }
  60680. }
  60681. return this;
  60682. };
  60683. InstancedMesh.prototype._generatePointsArray = function () {
  60684. return this._sourceMesh._generatePointsArray();
  60685. };
  60686. /**
  60687. * Creates a new InstancedMesh from the current mesh.
  60688. * - name (string) : the cloned mesh name
  60689. * - newParent (optional Node) : the optional Node to parent the clone to.
  60690. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60691. *
  60692. * Returns the clone.
  60693. */
  60694. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60695. var result = this._sourceMesh.createInstance(name);
  60696. // Deep copy
  60697. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60698. // Bounding info
  60699. this.refreshBoundingInfo();
  60700. // Parent
  60701. if (newParent) {
  60702. result.parent = newParent;
  60703. }
  60704. if (!doNotCloneChildren) {
  60705. // Children
  60706. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60707. var mesh = this.getScene().meshes[index];
  60708. if (mesh.parent === this) {
  60709. mesh.clone(mesh.name, result);
  60710. }
  60711. }
  60712. }
  60713. result.computeWorldMatrix(true);
  60714. return result;
  60715. };
  60716. /**
  60717. * Disposes the InstancedMesh.
  60718. * Returns nothing.
  60719. */
  60720. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60721. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60722. // Remove from mesh
  60723. var index = this._sourceMesh.instances.indexOf(this);
  60724. this._sourceMesh.instances.splice(index, 1);
  60725. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60726. };
  60727. return InstancedMesh;
  60728. }(BABYLON.AbstractMesh));
  60729. BABYLON.InstancedMesh = InstancedMesh;
  60730. })(BABYLON || (BABYLON = {}));
  60731. //# sourceMappingURL=babylon.instancedMesh.js.map
  60732. var BABYLON;
  60733. (function (BABYLON) {
  60734. var LinesMesh = /** @class */ (function (_super) {
  60735. __extends(LinesMesh, _super);
  60736. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60737. if (scene === void 0) { scene = null; }
  60738. if (parent === void 0) { parent = null; }
  60739. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60740. _this.useVertexColor = useVertexColor;
  60741. _this.useVertexAlpha = useVertexAlpha;
  60742. _this.color = new BABYLON.Color3(1, 1, 1);
  60743. _this.alpha = 1;
  60744. if (source) {
  60745. _this.color = source.color.clone();
  60746. _this.alpha = source.alpha;
  60747. _this.useVertexColor = source.useVertexColor;
  60748. _this.useVertexAlpha = source.useVertexAlpha;
  60749. }
  60750. _this._intersectionThreshold = 0.1;
  60751. var defines = [];
  60752. var options = {
  60753. attributes: [BABYLON.VertexBuffer.PositionKind],
  60754. uniforms: ["world", "viewProjection"],
  60755. needAlphaBlending: true,
  60756. defines: defines
  60757. };
  60758. if (useVertexAlpha === false) {
  60759. options.needAlphaBlending = false;
  60760. }
  60761. if (!useVertexColor) {
  60762. options.uniforms.push("color");
  60763. }
  60764. else {
  60765. options.defines.push("#define VERTEXCOLOR");
  60766. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60767. }
  60768. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60769. return _this;
  60770. }
  60771. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60772. /**
  60773. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60774. * This margin is expressed in world space coordinates, so its value may vary.
  60775. * Default value is 0.1
  60776. * @returns the intersection Threshold value.
  60777. */
  60778. get: function () {
  60779. return this._intersectionThreshold;
  60780. },
  60781. /**
  60782. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60783. * This margin is expressed in world space coordinates, so its value may vary.
  60784. * @param value the new threshold to apply
  60785. */
  60786. set: function (value) {
  60787. if (this._intersectionThreshold === value) {
  60788. return;
  60789. }
  60790. this._intersectionThreshold = value;
  60791. if (this.geometry) {
  60792. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60793. }
  60794. },
  60795. enumerable: true,
  60796. configurable: true
  60797. });
  60798. /**
  60799. * Returns the string "LineMesh"
  60800. */
  60801. LinesMesh.prototype.getClassName = function () {
  60802. return "LinesMesh";
  60803. };
  60804. Object.defineProperty(LinesMesh.prototype, "material", {
  60805. get: function () {
  60806. return this._colorShader;
  60807. },
  60808. set: function (value) {
  60809. // Do nothing
  60810. },
  60811. enumerable: true,
  60812. configurable: true
  60813. });
  60814. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60815. get: function () {
  60816. return false;
  60817. },
  60818. enumerable: true,
  60819. configurable: true
  60820. });
  60821. LinesMesh.prototype.createInstance = function (name) {
  60822. throw new Error("LinesMeshes do not support createInstance.");
  60823. };
  60824. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60825. if (!this._geometry) {
  60826. return this;
  60827. }
  60828. // VBOs
  60829. this._geometry._bind(this._colorShader.getEffect());
  60830. // Color
  60831. if (!this.useVertexColor) {
  60832. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60833. }
  60834. return this;
  60835. };
  60836. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60837. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60838. return this;
  60839. }
  60840. var engine = this.getScene().getEngine();
  60841. // Draw order
  60842. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60843. return this;
  60844. };
  60845. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60846. this._colorShader.dispose();
  60847. _super.prototype.dispose.call(this, doNotRecurse);
  60848. };
  60849. /**
  60850. * Returns a new LineMesh object cloned from the current one.
  60851. */
  60852. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60853. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60854. };
  60855. return LinesMesh;
  60856. }(BABYLON.Mesh));
  60857. BABYLON.LinesMesh = LinesMesh;
  60858. })(BABYLON || (BABYLON = {}));
  60859. //# sourceMappingURL=babylon.linesMesh.js.map
  60860. var BABYLON;
  60861. (function (BABYLON) {
  60862. /**
  60863. * Class containing static functions to help procedurally build meshes
  60864. */
  60865. var MeshBuilder = /** @class */ (function () {
  60866. function MeshBuilder() {
  60867. }
  60868. MeshBuilder.updateSideOrientation = function (orientation) {
  60869. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60870. return BABYLON.Mesh.DOUBLESIDE;
  60871. }
  60872. if (orientation === undefined || orientation === null) {
  60873. return BABYLON.Mesh.FRONTSIDE;
  60874. }
  60875. return orientation;
  60876. };
  60877. /**
  60878. * Creates a box mesh
  60879. * * The parameter `size` sets the size (float) of each box side (default 1)
  60880. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60881. * * 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)
  60882. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60883. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60884. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60885. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60886. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60887. * @param name defines the name of the mesh
  60888. * @param options defines the options used to create the mesh
  60889. * @param scene defines the hosting scene
  60890. * @returns the box mesh
  60891. */
  60892. MeshBuilder.CreateBox = function (name, options, scene) {
  60893. if (scene === void 0) { scene = null; }
  60894. var box = new BABYLON.Mesh(name, scene);
  60895. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60896. box._originalBuilderSideOrientation = options.sideOrientation;
  60897. var vertexData = BABYLON.VertexData.CreateBox(options);
  60898. vertexData.applyToMesh(box, options.updatable);
  60899. return box;
  60900. };
  60901. /**
  60902. * Creates a sphere mesh
  60903. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60904. * * 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`)
  60905. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60906. * * 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
  60907. * * 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)
  60908. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60909. * * 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
  60910. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60911. * @param name defines the name of the mesh
  60912. * @param options defines the options used to create the mesh
  60913. * @param scene defines the hosting scene
  60914. * @returns the sphere mesh
  60915. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60916. */
  60917. MeshBuilder.CreateSphere = function (name, options, scene) {
  60918. var sphere = new BABYLON.Mesh(name, scene);
  60919. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60920. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60921. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60922. vertexData.applyToMesh(sphere, options.updatable);
  60923. return sphere;
  60924. };
  60925. /**
  60926. * Creates a plane polygonal mesh. By default, this is a disc
  60927. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60928. * * 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
  60929. * * 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
  60930. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60931. * * 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
  60932. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60933. * @param name defines the name of the mesh
  60934. * @param options defines the options used to create the mesh
  60935. * @param scene defines the hosting scene
  60936. * @returns the plane polygonal mesh
  60937. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60938. */
  60939. MeshBuilder.CreateDisc = function (name, options, scene) {
  60940. if (scene === void 0) { scene = null; }
  60941. var disc = new BABYLON.Mesh(name, scene);
  60942. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60943. disc._originalBuilderSideOrientation = options.sideOrientation;
  60944. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60945. vertexData.applyToMesh(disc, options.updatable);
  60946. return disc;
  60947. };
  60948. /**
  60949. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60950. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60951. * * 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`)
  60952. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60953. * * 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
  60954. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60955. * * 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
  60956. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60957. * @param name defines the name of the mesh
  60958. * @param options defines the options used to create the mesh
  60959. * @param scene defines the hosting scene
  60960. * @returns the icosahedron mesh
  60961. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60962. */
  60963. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60964. var sphere = new BABYLON.Mesh(name, scene);
  60965. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60966. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60967. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60968. vertexData.applyToMesh(sphere, options.updatable);
  60969. return sphere;
  60970. };
  60971. ;
  60972. /**
  60973. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60974. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60975. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60976. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60977. * * 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
  60978. * * 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
  60979. * * 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
  60980. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60981. * * 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
  60982. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60983. * * 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
  60984. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60985. * * 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
  60986. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60987. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60988. * @param name defines the name of the mesh
  60989. * @param options defines the options used to create the mesh
  60990. * @param scene defines the hosting scene
  60991. * @returns the ribbon mesh
  60992. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60993. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60994. */
  60995. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60996. if (scene === void 0) { scene = null; }
  60997. var pathArray = options.pathArray;
  60998. var closeArray = options.closeArray;
  60999. var closePath = options.closePath;
  61000. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61001. var instance = options.instance;
  61002. var updatable = options.updatable;
  61003. if (instance) { // existing ribbon instance update
  61004. // positionFunction : ribbon case
  61005. // only pathArray and sideOrientation parameters are taken into account for positions update
  61006. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61007. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61008. var positionFunction = function (positions) {
  61009. var minlg = pathArray[0].length;
  61010. var i = 0;
  61011. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61012. for (var si = 1; si <= ns; si++) {
  61013. for (var p = 0; p < pathArray.length; p++) {
  61014. var path = pathArray[p];
  61015. var l = path.length;
  61016. minlg = (minlg < l) ? minlg : l;
  61017. var j = 0;
  61018. while (j < minlg) {
  61019. positions[i] = path[j].x;
  61020. positions[i + 1] = path[j].y;
  61021. positions[i + 2] = path[j].z;
  61022. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61023. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61024. }
  61025. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61026. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61027. }
  61028. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61029. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61030. }
  61031. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61032. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61033. }
  61034. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61035. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61036. }
  61037. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61038. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61039. }
  61040. j++;
  61041. i += 3;
  61042. }
  61043. if (instance._closePath) {
  61044. positions[i] = path[0].x;
  61045. positions[i + 1] = path[0].y;
  61046. positions[i + 2] = path[0].z;
  61047. i += 3;
  61048. }
  61049. }
  61050. }
  61051. };
  61052. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61053. positionFunction(positions);
  61054. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61055. instance._boundingInfo.update(instance._worldMatrix);
  61056. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61057. if (options.colors) {
  61058. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61059. for (var c = 0; c < options.colors.length; c++) {
  61060. colors[c * 4] = options.colors[c].r;
  61061. colors[c * 4 + 1] = options.colors[c].g;
  61062. colors[c * 4 + 2] = options.colors[c].b;
  61063. colors[c * 4 + 3] = options.colors[c].a;
  61064. }
  61065. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61066. }
  61067. if (options.uvs) {
  61068. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61069. for (var i = 0; i < options.uvs.length; i++) {
  61070. uvs[i * 2] = options.uvs[i].x;
  61071. uvs[i * 2 + 1] = options.uvs[i].y;
  61072. }
  61073. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61074. }
  61075. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61076. var indices = instance.getIndices();
  61077. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61078. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61079. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61080. if (instance._closePath) {
  61081. var indexFirst = 0;
  61082. var indexLast = 0;
  61083. for (var p = 0; p < pathArray.length; p++) {
  61084. indexFirst = instance._idx[p] * 3;
  61085. if (p + 1 < pathArray.length) {
  61086. indexLast = (instance._idx[p + 1] - 1) * 3;
  61087. }
  61088. else {
  61089. indexLast = normals.length - 3;
  61090. }
  61091. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61092. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61093. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61094. normals[indexLast] = normals[indexFirst];
  61095. normals[indexLast + 1] = normals[indexFirst + 1];
  61096. normals[indexLast + 2] = normals[indexFirst + 2];
  61097. }
  61098. }
  61099. if (!(instance.areNormalsFrozen)) {
  61100. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61101. }
  61102. }
  61103. return instance;
  61104. }
  61105. else { // new ribbon creation
  61106. var ribbon = new BABYLON.Mesh(name, scene);
  61107. ribbon._originalBuilderSideOrientation = sideOrientation;
  61108. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61109. if (closePath) {
  61110. ribbon._idx = vertexData._idx;
  61111. }
  61112. ribbon._closePath = closePath;
  61113. ribbon._closeArray = closeArray;
  61114. vertexData.applyToMesh(ribbon, updatable);
  61115. return ribbon;
  61116. }
  61117. };
  61118. /**
  61119. * Creates a cylinder or a cone mesh
  61120. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61121. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61122. * * 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.
  61123. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61124. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61125. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61126. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61127. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61128. * * 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).
  61129. * * 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
  61130. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61131. * * 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
  61132. * * 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.
  61133. * * If `enclose` is false, a ring surface is one element.
  61134. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61135. * * 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
  61136. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61137. * * 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
  61138. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61139. * @param name defines the name of the mesh
  61140. * @param options defines the options used to create the mesh
  61141. * @param scene defines the hosting scene
  61142. * @returns the cylinder mesh
  61143. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61144. */
  61145. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61146. var cylinder = new BABYLON.Mesh(name, scene);
  61147. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61148. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61149. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61150. vertexData.applyToMesh(cylinder, options.updatable);
  61151. return cylinder;
  61152. };
  61153. /**
  61154. * Creates a torus mesh
  61155. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61156. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61157. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61158. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61159. * * 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
  61160. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61161. * @param name defines the name of the mesh
  61162. * @param options defines the options used to create the mesh
  61163. * @param scene defines the hosting scene
  61164. * @returns the torus mesh
  61165. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61166. */
  61167. MeshBuilder.CreateTorus = function (name, options, scene) {
  61168. var torus = new BABYLON.Mesh(name, scene);
  61169. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61170. torus._originalBuilderSideOrientation = options.sideOrientation;
  61171. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61172. vertexData.applyToMesh(torus, options.updatable);
  61173. return torus;
  61174. };
  61175. /**
  61176. * Creates a torus knot mesh
  61177. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61178. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61179. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61180. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61181. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61182. * * 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
  61183. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61184. * @param name defines the name of the mesh
  61185. * @param options defines the options used to create the mesh
  61186. * @param scene defines the hosting scene
  61187. * @returns the torus knot mesh
  61188. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61189. */
  61190. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61191. var torusKnot = new BABYLON.Mesh(name, scene);
  61192. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61193. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61194. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61195. vertexData.applyToMesh(torusKnot, options.updatable);
  61196. return torusKnot;
  61197. };
  61198. /**
  61199. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61200. * * 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
  61201. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61202. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61203. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61204. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61205. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61206. * * 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
  61207. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61208. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61209. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61210. * @param name defines the name of the new line system
  61211. * @param options defines the options used to create the line system
  61212. * @param scene defines the hosting scene
  61213. * @returns a new line system mesh
  61214. */
  61215. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61216. var instance = options.instance;
  61217. var lines = options.lines;
  61218. var colors = options.colors;
  61219. if (instance) { // lines update
  61220. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61221. var vertexColor;
  61222. var lineColors;
  61223. if (colors) {
  61224. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61225. }
  61226. var i = 0;
  61227. var c = 0;
  61228. for (var l = 0; l < lines.length; l++) {
  61229. var points = lines[l];
  61230. for (var p = 0; p < points.length; p++) {
  61231. positions[i] = points[p].x;
  61232. positions[i + 1] = points[p].y;
  61233. positions[i + 2] = points[p].z;
  61234. if (colors && vertexColor) {
  61235. lineColors = colors[l];
  61236. vertexColor[c] = lineColors[p].r;
  61237. vertexColor[c + 1] = lineColors[p].g;
  61238. vertexColor[c + 2] = lineColors[p].b;
  61239. vertexColor[c + 3] = lineColors[p].a;
  61240. c += 4;
  61241. }
  61242. i += 3;
  61243. }
  61244. }
  61245. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61246. if (colors && vertexColor) {
  61247. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61248. }
  61249. return instance;
  61250. }
  61251. // line system creation
  61252. var useVertexColor = (colors) ? true : false;
  61253. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61254. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61255. vertexData.applyToMesh(lineSystem, options.updatable);
  61256. return lineSystem;
  61257. };
  61258. /**
  61259. * Creates a line mesh
  61260. * 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
  61261. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61262. * * The parameter `points` is an array successive Vector3
  61263. * * 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
  61264. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61265. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61266. * * When updating an instance, remember that only point positions can change, not the number of points
  61267. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61268. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61269. * @param name defines the name of the new line system
  61270. * @param options defines the options used to create the line system
  61271. * @param scene defines the hosting scene
  61272. * @returns a new line mesh
  61273. */
  61274. MeshBuilder.CreateLines = function (name, options, scene) {
  61275. if (scene === void 0) { scene = null; }
  61276. var colors = (options.colors) ? [options.colors] : null;
  61277. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61278. return lines;
  61279. };
  61280. /**
  61281. * Creates a dashed line mesh
  61282. * * 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
  61283. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61284. * * The parameter `points` is an array successive Vector3
  61285. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61286. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61287. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61288. * * 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
  61289. * * When updating an instance, remember that only point positions can change, not the number of points
  61290. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61291. * @param name defines the name of the mesh
  61292. * @param options defines the options used to create the mesh
  61293. * @param scene defines the hosting scene
  61294. * @returns the dashed line mesh
  61295. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61296. */
  61297. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61298. if (scene === void 0) { scene = null; }
  61299. var points = options.points;
  61300. var instance = options.instance;
  61301. var gapSize = options.gapSize || 1;
  61302. var dashSize = options.dashSize || 3;
  61303. if (instance) { // dashed lines update
  61304. var positionFunction = function (positions) {
  61305. var curvect = BABYLON.Vector3.Zero();
  61306. var nbSeg = positions.length / 6;
  61307. var lg = 0;
  61308. var nb = 0;
  61309. var shft = 0;
  61310. var dashshft = 0;
  61311. var curshft = 0;
  61312. var p = 0;
  61313. var i = 0;
  61314. var j = 0;
  61315. for (i = 0; i < points.length - 1; i++) {
  61316. points[i + 1].subtractToRef(points[i], curvect);
  61317. lg += curvect.length();
  61318. }
  61319. shft = lg / nbSeg;
  61320. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61321. for (i = 0; i < points.length - 1; i++) {
  61322. points[i + 1].subtractToRef(points[i], curvect);
  61323. nb = Math.floor(curvect.length() / shft);
  61324. curvect.normalize();
  61325. j = 0;
  61326. while (j < nb && p < positions.length) {
  61327. curshft = shft * j;
  61328. positions[p] = points[i].x + curshft * curvect.x;
  61329. positions[p + 1] = points[i].y + curshft * curvect.y;
  61330. positions[p + 2] = points[i].z + curshft * curvect.z;
  61331. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61332. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61333. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61334. p += 6;
  61335. j++;
  61336. }
  61337. }
  61338. while (p < positions.length) {
  61339. positions[p] = points[i].x;
  61340. positions[p + 1] = points[i].y;
  61341. positions[p + 2] = points[i].z;
  61342. p += 3;
  61343. }
  61344. };
  61345. instance.updateMeshPositions(positionFunction, false);
  61346. return instance;
  61347. }
  61348. // dashed lines creation
  61349. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61350. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61351. vertexData.applyToMesh(dashedLines, options.updatable);
  61352. dashedLines.dashSize = dashSize;
  61353. dashedLines.gapSize = gapSize;
  61354. return dashedLines;
  61355. };
  61356. /**
  61357. * 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.
  61358. * * 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.
  61359. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61360. * * 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.
  61361. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61362. * * 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
  61363. * * 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
  61364. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61365. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61366. * * 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
  61367. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61368. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61369. * @param name defines the name of the mesh
  61370. * @param options defines the options used to create the mesh
  61371. * @param scene defines the hosting scene
  61372. * @returns the extruded shape mesh
  61373. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61374. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61375. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61376. */
  61377. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61378. if (scene === void 0) { scene = null; }
  61379. var path = options.path;
  61380. var shape = options.shape;
  61381. var scale = options.scale || 1;
  61382. var rotation = options.rotation || 0;
  61383. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61384. var updatable = options.updatable;
  61385. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61386. var instance = options.instance || null;
  61387. var invertUV = options.invertUV || false;
  61388. 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);
  61389. };
  61390. /**
  61391. * Creates an custom extruded shape mesh.
  61392. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61393. * * 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.
  61394. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61395. * * 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
  61396. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61397. * * 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
  61398. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61399. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61400. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61401. * * 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
  61402. * * 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
  61403. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61404. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61405. * * 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
  61406. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61407. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61408. * @param name defines the name of the mesh
  61409. * @param options defines the options used to create the mesh
  61410. * @param scene defines the hosting scene
  61411. * @returns the custom extruded shape mesh
  61412. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61413. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61414. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61415. */
  61416. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61417. var path = options.path;
  61418. var shape = options.shape;
  61419. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61420. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61421. var ribbonCloseArray = options.ribbonCloseArray || false;
  61422. var ribbonClosePath = options.ribbonClosePath || false;
  61423. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61424. var updatable = options.updatable;
  61425. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61426. var instance = options.instance;
  61427. var invertUV = options.invertUV || false;
  61428. 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);
  61429. };
  61430. /**
  61431. * Creates lathe mesh.
  61432. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61433. * * 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
  61434. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61435. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61436. * * 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
  61437. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61438. * * 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
  61439. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61440. * * 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
  61441. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61442. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61443. * @param name defines the name of the mesh
  61444. * @param options defines the options used to create the mesh
  61445. * @param scene defines the hosting scene
  61446. * @returns the lathe mesh
  61447. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61448. */
  61449. MeshBuilder.CreateLathe = function (name, options, scene) {
  61450. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61451. var closed = (options.closed === undefined) ? true : options.closed;
  61452. var shape = options.shape;
  61453. var radius = options.radius || 1;
  61454. var tessellation = options.tessellation || 64;
  61455. var updatable = options.updatable;
  61456. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61457. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61458. var pi2 = Math.PI * 2;
  61459. var paths = new Array();
  61460. var invertUV = options.invertUV || false;
  61461. var i = 0;
  61462. var p = 0;
  61463. var step = pi2 / tessellation * arc;
  61464. var rotated;
  61465. var path = new Array();
  61466. for (i = 0; i <= tessellation; i++) {
  61467. var path = [];
  61468. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61469. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61470. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61471. }
  61472. for (p = 0; p < shape.length; p++) {
  61473. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61474. path.push(rotated);
  61475. }
  61476. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61477. 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));
  61478. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61479. }
  61480. paths.push(path);
  61481. }
  61482. // lathe ribbon
  61483. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61484. return lathe;
  61485. };
  61486. /**
  61487. * Creates a plane mesh
  61488. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61489. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61490. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61491. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61492. * * 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
  61493. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61494. * @param name defines the name of the mesh
  61495. * @param options defines the options used to create the mesh
  61496. * @param scene defines the hosting scene
  61497. * @returns the plane mesh
  61498. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61499. */
  61500. MeshBuilder.CreatePlane = function (name, options, scene) {
  61501. var plane = new BABYLON.Mesh(name, scene);
  61502. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61503. plane._originalBuilderSideOrientation = options.sideOrientation;
  61504. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61505. vertexData.applyToMesh(plane, options.updatable);
  61506. if (options.sourcePlane) {
  61507. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61508. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61509. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61510. plane.rotate(vectorProduct, product);
  61511. }
  61512. return plane;
  61513. };
  61514. /**
  61515. * Creates a ground mesh
  61516. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61517. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61518. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61519. * @param name defines the name of the mesh
  61520. * @param options defines the options used to create the mesh
  61521. * @param scene defines the hosting scene
  61522. * @returns the ground mesh
  61523. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61524. */
  61525. MeshBuilder.CreateGround = function (name, options, scene) {
  61526. var ground = new BABYLON.GroundMesh(name, scene);
  61527. ground._setReady(false);
  61528. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61529. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61530. ground._width = options.width || 1;
  61531. ground._height = options.height || 1;
  61532. ground._maxX = ground._width / 2;
  61533. ground._maxZ = ground._height / 2;
  61534. ground._minX = -ground._maxX;
  61535. ground._minZ = -ground._maxZ;
  61536. var vertexData = BABYLON.VertexData.CreateGround(options);
  61537. vertexData.applyToMesh(ground, options.updatable);
  61538. ground._setReady(true);
  61539. return ground;
  61540. };
  61541. /**
  61542. * Creates a tiled ground mesh
  61543. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61544. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61545. * * 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
  61546. * * 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
  61547. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61548. * @param name defines the name of the mesh
  61549. * @param options defines the options used to create the mesh
  61550. * @param scene defines the hosting scene
  61551. * @returns the tiled ground mesh
  61552. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61553. */
  61554. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61555. var tiledGround = new BABYLON.Mesh(name, scene);
  61556. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61557. vertexData.applyToMesh(tiledGround, options.updatable);
  61558. return tiledGround;
  61559. };
  61560. /**
  61561. * Creates a ground mesh from a height map
  61562. * * The parameter `url` sets the URL of the height map image resource.
  61563. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61564. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61565. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61566. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61567. * * 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.
  61568. * * 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).
  61569. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61570. * @param name defines the name of the mesh
  61571. * @param url defines the url to the height map
  61572. * @param options defines the options used to create the mesh
  61573. * @param scene defines the hosting scene
  61574. * @returns the ground mesh
  61575. * @see http://doc.babylonjs.com/babylon101/height_map
  61576. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61577. */
  61578. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61579. var width = options.width || 10.0;
  61580. var height = options.height || 10.0;
  61581. var subdivisions = options.subdivisions || 1 | 0;
  61582. var minHeight = options.minHeight || 0.0;
  61583. var maxHeight = options.maxHeight || 1.0;
  61584. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61585. var updatable = options.updatable;
  61586. var onReady = options.onReady;
  61587. var ground = new BABYLON.GroundMesh(name, scene);
  61588. ground._subdivisionsX = subdivisions;
  61589. ground._subdivisionsY = subdivisions;
  61590. ground._width = width;
  61591. ground._height = height;
  61592. ground._maxX = ground._width / 2.0;
  61593. ground._maxZ = ground._height / 2.0;
  61594. ground._minX = -ground._maxX;
  61595. ground._minZ = -ground._maxZ;
  61596. ground._setReady(false);
  61597. var onload = function (img) {
  61598. // Getting height map data
  61599. var canvas = document.createElement("canvas");
  61600. var context = canvas.getContext("2d");
  61601. if (!context) {
  61602. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61603. }
  61604. if (scene.isDisposed) {
  61605. return;
  61606. }
  61607. var bufferWidth = img.width;
  61608. var bufferHeight = img.height;
  61609. canvas.width = bufferWidth;
  61610. canvas.height = bufferHeight;
  61611. context.drawImage(img, 0, 0);
  61612. // Create VertexData from map data
  61613. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61614. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61615. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61616. width: width, height: height,
  61617. subdivisions: subdivisions,
  61618. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61619. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61620. });
  61621. vertexData.applyToMesh(ground, updatable);
  61622. //execute ready callback, if set
  61623. if (onReady) {
  61624. onReady(ground);
  61625. }
  61626. ground._setReady(true);
  61627. };
  61628. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61629. return ground;
  61630. };
  61631. /**
  61632. * Creates a polygon mesh
  61633. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61634. * * 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
  61635. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61636. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61637. * * 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)
  61638. * * Remember you can only change the shape positions, not their number when updating a polygon
  61639. * @param name defines the name of the mesh
  61640. * @param options defines the options used to create the mesh
  61641. * @param scene defines the hosting scene
  61642. * @returns the polygon mesh
  61643. */
  61644. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61645. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61646. var shape = options.shape;
  61647. var holes = options.holes || [];
  61648. var depth = options.depth || 0;
  61649. var contours = [];
  61650. var hole = [];
  61651. for (var i = 0; i < shape.length; i++) {
  61652. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61653. }
  61654. var epsilon = 0.00000001;
  61655. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61656. contours.pop();
  61657. }
  61658. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61659. for (var hNb = 0; hNb < holes.length; hNb++) {
  61660. hole = [];
  61661. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61662. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61663. }
  61664. polygonTriangulation.addHole(hole);
  61665. }
  61666. var polygon = polygonTriangulation.build(options.updatable, depth);
  61667. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61668. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61669. vertexData.applyToMesh(polygon, options.updatable);
  61670. return polygon;
  61671. };
  61672. ;
  61673. /**
  61674. * Creates an extruded polygon mesh, with depth in the Y direction.
  61675. * * 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)
  61676. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61677. * @param name defines the name of the mesh
  61678. * @param options defines the options used to create the mesh
  61679. * @param scene defines the hosting scene
  61680. * @returns the polygon mesh
  61681. */
  61682. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61683. return MeshBuilder.CreatePolygon(name, options, scene);
  61684. };
  61685. ;
  61686. /**
  61687. * Creates a tube mesh.
  61688. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61689. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61690. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61691. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61692. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61693. * * 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)
  61694. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61695. * * 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
  61696. * * 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
  61697. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61698. * * 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
  61699. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61700. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61701. * @param name defines the name of the mesh
  61702. * @param options defines the options used to create the mesh
  61703. * @param scene defines the hosting scene
  61704. * @returns the tube mesh
  61705. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61706. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61707. */
  61708. MeshBuilder.CreateTube = function (name, options, scene) {
  61709. var path = options.path;
  61710. var instance = options.instance;
  61711. var radius = 1.0;
  61712. if (instance) {
  61713. radius = instance.radius;
  61714. }
  61715. if (options.radius !== undefined) {
  61716. radius = options.radius;
  61717. }
  61718. ;
  61719. var tessellation = options.tessellation || 64 | 0;
  61720. var radiusFunction = options.radiusFunction || null;
  61721. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61722. var invertUV = options.invertUV || false;
  61723. var updatable = options.updatable;
  61724. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61725. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61726. // tube geometry
  61727. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61728. var tangents = path3D.getTangents();
  61729. var normals = path3D.getNormals();
  61730. var distances = path3D.getDistances();
  61731. var pi2 = Math.PI * 2;
  61732. var step = pi2 / tessellation * arc;
  61733. var returnRadius = function () { return radius; };
  61734. var radiusFunctionFinal = radiusFunction || returnRadius;
  61735. var circlePath;
  61736. var rad;
  61737. var normal;
  61738. var rotated;
  61739. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61740. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61741. for (var i = 0; i < path.length; i++) {
  61742. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61743. circlePath = Array(); // current circle array
  61744. normal = normals[i]; // current normal
  61745. for (var t = 0; t < tessellation; t++) {
  61746. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61747. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61748. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61749. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61750. circlePath[t] = rotated;
  61751. }
  61752. circlePaths[index] = circlePath;
  61753. index++;
  61754. }
  61755. // cap
  61756. var capPath = function (nbPoints, pathIndex) {
  61757. var pointCap = Array();
  61758. for (var i = 0; i < nbPoints; i++) {
  61759. pointCap.push(path[pathIndex]);
  61760. }
  61761. return pointCap;
  61762. };
  61763. switch (cap) {
  61764. case BABYLON.Mesh.NO_CAP:
  61765. break;
  61766. case BABYLON.Mesh.CAP_START:
  61767. circlePaths[0] = capPath(tessellation, 0);
  61768. circlePaths[1] = circlePaths[2].slice(0);
  61769. break;
  61770. case BABYLON.Mesh.CAP_END:
  61771. circlePaths[index] = circlePaths[index - 1].slice(0);
  61772. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61773. break;
  61774. case BABYLON.Mesh.CAP_ALL:
  61775. circlePaths[0] = capPath(tessellation, 0);
  61776. circlePaths[1] = circlePaths[2].slice(0);
  61777. circlePaths[index] = circlePaths[index - 1].slice(0);
  61778. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61779. break;
  61780. default:
  61781. break;
  61782. }
  61783. return circlePaths;
  61784. };
  61785. var path3D;
  61786. var pathArray;
  61787. if (instance) { // tube update
  61788. var arc = options.arc || instance.arc;
  61789. path3D = (instance.path3D).update(path);
  61790. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61791. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61792. instance.path3D = path3D;
  61793. instance.pathArray = pathArray;
  61794. instance.arc = arc;
  61795. instance.radius = radius;
  61796. return instance;
  61797. }
  61798. // tube creation
  61799. path3D = new BABYLON.Path3D(path);
  61800. var newPathArray = new Array();
  61801. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61802. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61803. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61804. tube.pathArray = pathArray;
  61805. tube.path3D = path3D;
  61806. tube.tessellation = tessellation;
  61807. tube.cap = cap;
  61808. tube.arc = options.arc;
  61809. tube.radius = radius;
  61810. return tube;
  61811. };
  61812. /**
  61813. * Creates a polyhedron mesh
  61814. * * 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
  61815. * * The parameter `size` (positive float, default 1) sets the polygon size
  61816. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61817. * * 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`
  61818. * * 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
  61819. * * 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)`)
  61820. * * 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
  61821. * * 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
  61822. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61823. * * 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
  61824. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61825. * @param name defines the name of the mesh
  61826. * @param options defines the options used to create the mesh
  61827. * @param scene defines the hosting scene
  61828. * @returns the polyhedron mesh
  61829. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61830. */
  61831. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61832. var polyhedron = new BABYLON.Mesh(name, scene);
  61833. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61834. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61835. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61836. vertexData.applyToMesh(polyhedron, options.updatable);
  61837. return polyhedron;
  61838. };
  61839. /**
  61840. * Creates a decal mesh.
  61841. * 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
  61842. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61843. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61844. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61845. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61846. * @param name defines the name of the mesh
  61847. * @param sourceMesh defines the mesh where the decal must be applied
  61848. * @param options defines the options used to create the mesh
  61849. * @param scene defines the hosting scene
  61850. * @returns the decal mesh
  61851. * @see http://doc.babylonjs.com/how_to/decals
  61852. */
  61853. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61854. var indices = sourceMesh.getIndices();
  61855. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61856. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61857. var position = options.position || BABYLON.Vector3.Zero();
  61858. var normal = options.normal || BABYLON.Vector3.Up();
  61859. var size = options.size || BABYLON.Vector3.One();
  61860. var angle = options.angle || 0;
  61861. // Getting correct rotation
  61862. if (!normal) {
  61863. var target = new BABYLON.Vector3(0, 0, 1);
  61864. var camera = sourceMesh.getScene().activeCamera;
  61865. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61866. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61867. }
  61868. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61869. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61870. var pitch = Math.atan2(normal.y, len);
  61871. // Matrix
  61872. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61873. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61874. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61875. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61876. var vertexData = new BABYLON.VertexData();
  61877. vertexData.indices = [];
  61878. vertexData.positions = [];
  61879. vertexData.normals = [];
  61880. vertexData.uvs = [];
  61881. var currentVertexDataIndex = 0;
  61882. var extractDecalVector3 = function (indexId) {
  61883. var result = new BABYLON.PositionNormalVertex();
  61884. if (!indices || !positions || !normals) {
  61885. return result;
  61886. }
  61887. var vertexId = indices[indexId];
  61888. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61889. // Send vector to decal local world
  61890. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61891. // Get normal
  61892. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61893. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61894. return result;
  61895. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61896. var clip = function (vertices, axis) {
  61897. if (vertices.length === 0) {
  61898. return vertices;
  61899. }
  61900. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61901. var clipVertices = function (v0, v1) {
  61902. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61903. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61904. };
  61905. var result = new Array();
  61906. for (var index = 0; index < vertices.length; index += 3) {
  61907. var v1Out;
  61908. var v2Out;
  61909. var v3Out;
  61910. var total = 0;
  61911. var nV1 = null;
  61912. var nV2 = null;
  61913. var nV3 = null;
  61914. var nV4 = null;
  61915. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61916. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61917. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61918. v1Out = d1 > 0;
  61919. v2Out = d2 > 0;
  61920. v3Out = d3 > 0;
  61921. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61922. switch (total) {
  61923. case 0:
  61924. result.push(vertices[index]);
  61925. result.push(vertices[index + 1]);
  61926. result.push(vertices[index + 2]);
  61927. break;
  61928. case 1:
  61929. if (v1Out) {
  61930. nV1 = vertices[index + 1];
  61931. nV2 = vertices[index + 2];
  61932. nV3 = clipVertices(vertices[index], nV1);
  61933. nV4 = clipVertices(vertices[index], nV2);
  61934. }
  61935. if (v2Out) {
  61936. nV1 = vertices[index];
  61937. nV2 = vertices[index + 2];
  61938. nV3 = clipVertices(vertices[index + 1], nV1);
  61939. nV4 = clipVertices(vertices[index + 1], nV2);
  61940. result.push(nV3);
  61941. result.push(nV2.clone());
  61942. result.push(nV1.clone());
  61943. result.push(nV2.clone());
  61944. result.push(nV3.clone());
  61945. result.push(nV4);
  61946. break;
  61947. }
  61948. if (v3Out) {
  61949. nV1 = vertices[index];
  61950. nV2 = vertices[index + 1];
  61951. nV3 = clipVertices(vertices[index + 2], nV1);
  61952. nV4 = clipVertices(vertices[index + 2], nV2);
  61953. }
  61954. if (nV1 && nV2 && nV3 && nV4) {
  61955. result.push(nV1.clone());
  61956. result.push(nV2.clone());
  61957. result.push(nV3);
  61958. result.push(nV4);
  61959. result.push(nV3.clone());
  61960. result.push(nV2.clone());
  61961. }
  61962. break;
  61963. case 2:
  61964. if (!v1Out) {
  61965. nV1 = vertices[index].clone();
  61966. nV2 = clipVertices(nV1, vertices[index + 1]);
  61967. nV3 = clipVertices(nV1, vertices[index + 2]);
  61968. result.push(nV1);
  61969. result.push(nV2);
  61970. result.push(nV3);
  61971. }
  61972. if (!v2Out) {
  61973. nV1 = vertices[index + 1].clone();
  61974. nV2 = clipVertices(nV1, vertices[index + 2]);
  61975. nV3 = clipVertices(nV1, vertices[index]);
  61976. result.push(nV1);
  61977. result.push(nV2);
  61978. result.push(nV3);
  61979. }
  61980. if (!v3Out) {
  61981. nV1 = vertices[index + 2].clone();
  61982. nV2 = clipVertices(nV1, vertices[index]);
  61983. nV3 = clipVertices(nV1, vertices[index + 1]);
  61984. result.push(nV1);
  61985. result.push(nV2);
  61986. result.push(nV3);
  61987. }
  61988. break;
  61989. case 3:
  61990. break;
  61991. }
  61992. }
  61993. return result;
  61994. };
  61995. for (var index = 0; index < indices.length; index += 3) {
  61996. var faceVertices = new Array();
  61997. faceVertices.push(extractDecalVector3(index));
  61998. faceVertices.push(extractDecalVector3(index + 1));
  61999. faceVertices.push(extractDecalVector3(index + 2));
  62000. // Clip
  62001. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62002. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62003. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62004. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62005. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62006. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62007. if (faceVertices.length === 0) {
  62008. continue;
  62009. }
  62010. // Add UVs and get back to world
  62011. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62012. var vertex = faceVertices[vIndex];
  62013. //TODO check for Int32Array | Uint32Array | Uint16Array
  62014. vertexData.indices.push(currentVertexDataIndex);
  62015. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62016. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62017. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62018. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62019. currentVertexDataIndex++;
  62020. }
  62021. }
  62022. // Return mesh
  62023. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62024. vertexData.applyToMesh(decal);
  62025. decal.position = position.clone();
  62026. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62027. return decal;
  62028. };
  62029. // Privates
  62030. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62031. // extrusion geometry
  62032. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62033. var tangents = path3D.getTangents();
  62034. var normals = path3D.getNormals();
  62035. var binormals = path3D.getBinormals();
  62036. var distances = path3D.getDistances();
  62037. var angle = 0;
  62038. var returnScale = function () { return scale !== null ? scale : 1; };
  62039. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62040. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62041. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62042. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62043. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62044. for (var i = 0; i < curve.length; i++) {
  62045. var shapePath = new Array();
  62046. var angleStep = rotate(i, distances[i]);
  62047. var scaleRatio = scl(i, distances[i]);
  62048. for (var p = 0; p < shape.length; p++) {
  62049. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62050. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62051. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62052. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62053. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62054. shapePath[p] = rotated;
  62055. }
  62056. shapePaths[index] = shapePath;
  62057. angle += angleStep;
  62058. index++;
  62059. }
  62060. // cap
  62061. var capPath = function (shapePath) {
  62062. var pointCap = Array();
  62063. var barycenter = BABYLON.Vector3.Zero();
  62064. var i;
  62065. for (i = 0; i < shapePath.length; i++) {
  62066. barycenter.addInPlace(shapePath[i]);
  62067. }
  62068. barycenter.scaleInPlace(1.0 / shapePath.length);
  62069. for (i = 0; i < shapePath.length; i++) {
  62070. pointCap.push(barycenter);
  62071. }
  62072. return pointCap;
  62073. };
  62074. switch (cap) {
  62075. case BABYLON.Mesh.NO_CAP:
  62076. break;
  62077. case BABYLON.Mesh.CAP_START:
  62078. shapePaths[0] = capPath(shapePaths[2]);
  62079. shapePaths[1] = shapePaths[2];
  62080. break;
  62081. case BABYLON.Mesh.CAP_END:
  62082. shapePaths[index] = shapePaths[index - 1];
  62083. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62084. break;
  62085. case BABYLON.Mesh.CAP_ALL:
  62086. shapePaths[0] = capPath(shapePaths[2]);
  62087. shapePaths[1] = shapePaths[2];
  62088. shapePaths[index] = shapePaths[index - 1];
  62089. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62090. break;
  62091. default:
  62092. break;
  62093. }
  62094. return shapePaths;
  62095. };
  62096. var path3D;
  62097. var pathArray;
  62098. if (instance) { // instance update
  62099. path3D = (instance.path3D).update(curve);
  62100. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62101. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62102. return instance;
  62103. }
  62104. // extruded shape creation
  62105. path3D = new BABYLON.Path3D(curve);
  62106. var newShapePaths = new Array();
  62107. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62108. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62109. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62110. extrudedGeneric.pathArray = pathArray;
  62111. extrudedGeneric.path3D = path3D;
  62112. extrudedGeneric.cap = cap;
  62113. return extrudedGeneric;
  62114. };
  62115. return MeshBuilder;
  62116. }());
  62117. BABYLON.MeshBuilder = MeshBuilder;
  62118. })(BABYLON || (BABYLON = {}));
  62119. //# sourceMappingURL=babylon.meshBuilder.js.map
  62120. var BABYLON;
  62121. (function (BABYLON) {
  62122. /**
  62123. * Draco compression (https://google.github.io/draco/)
  62124. *
  62125. * This class wraps the Draco module.
  62126. *
  62127. * **Encoder**
  62128. *
  62129. * The encoder is not currently implemented.
  62130. *
  62131. * **Decoder**
  62132. *
  62133. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62134. *
  62135. * To update the configuration, use the following code:
  62136. * ```javascript
  62137. * BABYLON.DracoCompression.Configuration = {
  62138. * decoder: {
  62139. * wasmUrl: "<url to the WebAssembly library>",
  62140. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62141. * fallbackUrl: "<url to the fallback JavaScript library>",
  62142. * }
  62143. * };
  62144. * ```
  62145. *
  62146. * 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.
  62147. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62148. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62149. *
  62150. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62151. * ```javascript
  62152. * var dracoCompression = new BABYLON.DracoCompression();
  62153. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62154. * [BABYLON.VertexBuffer.PositionKind]: 0
  62155. * });
  62156. * ```
  62157. *
  62158. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62159. */
  62160. var DracoCompression = /** @class */ (function () {
  62161. /**
  62162. * Constructor
  62163. */
  62164. function DracoCompression() {
  62165. }
  62166. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62167. /**
  62168. * Returns true if the decoder is available.
  62169. */
  62170. get: function () {
  62171. if (typeof DracoDecoderModule !== "undefined") {
  62172. return true;
  62173. }
  62174. var decoder = DracoCompression.Configuration.decoder;
  62175. if (decoder) {
  62176. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62177. return true;
  62178. }
  62179. if (decoder.fallbackUrl) {
  62180. return true;
  62181. }
  62182. }
  62183. return false;
  62184. },
  62185. enumerable: true,
  62186. configurable: true
  62187. });
  62188. /**
  62189. * Stop all async operations and release resources.
  62190. */
  62191. DracoCompression.prototype.dispose = function () {
  62192. };
  62193. /**
  62194. * Decode Draco compressed mesh data to vertex data.
  62195. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62196. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62197. * @returns A promise that resolves with the decoded vertex data
  62198. */
  62199. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62200. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62201. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62202. var module = wrappedModule.module;
  62203. var vertexData = new BABYLON.VertexData();
  62204. var buffer = new module.DecoderBuffer();
  62205. buffer.Init(dataView, dataView.byteLength);
  62206. var decoder = new module.Decoder();
  62207. var geometry;
  62208. var status;
  62209. try {
  62210. var type = decoder.GetEncodedGeometryType(buffer);
  62211. switch (type) {
  62212. case module.TRIANGULAR_MESH:
  62213. geometry = new module.Mesh();
  62214. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62215. break;
  62216. case module.POINT_CLOUD:
  62217. geometry = new module.PointCloud();
  62218. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62219. break;
  62220. default:
  62221. throw new Error("Invalid geometry type " + type);
  62222. }
  62223. if (!status.ok() || !geometry.ptr) {
  62224. throw new Error(status.error_msg());
  62225. }
  62226. var numPoints = geometry.num_points();
  62227. if (type === module.TRIANGULAR_MESH) {
  62228. var numFaces = geometry.num_faces();
  62229. var faceIndices = new module.DracoInt32Array();
  62230. try {
  62231. var indices = new Uint32Array(numFaces * 3);
  62232. for (var i = 0; i < numFaces; i++) {
  62233. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62234. var offset = i * 3;
  62235. indices[offset + 0] = faceIndices.GetValue(0);
  62236. indices[offset + 1] = faceIndices.GetValue(1);
  62237. indices[offset + 2] = faceIndices.GetValue(2);
  62238. }
  62239. vertexData.indices = indices;
  62240. }
  62241. finally {
  62242. module.destroy(faceIndices);
  62243. }
  62244. }
  62245. for (var kind in attributes) {
  62246. var uniqueId = attributes[kind];
  62247. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62248. var dracoData = new module.DracoFloat32Array();
  62249. try {
  62250. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62251. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62252. for (var i = 0; i < babylonData.length; i++) {
  62253. babylonData[i] = dracoData.GetValue(i);
  62254. }
  62255. vertexData.set(babylonData, kind);
  62256. }
  62257. finally {
  62258. module.destroy(dracoData);
  62259. }
  62260. }
  62261. }
  62262. finally {
  62263. if (geometry) {
  62264. module.destroy(geometry);
  62265. }
  62266. module.destroy(decoder);
  62267. module.destroy(buffer);
  62268. }
  62269. return vertexData;
  62270. });
  62271. };
  62272. DracoCompression._GetDecoderModule = function () {
  62273. if (!DracoCompression._DecoderModulePromise) {
  62274. var promise = null;
  62275. var config_1 = {};
  62276. if (typeof DracoDecoderModule !== "undefined") {
  62277. promise = Promise.resolve();
  62278. }
  62279. else {
  62280. var decoder = DracoCompression.Configuration.decoder;
  62281. if (decoder) {
  62282. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62283. promise = Promise.all([
  62284. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62285. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62286. config_1.wasmBinary = data;
  62287. })
  62288. ]);
  62289. }
  62290. else if (decoder.fallbackUrl) {
  62291. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62292. }
  62293. }
  62294. }
  62295. if (!promise) {
  62296. throw new Error("Draco decoder module is not available");
  62297. }
  62298. DracoCompression._DecoderModulePromise = promise.then(function () {
  62299. return new Promise(function (resolve) {
  62300. config_1.onModuleLoaded = function (decoderModule) {
  62301. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62302. resolve({ module: decoderModule });
  62303. };
  62304. DracoDecoderModule(config_1);
  62305. });
  62306. });
  62307. }
  62308. return DracoCompression._DecoderModulePromise;
  62309. };
  62310. DracoCompression._LoadScriptAsync = function (url) {
  62311. return new Promise(function (resolve, reject) {
  62312. BABYLON.Tools.LoadScript(url, function () {
  62313. resolve();
  62314. }, function (message) {
  62315. reject(new Error(message));
  62316. });
  62317. });
  62318. };
  62319. DracoCompression._LoadFileAsync = function (url) {
  62320. return new Promise(function (resolve, reject) {
  62321. BABYLON.Tools.LoadFile(url, function (data) {
  62322. resolve(data);
  62323. }, undefined, undefined, true, function (request, exception) {
  62324. reject(exception);
  62325. });
  62326. });
  62327. };
  62328. /**
  62329. * The configuration. Defaults to the following urls:
  62330. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62331. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62332. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62333. */
  62334. DracoCompression.Configuration = {
  62335. decoder: {
  62336. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62337. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62338. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62339. }
  62340. };
  62341. return DracoCompression;
  62342. }());
  62343. BABYLON.DracoCompression = DracoCompression;
  62344. })(BABYLON || (BABYLON = {}));
  62345. //# sourceMappingURL=babylon.dracoCompression.js.map
  62346. var BABYLON;
  62347. (function (BABYLON) {
  62348. var AudioEngine = /** @class */ (function () {
  62349. function AudioEngine() {
  62350. this._audioContext = null;
  62351. this._audioContextInitialized = false;
  62352. this.canUseWebAudio = false;
  62353. this.WarnedWebAudioUnsupported = false;
  62354. this.unlocked = false;
  62355. this.isMP3supported = false;
  62356. this.isOGGsupported = false;
  62357. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62358. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62359. this.canUseWebAudio = true;
  62360. }
  62361. var audioElem = document.createElement('audio');
  62362. try {
  62363. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62364. this.isMP3supported = true;
  62365. }
  62366. }
  62367. catch (e) {
  62368. // protect error during capability check.
  62369. }
  62370. try {
  62371. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62372. this.isOGGsupported = true;
  62373. }
  62374. }
  62375. catch (e) {
  62376. // protect error during capability check.
  62377. }
  62378. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62379. this._unlockiOSaudio();
  62380. }
  62381. else {
  62382. this.unlocked = true;
  62383. }
  62384. }
  62385. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62386. get: function () {
  62387. if (!this._audioContextInitialized) {
  62388. this._initializeAudioContext();
  62389. }
  62390. return this._audioContext;
  62391. },
  62392. enumerable: true,
  62393. configurable: true
  62394. });
  62395. AudioEngine.prototype._unlockiOSaudio = function () {
  62396. var _this = this;
  62397. var unlockaudio = function () {
  62398. if (!_this.audioContext) {
  62399. return;
  62400. }
  62401. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62402. var source = _this.audioContext.createBufferSource();
  62403. source.buffer = buffer;
  62404. source.connect(_this.audioContext.destination);
  62405. source.start(0);
  62406. setTimeout(function () {
  62407. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62408. _this.unlocked = true;
  62409. window.removeEventListener('touchend', unlockaudio, false);
  62410. if (_this.onAudioUnlocked) {
  62411. _this.onAudioUnlocked();
  62412. }
  62413. }
  62414. }, 0);
  62415. };
  62416. window.addEventListener('touchend', unlockaudio, false);
  62417. };
  62418. AudioEngine.prototype._initializeAudioContext = function () {
  62419. try {
  62420. if (this.canUseWebAudio) {
  62421. this._audioContext = new AudioContext();
  62422. // create a global volume gain node
  62423. this.masterGain = this._audioContext.createGain();
  62424. this.masterGain.gain.value = 1;
  62425. this.masterGain.connect(this._audioContext.destination);
  62426. this._audioContextInitialized = true;
  62427. }
  62428. }
  62429. catch (e) {
  62430. this.canUseWebAudio = false;
  62431. BABYLON.Tools.Error("Web Audio: " + e.message);
  62432. }
  62433. };
  62434. AudioEngine.prototype.dispose = function () {
  62435. if (this.canUseWebAudio && this._audioContextInitialized) {
  62436. if (this._connectedAnalyser && this._audioContext) {
  62437. this._connectedAnalyser.stopDebugCanvas();
  62438. this._connectedAnalyser.dispose();
  62439. this.masterGain.disconnect();
  62440. this.masterGain.connect(this._audioContext.destination);
  62441. this._connectedAnalyser = null;
  62442. }
  62443. this.masterGain.gain.value = 1;
  62444. }
  62445. this.WarnedWebAudioUnsupported = false;
  62446. };
  62447. AudioEngine.prototype.getGlobalVolume = function () {
  62448. if (this.canUseWebAudio && this._audioContextInitialized) {
  62449. return this.masterGain.gain.value;
  62450. }
  62451. else {
  62452. return -1;
  62453. }
  62454. };
  62455. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62456. if (this.canUseWebAudio && this._audioContextInitialized) {
  62457. this.masterGain.gain.value = newVolume;
  62458. }
  62459. };
  62460. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62461. if (this._connectedAnalyser) {
  62462. this._connectedAnalyser.stopDebugCanvas();
  62463. }
  62464. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62465. this._connectedAnalyser = analyser;
  62466. this.masterGain.disconnect();
  62467. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62468. }
  62469. };
  62470. return AudioEngine;
  62471. }());
  62472. BABYLON.AudioEngine = AudioEngine;
  62473. })(BABYLON || (BABYLON = {}));
  62474. //# sourceMappingURL=babylon.audioEngine.js.map
  62475. var BABYLON;
  62476. (function (BABYLON) {
  62477. var Sound = /** @class */ (function () {
  62478. /**
  62479. * Create a sound and attach it to a scene
  62480. * @param name Name of your sound
  62481. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62482. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62483. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62484. */
  62485. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62486. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62487. var _this = this;
  62488. this.autoplay = false;
  62489. this.loop = false;
  62490. this.useCustomAttenuation = false;
  62491. this.spatialSound = false;
  62492. this.refDistance = 1;
  62493. this.rolloffFactor = 1;
  62494. this.maxDistance = 100;
  62495. this.distanceModel = "linear";
  62496. this._panningModel = "equalpower";
  62497. this._playbackRate = 1;
  62498. this._streaming = false;
  62499. this._startTime = 0;
  62500. this._startOffset = 0;
  62501. this._position = BABYLON.Vector3.Zero();
  62502. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62503. this._volume = 1;
  62504. this._isReadyToPlay = false;
  62505. this.isPlaying = false;
  62506. this.isPaused = false;
  62507. this._isDirectional = false;
  62508. // Used if you'd like to create a directional sound.
  62509. // If not set, the sound will be omnidirectional
  62510. this._coneInnerAngle = 360;
  62511. this._coneOuterAngle = 360;
  62512. this._coneOuterGain = 0;
  62513. this._isOutputConnected = false;
  62514. this._urlType = "Unknown";
  62515. this.name = name;
  62516. this._scene = scene;
  62517. this._readyToPlayCallback = readyToPlayCallback;
  62518. // Default custom attenuation function is a linear attenuation
  62519. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62520. if (currentDistance < maxDistance) {
  62521. return currentVolume * (1 - currentDistance / maxDistance);
  62522. }
  62523. else {
  62524. return 0;
  62525. }
  62526. };
  62527. if (options) {
  62528. this.autoplay = options.autoplay || false;
  62529. this.loop = options.loop || false;
  62530. // if volume === 0, we need another way to check this option
  62531. if (options.volume !== undefined) {
  62532. this._volume = options.volume;
  62533. }
  62534. this.spatialSound = options.spatialSound || false;
  62535. this.maxDistance = options.maxDistance || 100;
  62536. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62537. this.rolloffFactor = options.rolloffFactor || 1;
  62538. this.refDistance = options.refDistance || 1;
  62539. this.distanceModel = options.distanceModel || "linear";
  62540. this._playbackRate = options.playbackRate || 1;
  62541. this._streaming = options.streaming || false;
  62542. }
  62543. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62544. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62545. this._soundGain.gain.value = this._volume;
  62546. this._inputAudioNode = this._soundGain;
  62547. this._ouputAudioNode = this._soundGain;
  62548. if (this.spatialSound) {
  62549. this._createSpatialParameters();
  62550. }
  62551. this._scene.mainSoundTrack.AddSound(this);
  62552. var validParameter = true;
  62553. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62554. if (urlOrArrayBuffer) {
  62555. try {
  62556. if (typeof (urlOrArrayBuffer) === "string") {
  62557. this._urlType = "String";
  62558. }
  62559. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62560. this._urlType = "ArrayBuffer";
  62561. }
  62562. else if (urlOrArrayBuffer instanceof MediaStream) {
  62563. this._urlType = "MediaStream";
  62564. }
  62565. else if (Array.isArray(urlOrArrayBuffer)) {
  62566. this._urlType = "Array";
  62567. }
  62568. var urls = [];
  62569. var codecSupportedFound = false;
  62570. switch (this._urlType) {
  62571. case "MediaStream":
  62572. this._streaming = true;
  62573. this._isReadyToPlay = true;
  62574. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62575. if (this.autoplay) {
  62576. this.play();
  62577. }
  62578. if (this._readyToPlayCallback) {
  62579. this._readyToPlayCallback();
  62580. }
  62581. break;
  62582. case "ArrayBuffer":
  62583. if (urlOrArrayBuffer.byteLength > 0) {
  62584. codecSupportedFound = true;
  62585. this._soundLoaded(urlOrArrayBuffer);
  62586. }
  62587. break;
  62588. case "String":
  62589. urls.push(urlOrArrayBuffer);
  62590. case "Array":
  62591. if (urls.length === 0)
  62592. urls = urlOrArrayBuffer;
  62593. // If we found a supported format, we load it immediately and stop the loop
  62594. for (var i = 0; i < urls.length; i++) {
  62595. var url = urls[i];
  62596. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62597. codecSupportedFound = true;
  62598. }
  62599. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62600. codecSupportedFound = true;
  62601. }
  62602. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62603. codecSupportedFound = true;
  62604. }
  62605. if (url.indexOf("blob:") !== -1) {
  62606. codecSupportedFound = true;
  62607. }
  62608. if (codecSupportedFound) {
  62609. // Loading sound using XHR2
  62610. if (!this._streaming) {
  62611. this._scene._loadFile(url, function (data) {
  62612. _this._soundLoaded(data);
  62613. }, undefined, true, true, function (exception) {
  62614. if (exception) {
  62615. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62616. }
  62617. BABYLON.Tools.Error("Sound creation aborted.");
  62618. _this._scene.mainSoundTrack.RemoveSound(_this);
  62619. });
  62620. }
  62621. // Streaming sound using HTML5 Audio tag
  62622. else {
  62623. this._htmlAudioElement = new Audio(url);
  62624. this._htmlAudioElement.controls = false;
  62625. this._htmlAudioElement.loop = this.loop;
  62626. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62627. this._htmlAudioElement.preload = "auto";
  62628. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62629. _this._isReadyToPlay = true;
  62630. if (_this.autoplay) {
  62631. _this.play();
  62632. }
  62633. if (_this._readyToPlayCallback) {
  62634. _this._readyToPlayCallback();
  62635. }
  62636. });
  62637. document.body.appendChild(this._htmlAudioElement);
  62638. }
  62639. break;
  62640. }
  62641. }
  62642. break;
  62643. default:
  62644. validParameter = false;
  62645. break;
  62646. }
  62647. if (!validParameter) {
  62648. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62649. }
  62650. else {
  62651. if (!codecSupportedFound) {
  62652. this._isReadyToPlay = true;
  62653. // Simulating a ready to play event to avoid breaking code path
  62654. if (this._readyToPlayCallback) {
  62655. window.setTimeout(function () {
  62656. if (_this._readyToPlayCallback) {
  62657. _this._readyToPlayCallback();
  62658. }
  62659. }, 1000);
  62660. }
  62661. }
  62662. }
  62663. }
  62664. catch (ex) {
  62665. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62666. this._scene.mainSoundTrack.RemoveSound(this);
  62667. }
  62668. }
  62669. }
  62670. else {
  62671. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62672. this._scene.mainSoundTrack.AddSound(this);
  62673. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62674. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62675. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62676. }
  62677. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62678. if (this._readyToPlayCallback) {
  62679. window.setTimeout(function () {
  62680. if (_this._readyToPlayCallback) {
  62681. _this._readyToPlayCallback();
  62682. }
  62683. }, 1000);
  62684. }
  62685. }
  62686. }
  62687. Sound.prototype.dispose = function () {
  62688. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62689. if (this.isPlaying) {
  62690. this.stop();
  62691. }
  62692. this._isReadyToPlay = false;
  62693. if (this.soundTrackId === -1) {
  62694. this._scene.mainSoundTrack.RemoveSound(this);
  62695. }
  62696. else {
  62697. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62698. }
  62699. if (this._soundGain) {
  62700. this._soundGain.disconnect();
  62701. this._soundGain = null;
  62702. }
  62703. if (this._soundPanner) {
  62704. this._soundPanner.disconnect();
  62705. this._soundPanner = null;
  62706. }
  62707. if (this._soundSource) {
  62708. this._soundSource.disconnect();
  62709. this._soundSource = null;
  62710. }
  62711. this._audioBuffer = null;
  62712. if (this._htmlAudioElement) {
  62713. this._htmlAudioElement.pause();
  62714. this._htmlAudioElement.src = "";
  62715. document.body.removeChild(this._htmlAudioElement);
  62716. }
  62717. if (this._streamingSource) {
  62718. this._streamingSource.disconnect();
  62719. }
  62720. if (this._connectedMesh && this._registerFunc) {
  62721. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62722. this._connectedMesh = null;
  62723. }
  62724. }
  62725. };
  62726. Sound.prototype.isReady = function () {
  62727. return this._isReadyToPlay;
  62728. };
  62729. Sound.prototype._soundLoaded = function (audioData) {
  62730. var _this = this;
  62731. if (!BABYLON.Engine.audioEngine.audioContext) {
  62732. return;
  62733. }
  62734. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62735. _this._audioBuffer = buffer;
  62736. _this._isReadyToPlay = true;
  62737. if (_this.autoplay) {
  62738. _this.play();
  62739. }
  62740. if (_this._readyToPlayCallback) {
  62741. _this._readyToPlayCallback();
  62742. }
  62743. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62744. };
  62745. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62746. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62747. this._audioBuffer = audioBuffer;
  62748. this._isReadyToPlay = true;
  62749. }
  62750. };
  62751. Sound.prototype.updateOptions = function (options) {
  62752. if (options) {
  62753. this.loop = options.loop || this.loop;
  62754. this.maxDistance = options.maxDistance || this.maxDistance;
  62755. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62756. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62757. this.refDistance = options.refDistance || this.refDistance;
  62758. this.distanceModel = options.distanceModel || this.distanceModel;
  62759. this._playbackRate = options.playbackRate || this._playbackRate;
  62760. this._updateSpatialParameters();
  62761. if (this.isPlaying) {
  62762. if (this._streaming && this._htmlAudioElement) {
  62763. this._htmlAudioElement.playbackRate = this._playbackRate;
  62764. }
  62765. else {
  62766. if (this._soundSource) {
  62767. this._soundSource.playbackRate.value = this._playbackRate;
  62768. }
  62769. }
  62770. }
  62771. }
  62772. };
  62773. Sound.prototype._createSpatialParameters = function () {
  62774. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62775. if (this._scene.headphone) {
  62776. this._panningModel = "HRTF";
  62777. }
  62778. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62779. this._updateSpatialParameters();
  62780. this._soundPanner.connect(this._ouputAudioNode);
  62781. this._inputAudioNode = this._soundPanner;
  62782. }
  62783. };
  62784. Sound.prototype._updateSpatialParameters = function () {
  62785. if (this.spatialSound && this._soundPanner) {
  62786. if (this.useCustomAttenuation) {
  62787. // Tricks to disable in a way embedded Web Audio attenuation
  62788. this._soundPanner.distanceModel = "linear";
  62789. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62790. this._soundPanner.refDistance = 1;
  62791. this._soundPanner.rolloffFactor = 1;
  62792. this._soundPanner.panningModel = this._panningModel;
  62793. }
  62794. else {
  62795. this._soundPanner.distanceModel = this.distanceModel;
  62796. this._soundPanner.maxDistance = this.maxDistance;
  62797. this._soundPanner.refDistance = this.refDistance;
  62798. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62799. this._soundPanner.panningModel = this._panningModel;
  62800. }
  62801. }
  62802. };
  62803. Sound.prototype.switchPanningModelToHRTF = function () {
  62804. this._panningModel = "HRTF";
  62805. this._switchPanningModel();
  62806. };
  62807. Sound.prototype.switchPanningModelToEqualPower = function () {
  62808. this._panningModel = "equalpower";
  62809. this._switchPanningModel();
  62810. };
  62811. Sound.prototype._switchPanningModel = function () {
  62812. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62813. this._soundPanner.panningModel = this._panningModel;
  62814. }
  62815. };
  62816. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62817. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62818. if (this._isOutputConnected) {
  62819. this._ouputAudioNode.disconnect();
  62820. }
  62821. this._ouputAudioNode.connect(soundTrackAudioNode);
  62822. this._isOutputConnected = true;
  62823. }
  62824. };
  62825. /**
  62826. * Transform this sound into a directional source
  62827. * @param coneInnerAngle Size of the inner cone in degree
  62828. * @param coneOuterAngle Size of the outer cone in degree
  62829. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62830. */
  62831. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62832. if (coneOuterAngle < coneInnerAngle) {
  62833. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62834. return;
  62835. }
  62836. this._coneInnerAngle = coneInnerAngle;
  62837. this._coneOuterAngle = coneOuterAngle;
  62838. this._coneOuterGain = coneOuterGain;
  62839. this._isDirectional = true;
  62840. if (this.isPlaying && this.loop) {
  62841. this.stop();
  62842. this.play();
  62843. }
  62844. };
  62845. Sound.prototype.setPosition = function (newPosition) {
  62846. this._position = newPosition;
  62847. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62848. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62849. }
  62850. };
  62851. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62852. this._localDirection = newLocalDirection;
  62853. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62854. this._updateDirection();
  62855. }
  62856. };
  62857. Sound.prototype._updateDirection = function () {
  62858. if (!this._connectedMesh || !this._soundPanner) {
  62859. return;
  62860. }
  62861. var mat = this._connectedMesh.getWorldMatrix();
  62862. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62863. direction.normalize();
  62864. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62865. };
  62866. Sound.prototype.updateDistanceFromListener = function () {
  62867. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62868. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62869. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62870. }
  62871. };
  62872. Sound.prototype.setAttenuationFunction = function (callback) {
  62873. this._customAttenuationFunction = callback;
  62874. };
  62875. /**
  62876. * Play the sound
  62877. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62878. * @param offset (optional) Start the sound setting it at a specific time
  62879. */
  62880. Sound.prototype.play = function (time, offset) {
  62881. var _this = this;
  62882. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62883. try {
  62884. if (this._startOffset < 0) {
  62885. time = -this._startOffset;
  62886. this._startOffset = 0;
  62887. }
  62888. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62889. if (!this._soundSource || !this._streamingSource) {
  62890. if (this.spatialSound && this._soundPanner) {
  62891. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62892. if (this._isDirectional) {
  62893. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62894. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62895. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62896. if (this._connectedMesh) {
  62897. this._updateDirection();
  62898. }
  62899. else {
  62900. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62901. }
  62902. }
  62903. }
  62904. }
  62905. if (this._streaming) {
  62906. if (!this._streamingSource) {
  62907. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62908. this._htmlAudioElement.onended = function () { _this._onended(); };
  62909. this._htmlAudioElement.playbackRate = this._playbackRate;
  62910. }
  62911. this._streamingSource.disconnect();
  62912. this._streamingSource.connect(this._inputAudioNode);
  62913. if (this._htmlAudioElement) {
  62914. this._htmlAudioElement.play();
  62915. }
  62916. }
  62917. else {
  62918. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62919. this._soundSource.buffer = this._audioBuffer;
  62920. this._soundSource.connect(this._inputAudioNode);
  62921. this._soundSource.loop = this.loop;
  62922. this._soundSource.playbackRate.value = this._playbackRate;
  62923. this._soundSource.onended = function () { _this._onended(); };
  62924. if (this._soundSource.buffer) {
  62925. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62926. }
  62927. }
  62928. this._startTime = startTime;
  62929. this.isPlaying = true;
  62930. this.isPaused = false;
  62931. }
  62932. catch (ex) {
  62933. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62934. }
  62935. }
  62936. };
  62937. Sound.prototype._onended = function () {
  62938. this.isPlaying = false;
  62939. if (this.onended) {
  62940. this.onended();
  62941. }
  62942. };
  62943. /**
  62944. * Stop the sound
  62945. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62946. */
  62947. Sound.prototype.stop = function (time) {
  62948. if (this.isPlaying) {
  62949. if (this._streaming) {
  62950. if (this._htmlAudioElement) {
  62951. this._htmlAudioElement.pause();
  62952. // Test needed for Firefox or it will generate an Invalid State Error
  62953. if (this._htmlAudioElement.currentTime > 0) {
  62954. this._htmlAudioElement.currentTime = 0;
  62955. }
  62956. }
  62957. else {
  62958. this._streamingSource.disconnect();
  62959. }
  62960. }
  62961. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62962. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62963. this._soundSource.stop(stopTime);
  62964. this._soundSource.onended = function () { };
  62965. if (!this.isPaused) {
  62966. this._startOffset = 0;
  62967. }
  62968. }
  62969. this.isPlaying = false;
  62970. }
  62971. };
  62972. Sound.prototype.pause = function () {
  62973. if (this.isPlaying) {
  62974. this.isPaused = true;
  62975. if (this._streaming) {
  62976. if (this._htmlAudioElement) {
  62977. this._htmlAudioElement.pause();
  62978. }
  62979. else {
  62980. this._streamingSource.disconnect();
  62981. }
  62982. }
  62983. else if (BABYLON.Engine.audioEngine.audioContext) {
  62984. this.stop(0);
  62985. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62986. }
  62987. }
  62988. };
  62989. Sound.prototype.setVolume = function (newVolume, time) {
  62990. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62991. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62992. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62993. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62994. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62995. }
  62996. else {
  62997. this._soundGain.gain.value = newVolume;
  62998. }
  62999. }
  63000. this._volume = newVolume;
  63001. };
  63002. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63003. this._playbackRate = newPlaybackRate;
  63004. if (this.isPlaying) {
  63005. if (this._streaming && this._htmlAudioElement) {
  63006. this._htmlAudioElement.playbackRate = this._playbackRate;
  63007. }
  63008. else if (this._soundSource) {
  63009. this._soundSource.playbackRate.value = this._playbackRate;
  63010. }
  63011. }
  63012. };
  63013. Sound.prototype.getVolume = function () {
  63014. return this._volume;
  63015. };
  63016. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63017. var _this = this;
  63018. if (this._connectedMesh && this._registerFunc) {
  63019. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63020. this._registerFunc = null;
  63021. }
  63022. this._connectedMesh = meshToConnectTo;
  63023. if (!this.spatialSound) {
  63024. this.spatialSound = true;
  63025. this._createSpatialParameters();
  63026. if (this.isPlaying && this.loop) {
  63027. this.stop();
  63028. this.play();
  63029. }
  63030. }
  63031. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63032. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63033. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63034. };
  63035. Sound.prototype.detachFromMesh = function () {
  63036. if (this._connectedMesh && this._registerFunc) {
  63037. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63038. this._registerFunc = null;
  63039. this._connectedMesh = null;
  63040. }
  63041. };
  63042. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63043. if (!node.getBoundingInfo) {
  63044. return;
  63045. }
  63046. var mesh = node;
  63047. var boundingInfo = mesh.getBoundingInfo();
  63048. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63049. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63050. this._updateDirection();
  63051. }
  63052. };
  63053. Sound.prototype.clone = function () {
  63054. var _this = this;
  63055. if (!this._streaming) {
  63056. var setBufferAndRun = function () {
  63057. if (_this._isReadyToPlay) {
  63058. clonedSound._audioBuffer = _this.getAudioBuffer();
  63059. clonedSound._isReadyToPlay = true;
  63060. if (clonedSound.autoplay) {
  63061. clonedSound.play();
  63062. }
  63063. }
  63064. else {
  63065. window.setTimeout(setBufferAndRun, 300);
  63066. }
  63067. };
  63068. var currentOptions = {
  63069. autoplay: this.autoplay, loop: this.loop,
  63070. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63071. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63072. refDistance: this.refDistance, distanceModel: this.distanceModel
  63073. };
  63074. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63075. if (this.useCustomAttenuation) {
  63076. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63077. }
  63078. clonedSound.setPosition(this._position);
  63079. clonedSound.setPlaybackRate(this._playbackRate);
  63080. setBufferAndRun();
  63081. return clonedSound;
  63082. }
  63083. // Can't clone a streaming sound
  63084. else {
  63085. return null;
  63086. }
  63087. };
  63088. Sound.prototype.getAudioBuffer = function () {
  63089. return this._audioBuffer;
  63090. };
  63091. Sound.prototype.serialize = function () {
  63092. var serializationObject = {
  63093. name: this.name,
  63094. url: this.name,
  63095. autoplay: this.autoplay,
  63096. loop: this.loop,
  63097. volume: this._volume,
  63098. spatialSound: this.spatialSound,
  63099. maxDistance: this.maxDistance,
  63100. rolloffFactor: this.rolloffFactor,
  63101. refDistance: this.refDistance,
  63102. distanceModel: this.distanceModel,
  63103. playbackRate: this._playbackRate,
  63104. panningModel: this._panningModel,
  63105. soundTrackId: this.soundTrackId
  63106. };
  63107. if (this.spatialSound) {
  63108. if (this._connectedMesh)
  63109. serializationObject.connectedMeshId = this._connectedMesh.id;
  63110. serializationObject.position = this._position.asArray();
  63111. serializationObject.refDistance = this.refDistance;
  63112. serializationObject.distanceModel = this.distanceModel;
  63113. serializationObject.isDirectional = this._isDirectional;
  63114. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63115. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63116. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63117. serializationObject.coneOuterGain = this._coneOuterGain;
  63118. }
  63119. return serializationObject;
  63120. };
  63121. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63122. var soundName = parsedSound.name;
  63123. var soundUrl;
  63124. if (parsedSound.url) {
  63125. soundUrl = rootUrl + parsedSound.url;
  63126. }
  63127. else {
  63128. soundUrl = rootUrl + soundName;
  63129. }
  63130. var options = {
  63131. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63132. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63133. rolloffFactor: parsedSound.rolloffFactor,
  63134. refDistance: parsedSound.refDistance,
  63135. distanceModel: parsedSound.distanceModel,
  63136. playbackRate: parsedSound.playbackRate
  63137. };
  63138. var newSound;
  63139. if (!sourceSound) {
  63140. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63141. scene._addPendingData(newSound);
  63142. }
  63143. else {
  63144. var setBufferAndRun = function () {
  63145. if (sourceSound._isReadyToPlay) {
  63146. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63147. newSound._isReadyToPlay = true;
  63148. if (newSound.autoplay) {
  63149. newSound.play();
  63150. }
  63151. }
  63152. else {
  63153. window.setTimeout(setBufferAndRun, 300);
  63154. }
  63155. };
  63156. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63157. setBufferAndRun();
  63158. }
  63159. if (parsedSound.position) {
  63160. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63161. newSound.setPosition(soundPosition);
  63162. }
  63163. if (parsedSound.isDirectional) {
  63164. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63165. if (parsedSound.localDirectionToMesh) {
  63166. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63167. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63168. }
  63169. }
  63170. if (parsedSound.connectedMeshId) {
  63171. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63172. if (connectedMesh) {
  63173. newSound.attachToMesh(connectedMesh);
  63174. }
  63175. }
  63176. return newSound;
  63177. };
  63178. return Sound;
  63179. }());
  63180. BABYLON.Sound = Sound;
  63181. })(BABYLON || (BABYLON = {}));
  63182. //# sourceMappingURL=babylon.sound.js.map
  63183. var BABYLON;
  63184. (function (BABYLON) {
  63185. var SoundTrack = /** @class */ (function () {
  63186. function SoundTrack(scene, options) {
  63187. this.id = -1;
  63188. this._isMainTrack = false;
  63189. this._isInitialized = false;
  63190. this._scene = scene;
  63191. this.soundCollection = new Array();
  63192. this._options = options;
  63193. if (!this._isMainTrack) {
  63194. this._scene.soundTracks.push(this);
  63195. this.id = this._scene.soundTracks.length - 1;
  63196. }
  63197. }
  63198. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63199. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63200. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63201. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63202. if (this._options) {
  63203. if (this._options.volume) {
  63204. this._outputAudioNode.gain.value = this._options.volume;
  63205. }
  63206. if (this._options.mainTrack) {
  63207. this._isMainTrack = this._options.mainTrack;
  63208. }
  63209. }
  63210. this._isInitialized = true;
  63211. }
  63212. };
  63213. SoundTrack.prototype.dispose = function () {
  63214. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63215. if (this._connectedAnalyser) {
  63216. this._connectedAnalyser.stopDebugCanvas();
  63217. }
  63218. while (this.soundCollection.length) {
  63219. this.soundCollection[0].dispose();
  63220. }
  63221. if (this._outputAudioNode) {
  63222. this._outputAudioNode.disconnect();
  63223. }
  63224. this._outputAudioNode = null;
  63225. }
  63226. };
  63227. SoundTrack.prototype.AddSound = function (sound) {
  63228. if (!this._isInitialized) {
  63229. this._initializeSoundTrackAudioGraph();
  63230. }
  63231. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63232. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63233. }
  63234. if (sound.soundTrackId) {
  63235. if (sound.soundTrackId === -1) {
  63236. this._scene.mainSoundTrack.RemoveSound(sound);
  63237. }
  63238. else {
  63239. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63240. }
  63241. }
  63242. this.soundCollection.push(sound);
  63243. sound.soundTrackId = this.id;
  63244. };
  63245. SoundTrack.prototype.RemoveSound = function (sound) {
  63246. var index = this.soundCollection.indexOf(sound);
  63247. if (index !== -1) {
  63248. this.soundCollection.splice(index, 1);
  63249. }
  63250. };
  63251. SoundTrack.prototype.setVolume = function (newVolume) {
  63252. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63253. this._outputAudioNode.gain.value = newVolume;
  63254. }
  63255. };
  63256. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63257. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63258. for (var i = 0; i < this.soundCollection.length; i++) {
  63259. this.soundCollection[i].switchPanningModelToHRTF();
  63260. }
  63261. }
  63262. };
  63263. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63264. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63265. for (var i = 0; i < this.soundCollection.length; i++) {
  63266. this.soundCollection[i].switchPanningModelToEqualPower();
  63267. }
  63268. }
  63269. };
  63270. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63271. if (this._connectedAnalyser) {
  63272. this._connectedAnalyser.stopDebugCanvas();
  63273. }
  63274. this._connectedAnalyser = analyser;
  63275. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63276. this._outputAudioNode.disconnect();
  63277. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63278. }
  63279. };
  63280. return SoundTrack;
  63281. }());
  63282. BABYLON.SoundTrack = SoundTrack;
  63283. })(BABYLON || (BABYLON = {}));
  63284. //# sourceMappingURL=babylon.soundtrack.js.map
  63285. var BABYLON;
  63286. (function (BABYLON) {
  63287. /**
  63288. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63289. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63290. */
  63291. var Analyser = /** @class */ (function () {
  63292. /**
  63293. * Creates a new analyser
  63294. * @param scene defines hosting scene
  63295. */
  63296. function Analyser(scene) {
  63297. /**
  63298. * Gets or sets the smoothing
  63299. * @ignorenaming
  63300. */
  63301. this.SMOOTHING = 0.75;
  63302. /**
  63303. * Gets or sets the FFT table size
  63304. * @ignorenaming
  63305. */
  63306. this.FFT_SIZE = 512;
  63307. /**
  63308. * Gets or sets the bar graph amplitude
  63309. * @ignorenaming
  63310. */
  63311. this.BARGRAPHAMPLITUDE = 256;
  63312. /**
  63313. * Gets or sets the position of the debug canvas
  63314. * @ignorenaming
  63315. */
  63316. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63317. /**
  63318. * Gets or sets the debug canvas size
  63319. * @ignorenaming
  63320. */
  63321. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63322. this._scene = scene;
  63323. this._audioEngine = BABYLON.Engine.audioEngine;
  63324. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63325. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63326. this._webAudioAnalyser.minDecibels = -140;
  63327. this._webAudioAnalyser.maxDecibels = 0;
  63328. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63329. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63330. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63331. }
  63332. }
  63333. /**
  63334. * Get the number of data values you will have to play with for the visualization
  63335. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63336. * @returns a number
  63337. */
  63338. Analyser.prototype.getFrequencyBinCount = function () {
  63339. if (this._audioEngine.canUseWebAudio) {
  63340. return this._webAudioAnalyser.frequencyBinCount;
  63341. }
  63342. else {
  63343. return 0;
  63344. }
  63345. };
  63346. /**
  63347. * Gets the current frequency data as a byte array
  63348. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63349. * @returns a Uint8Array
  63350. */
  63351. Analyser.prototype.getByteFrequencyData = function () {
  63352. if (this._audioEngine.canUseWebAudio) {
  63353. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63354. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63355. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63356. }
  63357. return this._byteFreqs;
  63358. };
  63359. /**
  63360. * Gets the current waveform as a byte array
  63361. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63362. * @returns a Uint8Array
  63363. */
  63364. Analyser.prototype.getByteTimeDomainData = function () {
  63365. if (this._audioEngine.canUseWebAudio) {
  63366. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63367. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63368. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63369. }
  63370. return this._byteTime;
  63371. };
  63372. /**
  63373. * Gets the current frequency data as a float array
  63374. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63375. * @returns a Float32Array
  63376. */
  63377. Analyser.prototype.getFloatFrequencyData = function () {
  63378. if (this._audioEngine.canUseWebAudio) {
  63379. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63380. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63381. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63382. }
  63383. return this._floatFreqs;
  63384. };
  63385. /**
  63386. * Renders the debug canvas
  63387. */
  63388. Analyser.prototype.drawDebugCanvas = function () {
  63389. var _this = this;
  63390. if (this._audioEngine.canUseWebAudio) {
  63391. if (!this._debugCanvas) {
  63392. this._debugCanvas = document.createElement("canvas");
  63393. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63394. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63395. this._debugCanvas.style.position = "absolute";
  63396. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63397. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63398. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63399. document.body.appendChild(this._debugCanvas);
  63400. this._registerFunc = function () {
  63401. _this.drawDebugCanvas();
  63402. };
  63403. this._scene.registerBeforeRender(this._registerFunc);
  63404. }
  63405. if (this._registerFunc && this._debugCanvasContext) {
  63406. var workingArray = this.getByteFrequencyData();
  63407. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63408. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63409. // Draw the frequency domain chart.
  63410. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63411. var value = workingArray[i];
  63412. var percent = value / this.BARGRAPHAMPLITUDE;
  63413. var height = this.DEBUGCANVASSIZE.height * percent;
  63414. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63415. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63416. var hue = i / this.getFrequencyBinCount() * 360;
  63417. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63418. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63419. }
  63420. }
  63421. }
  63422. };
  63423. /**
  63424. * Stops rendering the debug canvas and removes it
  63425. */
  63426. Analyser.prototype.stopDebugCanvas = function () {
  63427. if (this._debugCanvas) {
  63428. if (this._registerFunc) {
  63429. this._scene.unregisterBeforeRender(this._registerFunc);
  63430. this._registerFunc = null;
  63431. }
  63432. document.body.removeChild(this._debugCanvas);
  63433. this._debugCanvas = null;
  63434. this._debugCanvasContext = null;
  63435. }
  63436. };
  63437. /**
  63438. * Connects two audio nodes
  63439. * @param inputAudioNode defines first node to connect
  63440. * @param outputAudioNode defines second node to connect
  63441. */
  63442. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63443. if (this._audioEngine.canUseWebAudio) {
  63444. inputAudioNode.connect(this._webAudioAnalyser);
  63445. this._webAudioAnalyser.connect(outputAudioNode);
  63446. }
  63447. };
  63448. /**
  63449. * Releases all associated resources
  63450. */
  63451. Analyser.prototype.dispose = function () {
  63452. if (this._audioEngine.canUseWebAudio) {
  63453. this._webAudioAnalyser.disconnect();
  63454. }
  63455. };
  63456. return Analyser;
  63457. }());
  63458. BABYLON.Analyser = Analyser;
  63459. })(BABYLON || (BABYLON = {}));
  63460. //# sourceMappingURL=babylon.analyser.js.map
  63461. var BABYLON;
  63462. (function (BABYLON) {
  63463. var CubeTexture = /** @class */ (function (_super) {
  63464. __extends(CubeTexture, _super);
  63465. /**
  63466. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63467. * as prefiltered data.
  63468. * @param rootUrl defines the url of the texture or the root name of the six images
  63469. * @param scene defines the scene the texture is attached to
  63470. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63471. * @param noMipmap defines if mipmaps should be created or not
  63472. * @param files defines the six files to load for the different faces
  63473. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63474. * @param onError defines a callback triggered in case of error during load
  63475. * @param format defines the internal format to use for the texture once loaded
  63476. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63477. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63478. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63479. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63480. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63481. * @return the cube texture
  63482. */
  63483. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63484. if (extensions === void 0) { extensions = null; }
  63485. if (noMipmap === void 0) { noMipmap = false; }
  63486. if (files === void 0) { files = null; }
  63487. if (onLoad === void 0) { onLoad = null; }
  63488. if (onError === void 0) { onError = null; }
  63489. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63490. if (prefiltered === void 0) { prefiltered = false; }
  63491. if (forcedExtension === void 0) { forcedExtension = null; }
  63492. if (createPolynomials === void 0) { createPolynomials = false; }
  63493. if (lodScale === void 0) { lodScale = 0.8; }
  63494. if (lodOffset === void 0) { lodOffset = 0; }
  63495. var _this = _super.call(this, scene) || this;
  63496. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63497. /**
  63498. * Gets or sets the center of the bounding box associated with the cube texture
  63499. * It must define where the camera used to render the texture was set
  63500. */
  63501. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63502. _this._rotationY = 0;
  63503. /** @hidden */
  63504. _this._prefiltered = false;
  63505. _this.name = rootUrl;
  63506. _this.url = rootUrl;
  63507. _this._noMipmap = noMipmap;
  63508. _this.hasAlpha = false;
  63509. _this._format = format;
  63510. _this.isCube = true;
  63511. _this._textureMatrix = BABYLON.Matrix.Identity();
  63512. _this._createPolynomials = createPolynomials;
  63513. if (!rootUrl && !files) {
  63514. return _this;
  63515. }
  63516. var lastDot = rootUrl.lastIndexOf(".");
  63517. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63518. var isDDS = (extension === ".dds");
  63519. var isEnv = (extension === ".env");
  63520. if (isEnv) {
  63521. _this.gammaSpace = false;
  63522. _this._prefiltered = false;
  63523. }
  63524. else {
  63525. _this._prefiltered = prefiltered;
  63526. if (prefiltered) {
  63527. _this.gammaSpace = false;
  63528. }
  63529. }
  63530. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63531. if (!files) {
  63532. if (!isEnv && !isDDS && !extensions) {
  63533. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63534. }
  63535. files = [];
  63536. if (extensions) {
  63537. for (var index = 0; index < extensions.length; index++) {
  63538. files.push(rootUrl + extensions[index]);
  63539. }
  63540. }
  63541. }
  63542. _this._files = files;
  63543. if (!_this._texture) {
  63544. if (!scene.useDelayedTextureLoading) {
  63545. if (prefiltered) {
  63546. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63547. }
  63548. else {
  63549. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63550. }
  63551. }
  63552. else {
  63553. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63554. }
  63555. }
  63556. else if (onLoad) {
  63557. if (_this._texture.isReady) {
  63558. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63559. }
  63560. else {
  63561. _this._texture.onLoadedObservable.add(onLoad);
  63562. }
  63563. }
  63564. return _this;
  63565. }
  63566. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63567. get: function () {
  63568. return this._boundingBoxSize;
  63569. },
  63570. /**
  63571. * Gets or sets the size of the bounding box associated with the cube texture
  63572. * When defined, the cubemap will switch to local mode
  63573. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63574. * @example https://www.babylonjs-playground.com/#RNASML
  63575. */
  63576. set: function (value) {
  63577. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63578. return;
  63579. }
  63580. this._boundingBoxSize = value;
  63581. var scene = this.getScene();
  63582. if (scene) {
  63583. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63584. }
  63585. },
  63586. enumerable: true,
  63587. configurable: true
  63588. });
  63589. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63590. /**
  63591. * Gets texture matrix rotation angle around Y axis radians.
  63592. */
  63593. get: function () {
  63594. return this._rotationY;
  63595. },
  63596. /**
  63597. * Sets texture matrix rotation angle around Y axis in radians.
  63598. */
  63599. set: function (value) {
  63600. this._rotationY = value;
  63601. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63602. },
  63603. enumerable: true,
  63604. configurable: true
  63605. });
  63606. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63607. var rootUrlKey = "";
  63608. files.forEach(function (url) { return rootUrlKey += url; });
  63609. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63610. };
  63611. /**
  63612. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63613. * @param url defines the url of the prefiltered texture
  63614. * @param scene defines the scene the texture is attached to
  63615. * @param forcedExtension defines the extension of the file if different from the url
  63616. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63617. * @return the prefiltered texture
  63618. */
  63619. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63620. if (forcedExtension === void 0) { forcedExtension = null; }
  63621. if (createPolynomials === void 0) { createPolynomials = true; }
  63622. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63623. };
  63624. // Methods
  63625. CubeTexture.prototype.delayLoad = function () {
  63626. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63627. return;
  63628. }
  63629. var scene = this.getScene();
  63630. if (!scene) {
  63631. return;
  63632. }
  63633. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63634. this._texture = this._getFromCache(this.url, this._noMipmap);
  63635. if (!this._texture) {
  63636. if (this._prefiltered) {
  63637. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63638. }
  63639. else {
  63640. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63641. }
  63642. }
  63643. };
  63644. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63645. return this._textureMatrix;
  63646. };
  63647. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63648. this._textureMatrix = value;
  63649. };
  63650. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63651. var texture = BABYLON.SerializationHelper.Parse(function () {
  63652. var prefiltered = false;
  63653. if (parsedTexture.prefiltered) {
  63654. prefiltered = parsedTexture.prefiltered;
  63655. }
  63656. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63657. }, parsedTexture, scene);
  63658. // Local Cubemaps
  63659. if (parsedTexture.boundingBoxPosition) {
  63660. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63661. }
  63662. if (parsedTexture.boundingBoxSize) {
  63663. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63664. }
  63665. // Animations
  63666. if (parsedTexture.animations) {
  63667. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63668. var parsedAnimation = parsedTexture.animations[animationIndex];
  63669. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63670. }
  63671. }
  63672. return texture;
  63673. };
  63674. CubeTexture.prototype.clone = function () {
  63675. var _this = this;
  63676. return BABYLON.SerializationHelper.Clone(function () {
  63677. var scene = _this.getScene();
  63678. if (!scene) {
  63679. return _this;
  63680. }
  63681. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63682. }, this);
  63683. };
  63684. __decorate([
  63685. BABYLON.serialize("rotationY")
  63686. ], CubeTexture.prototype, "_rotationY", void 0);
  63687. return CubeTexture;
  63688. }(BABYLON.BaseTexture));
  63689. BABYLON.CubeTexture = CubeTexture;
  63690. })(BABYLON || (BABYLON = {}));
  63691. //# sourceMappingURL=babylon.cubeTexture.js.map
  63692. var BABYLON;
  63693. (function (BABYLON) {
  63694. var RenderTargetTexture = /** @class */ (function (_super) {
  63695. __extends(RenderTargetTexture, _super);
  63696. /**
  63697. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63698. * or used a shadow, depth texture...
  63699. * @param name The friendly name of the texture
  63700. * @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)
  63701. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63702. * @param generateMipMaps True if mip maps need to be generated after render.
  63703. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63704. * @param type The type of the buffer in the RTT (int, half float, float...)
  63705. * @param isCube True if a cube texture needs to be created
  63706. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63707. * @param generateDepthBuffer True to generate a depth buffer
  63708. * @param generateStencilBuffer True to generate a stencil buffer
  63709. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63710. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63711. */
  63712. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63713. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63714. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63715. if (isCube === void 0) { isCube = false; }
  63716. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63717. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63718. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63719. if (isMulti === void 0) { isMulti = false; }
  63720. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63721. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63722. _this.isCube = isCube;
  63723. /**
  63724. * Use this list to define the list of mesh you want to render.
  63725. */
  63726. _this.renderList = new Array();
  63727. _this.renderParticles = true;
  63728. _this.renderSprites = false;
  63729. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63730. _this.ignoreCameraViewport = false;
  63731. // Events
  63732. /**
  63733. * An event triggered when the texture is unbind.
  63734. */
  63735. _this.onBeforeBindObservable = new BABYLON.Observable();
  63736. /**
  63737. * An event triggered when the texture is unbind.
  63738. */
  63739. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63740. /**
  63741. * An event triggered before rendering the texture
  63742. */
  63743. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63744. /**
  63745. * An event triggered after rendering the texture
  63746. */
  63747. _this.onAfterRenderObservable = new BABYLON.Observable();
  63748. /**
  63749. * An event triggered after the texture clear
  63750. */
  63751. _this.onClearObservable = new BABYLON.Observable();
  63752. _this._currentRefreshId = -1;
  63753. _this._refreshRate = 1;
  63754. _this._samples = 1;
  63755. /**
  63756. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63757. * It must define where the camera used to render the texture is set
  63758. */
  63759. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63760. scene = _this.getScene();
  63761. if (!scene) {
  63762. return _this;
  63763. }
  63764. _this._engine = scene.getEngine();
  63765. _this.name = name;
  63766. _this.isRenderTarget = true;
  63767. _this._initialSizeParameter = size;
  63768. _this._processSizeParameter(size);
  63769. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63770. });
  63771. _this._generateMipMaps = generateMipMaps ? true : false;
  63772. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63773. // Rendering groups
  63774. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63775. if (isMulti) {
  63776. return _this;
  63777. }
  63778. _this._renderTargetOptions = {
  63779. generateMipMaps: generateMipMaps,
  63780. type: type,
  63781. format: format,
  63782. samplingMode: samplingMode,
  63783. generateDepthBuffer: generateDepthBuffer,
  63784. generateStencilBuffer: generateStencilBuffer
  63785. };
  63786. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63787. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63788. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63789. }
  63790. if (isCube) {
  63791. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63792. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63793. _this._textureMatrix = BABYLON.Matrix.Identity();
  63794. }
  63795. else {
  63796. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63797. }
  63798. return _this;
  63799. }
  63800. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63801. get: function () {
  63802. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63803. },
  63804. enumerable: true,
  63805. configurable: true
  63806. });
  63807. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63808. get: function () {
  63809. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63810. },
  63811. enumerable: true,
  63812. configurable: true
  63813. });
  63814. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63815. get: function () {
  63816. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63817. },
  63818. enumerable: true,
  63819. configurable: true
  63820. });
  63821. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63822. set: function (callback) {
  63823. if (this._onAfterUnbindObserver) {
  63824. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63825. }
  63826. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63827. },
  63828. enumerable: true,
  63829. configurable: true
  63830. });
  63831. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63832. set: function (callback) {
  63833. if (this._onBeforeRenderObserver) {
  63834. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63835. }
  63836. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63837. },
  63838. enumerable: true,
  63839. configurable: true
  63840. });
  63841. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63842. set: function (callback) {
  63843. if (this._onAfterRenderObserver) {
  63844. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63845. }
  63846. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63847. },
  63848. enumerable: true,
  63849. configurable: true
  63850. });
  63851. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63852. set: function (callback) {
  63853. if (this._onClearObserver) {
  63854. this.onClearObservable.remove(this._onClearObserver);
  63855. }
  63856. this._onClearObserver = this.onClearObservable.add(callback);
  63857. },
  63858. enumerable: true,
  63859. configurable: true
  63860. });
  63861. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63862. get: function () {
  63863. return this._renderTargetOptions;
  63864. },
  63865. enumerable: true,
  63866. configurable: true
  63867. });
  63868. RenderTargetTexture.prototype._onRatioRescale = function () {
  63869. if (this._sizeRatio) {
  63870. this.resize(this._initialSizeParameter);
  63871. }
  63872. };
  63873. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63874. get: function () {
  63875. return this._boundingBoxSize;
  63876. },
  63877. /**
  63878. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63879. * When defined, the cubemap will switch to local mode
  63880. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63881. * @example https://www.babylonjs-playground.com/#RNASML
  63882. */
  63883. set: function (value) {
  63884. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63885. return;
  63886. }
  63887. this._boundingBoxSize = value;
  63888. var scene = this.getScene();
  63889. if (scene) {
  63890. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63891. }
  63892. },
  63893. enumerable: true,
  63894. configurable: true
  63895. });
  63896. /**
  63897. * Creates a depth stencil texture.
  63898. * This is only available in WebGL 2 or with the depth texture extension available.
  63899. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63900. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63901. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63902. */
  63903. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63904. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63905. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63906. if (generateStencil === void 0) { generateStencil = false; }
  63907. if (!this.getScene()) {
  63908. return;
  63909. }
  63910. var engine = this.getScene().getEngine();
  63911. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63912. bilinearFiltering: bilinearFiltering,
  63913. comparisonFunction: comparisonFunction,
  63914. generateStencil: generateStencil,
  63915. isCube: this.isCube
  63916. });
  63917. engine.setFrameBufferDepthStencilTexture(this);
  63918. };
  63919. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63920. if (size.ratio) {
  63921. this._sizeRatio = size.ratio;
  63922. this._size = {
  63923. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63924. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63925. };
  63926. }
  63927. else {
  63928. this._size = size;
  63929. }
  63930. };
  63931. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63932. get: function () {
  63933. return this._samples;
  63934. },
  63935. set: function (value) {
  63936. if (this._samples === value) {
  63937. return;
  63938. }
  63939. var scene = this.getScene();
  63940. if (!scene) {
  63941. return;
  63942. }
  63943. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63944. },
  63945. enumerable: true,
  63946. configurable: true
  63947. });
  63948. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63949. this._currentRefreshId = -1;
  63950. };
  63951. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63952. get: function () {
  63953. return this._refreshRate;
  63954. },
  63955. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63956. set: function (value) {
  63957. this._refreshRate = value;
  63958. this.resetRefreshCounter();
  63959. },
  63960. enumerable: true,
  63961. configurable: true
  63962. });
  63963. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63964. if (!this._postProcessManager) {
  63965. var scene = this.getScene();
  63966. if (!scene) {
  63967. return;
  63968. }
  63969. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63970. this._postProcesses = new Array();
  63971. }
  63972. this._postProcesses.push(postProcess);
  63973. this._postProcesses[0].autoClear = false;
  63974. };
  63975. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63976. if (!this._postProcesses) {
  63977. return;
  63978. }
  63979. if (dispose) {
  63980. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63981. var postProcess = _a[_i];
  63982. postProcess.dispose();
  63983. }
  63984. }
  63985. this._postProcesses = [];
  63986. };
  63987. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63988. if (!this._postProcesses) {
  63989. return;
  63990. }
  63991. var index = this._postProcesses.indexOf(postProcess);
  63992. if (index === -1) {
  63993. return;
  63994. }
  63995. this._postProcesses.splice(index, 1);
  63996. if (this._postProcesses.length > 0) {
  63997. this._postProcesses[0].autoClear = false;
  63998. }
  63999. };
  64000. RenderTargetTexture.prototype._shouldRender = function () {
  64001. if (this._currentRefreshId === -1) { // At least render once
  64002. this._currentRefreshId = 1;
  64003. return true;
  64004. }
  64005. if (this.refreshRate === this._currentRefreshId) {
  64006. this._currentRefreshId = 1;
  64007. return true;
  64008. }
  64009. this._currentRefreshId++;
  64010. return false;
  64011. };
  64012. RenderTargetTexture.prototype.getRenderSize = function () {
  64013. if (this._size.width) {
  64014. return this._size.width;
  64015. }
  64016. return this._size;
  64017. };
  64018. RenderTargetTexture.prototype.getRenderWidth = function () {
  64019. if (this._size.width) {
  64020. return this._size.width;
  64021. }
  64022. return this._size;
  64023. };
  64024. RenderTargetTexture.prototype.getRenderHeight = function () {
  64025. if (this._size.width) {
  64026. return this._size.height;
  64027. }
  64028. return this._size;
  64029. };
  64030. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64031. get: function () {
  64032. return true;
  64033. },
  64034. enumerable: true,
  64035. configurable: true
  64036. });
  64037. RenderTargetTexture.prototype.scale = function (ratio) {
  64038. var newSize = this.getRenderSize() * ratio;
  64039. this.resize(newSize);
  64040. };
  64041. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64042. if (this.isCube) {
  64043. return this._textureMatrix;
  64044. }
  64045. return _super.prototype.getReflectionTextureMatrix.call(this);
  64046. };
  64047. RenderTargetTexture.prototype.resize = function (size) {
  64048. this.releaseInternalTexture();
  64049. var scene = this.getScene();
  64050. if (!scene) {
  64051. return;
  64052. }
  64053. this._processSizeParameter(size);
  64054. if (this.isCube) {
  64055. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64056. }
  64057. else {
  64058. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64059. }
  64060. };
  64061. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64062. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64063. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64064. var scene = this.getScene();
  64065. if (!scene) {
  64066. return;
  64067. }
  64068. var engine = scene.getEngine();
  64069. if (this.useCameraPostProcesses !== undefined) {
  64070. useCameraPostProcess = this.useCameraPostProcesses;
  64071. }
  64072. if (this._waitingRenderList) {
  64073. this.renderList = [];
  64074. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64075. var id = this._waitingRenderList[index];
  64076. var mesh_1 = scene.getMeshByID(id);
  64077. if (mesh_1) {
  64078. this.renderList.push(mesh_1);
  64079. }
  64080. }
  64081. delete this._waitingRenderList;
  64082. }
  64083. // Is predicate defined?
  64084. if (this.renderListPredicate) {
  64085. if (this.renderList) {
  64086. this.renderList.splice(0); // Clear previous renderList
  64087. }
  64088. else {
  64089. this.renderList = [];
  64090. }
  64091. var scene = this.getScene();
  64092. if (!scene) {
  64093. return;
  64094. }
  64095. var sceneMeshes = scene.meshes;
  64096. for (var index = 0; index < sceneMeshes.length; index++) {
  64097. var mesh = sceneMeshes[index];
  64098. if (this.renderListPredicate(mesh)) {
  64099. this.renderList.push(mesh);
  64100. }
  64101. }
  64102. }
  64103. this.onBeforeBindObservable.notifyObservers(this);
  64104. // Set custom projection.
  64105. // Needs to be before binding to prevent changing the aspect ratio.
  64106. var camera;
  64107. if (this.activeCamera) {
  64108. camera = this.activeCamera;
  64109. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64110. if (this.activeCamera !== scene.activeCamera) {
  64111. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64112. }
  64113. }
  64114. else {
  64115. camera = scene.activeCamera;
  64116. if (camera) {
  64117. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64118. }
  64119. }
  64120. // Prepare renderingManager
  64121. this._renderingManager.reset();
  64122. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64123. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64124. var sceneRenderId = scene.getRenderId();
  64125. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64126. var mesh = currentRenderList[meshIndex];
  64127. if (mesh) {
  64128. if (!mesh.isReady(this.refreshRate === 0)) {
  64129. this.resetRefreshCounter();
  64130. continue;
  64131. }
  64132. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64133. var isMasked = void 0;
  64134. if (!this.renderList && camera) {
  64135. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64136. }
  64137. else {
  64138. isMasked = false;
  64139. }
  64140. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64141. mesh._activate(sceneRenderId);
  64142. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64143. var subMesh = mesh.subMeshes[subIndex];
  64144. scene._activeIndices.addCount(subMesh.indexCount, false);
  64145. this._renderingManager.dispatch(subMesh, mesh);
  64146. }
  64147. }
  64148. }
  64149. }
  64150. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64151. var particleSystem = scene.particleSystems[particleIndex];
  64152. var emitter = particleSystem.emitter;
  64153. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64154. continue;
  64155. }
  64156. if (currentRenderList.indexOf(emitter) >= 0) {
  64157. this._renderingManager.dispatchParticles(particleSystem);
  64158. }
  64159. }
  64160. if (this.isCube) {
  64161. for (var face = 0; face < 6; face++) {
  64162. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64163. scene.incrementRenderId();
  64164. scene.resetCachedMaterial();
  64165. }
  64166. }
  64167. else {
  64168. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64169. }
  64170. this.onAfterUnbindObservable.notifyObservers(this);
  64171. if (scene.activeCamera) {
  64172. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64173. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64174. }
  64175. engine.setViewport(scene.activeCamera.viewport);
  64176. }
  64177. scene.resetCachedMaterial();
  64178. };
  64179. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64180. var minimum = 128;
  64181. var x = renderDimension * scale;
  64182. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64183. // Ensure we don't exceed the render dimension (while staying POT)
  64184. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64185. };
  64186. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64187. var _this = this;
  64188. if (!this._texture) {
  64189. return;
  64190. }
  64191. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64192. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64193. });
  64194. };
  64195. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64196. var scene = this.getScene();
  64197. if (!scene) {
  64198. return;
  64199. }
  64200. var engine = scene.getEngine();
  64201. if (!this._texture) {
  64202. return;
  64203. }
  64204. // Bind
  64205. if (this._postProcessManager) {
  64206. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64207. }
  64208. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64209. if (this._texture) {
  64210. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64211. }
  64212. }
  64213. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64214. // Clear
  64215. if (this.onClearObservable.hasObservers()) {
  64216. this.onClearObservable.notifyObservers(engine);
  64217. }
  64218. else {
  64219. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64220. }
  64221. if (!this._doNotChangeAspectRatio) {
  64222. scene.updateTransformMatrix(true);
  64223. }
  64224. // Render
  64225. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64226. if (this._postProcessManager) {
  64227. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64228. }
  64229. else if (useCameraPostProcess) {
  64230. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64231. }
  64232. if (!this._doNotChangeAspectRatio) {
  64233. scene.updateTransformMatrix(true);
  64234. }
  64235. // Dump ?
  64236. if (dumpForDebug) {
  64237. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64238. }
  64239. // Unbind
  64240. if (!this.isCube || faceIndex === 5) {
  64241. if (this.isCube) {
  64242. if (faceIndex === 5) {
  64243. engine.generateMipMapsForCubemap(this._texture);
  64244. }
  64245. }
  64246. this.unbindFrameBuffer(engine, faceIndex);
  64247. }
  64248. else {
  64249. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64250. }
  64251. };
  64252. /**
  64253. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64254. * This allowed control for front to back rendering or reversly depending of the special needs.
  64255. *
  64256. * @param renderingGroupId The rendering group id corresponding to its index
  64257. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64258. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64259. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64260. */
  64261. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64262. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64263. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64264. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64265. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64266. };
  64267. /**
  64268. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64269. *
  64270. * @param renderingGroupId The rendering group id corresponding to its index
  64271. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64272. */
  64273. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64274. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64275. };
  64276. RenderTargetTexture.prototype.clone = function () {
  64277. var textureSize = this.getSize();
  64278. 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);
  64279. // Base texture
  64280. newTexture.hasAlpha = this.hasAlpha;
  64281. newTexture.level = this.level;
  64282. // RenderTarget Texture
  64283. newTexture.coordinatesMode = this.coordinatesMode;
  64284. if (this.renderList) {
  64285. newTexture.renderList = this.renderList.slice(0);
  64286. }
  64287. return newTexture;
  64288. };
  64289. RenderTargetTexture.prototype.serialize = function () {
  64290. if (!this.name) {
  64291. return null;
  64292. }
  64293. var serializationObject = _super.prototype.serialize.call(this);
  64294. serializationObject.renderTargetSize = this.getRenderSize();
  64295. serializationObject.renderList = [];
  64296. if (this.renderList) {
  64297. for (var index = 0; index < this.renderList.length; index++) {
  64298. serializationObject.renderList.push(this.renderList[index].id);
  64299. }
  64300. }
  64301. return serializationObject;
  64302. };
  64303. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64304. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64305. var objBuffer = this.getInternalTexture();
  64306. var scene = this.getScene();
  64307. if (objBuffer && scene) {
  64308. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64309. }
  64310. };
  64311. RenderTargetTexture.prototype.dispose = function () {
  64312. if (this._postProcessManager) {
  64313. this._postProcessManager.dispose();
  64314. this._postProcessManager = null;
  64315. }
  64316. this.clearPostProcesses(true);
  64317. if (this._resizeObserver) {
  64318. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64319. this._resizeObserver = null;
  64320. }
  64321. this.renderList = null;
  64322. // Remove from custom render targets
  64323. var scene = this.getScene();
  64324. if (!scene) {
  64325. return;
  64326. }
  64327. var index = scene.customRenderTargets.indexOf(this);
  64328. if (index >= 0) {
  64329. scene.customRenderTargets.splice(index, 1);
  64330. }
  64331. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64332. var camera = _a[_i];
  64333. index = camera.customRenderTargets.indexOf(this);
  64334. if (index >= 0) {
  64335. camera.customRenderTargets.splice(index, 1);
  64336. }
  64337. }
  64338. _super.prototype.dispose.call(this);
  64339. };
  64340. RenderTargetTexture.prototype._rebuild = function () {
  64341. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64342. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64343. }
  64344. if (this._postProcessManager) {
  64345. this._postProcessManager._rebuild();
  64346. }
  64347. };
  64348. /**
  64349. * Clear the info related to rendering groups preventing retention point in material dispose.
  64350. */
  64351. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64352. if (this._renderingManager) {
  64353. this._renderingManager.freeRenderingGroups();
  64354. }
  64355. };
  64356. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64357. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64358. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64359. return RenderTargetTexture;
  64360. }(BABYLON.Texture));
  64361. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64362. })(BABYLON || (BABYLON = {}));
  64363. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64364. var BABYLON;
  64365. (function (BABYLON) {
  64366. ;
  64367. var MultiRenderTarget = /** @class */ (function (_super) {
  64368. __extends(MultiRenderTarget, _super);
  64369. function MultiRenderTarget(name, size, count, scene, options) {
  64370. var _this = this;
  64371. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64372. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64373. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64374. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64375. _this._engine = scene.getEngine();
  64376. if (!_this.isSupported) {
  64377. _this.dispose();
  64378. return;
  64379. }
  64380. var types = [];
  64381. var samplingModes = [];
  64382. for (var i = 0; i < count; i++) {
  64383. if (options && options.types && options.types[i] !== undefined) {
  64384. types.push(options.types[i]);
  64385. }
  64386. else {
  64387. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64388. }
  64389. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64390. samplingModes.push(options.samplingModes[i]);
  64391. }
  64392. else {
  64393. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64394. }
  64395. }
  64396. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64397. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64398. _this._size = size;
  64399. _this._multiRenderTargetOptions = {
  64400. samplingModes: samplingModes,
  64401. generateMipMaps: generateMipMaps,
  64402. generateDepthBuffer: generateDepthBuffer,
  64403. generateStencilBuffer: generateStencilBuffer,
  64404. generateDepthTexture: generateDepthTexture,
  64405. types: types,
  64406. textureCount: count
  64407. };
  64408. _this._createInternalTextures();
  64409. _this._createTextures();
  64410. return _this;
  64411. }
  64412. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64413. get: function () {
  64414. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64415. },
  64416. enumerable: true,
  64417. configurable: true
  64418. });
  64419. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64420. get: function () {
  64421. return this._textures;
  64422. },
  64423. enumerable: true,
  64424. configurable: true
  64425. });
  64426. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64427. get: function () {
  64428. return this._textures[this._textures.length - 1];
  64429. },
  64430. enumerable: true,
  64431. configurable: true
  64432. });
  64433. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64434. set: function (wrap) {
  64435. if (this._textures) {
  64436. for (var i = 0; i < this._textures.length; i++) {
  64437. this._textures[i].wrapU = wrap;
  64438. }
  64439. }
  64440. },
  64441. enumerable: true,
  64442. configurable: true
  64443. });
  64444. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64445. set: function (wrap) {
  64446. if (this._textures) {
  64447. for (var i = 0; i < this._textures.length; i++) {
  64448. this._textures[i].wrapV = wrap;
  64449. }
  64450. }
  64451. },
  64452. enumerable: true,
  64453. configurable: true
  64454. });
  64455. MultiRenderTarget.prototype._rebuild = function () {
  64456. this.releaseInternalTextures();
  64457. this._createInternalTextures();
  64458. for (var i = 0; i < this._internalTextures.length; i++) {
  64459. var texture = this._textures[i];
  64460. texture._texture = this._internalTextures[i];
  64461. }
  64462. // Keeps references to frame buffer and stencil/depth buffer
  64463. this._texture = this._internalTextures[0];
  64464. };
  64465. MultiRenderTarget.prototype._createInternalTextures = function () {
  64466. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64467. };
  64468. MultiRenderTarget.prototype._createTextures = function () {
  64469. this._textures = [];
  64470. for (var i = 0; i < this._internalTextures.length; i++) {
  64471. var texture = new BABYLON.Texture(null, this.getScene());
  64472. texture._texture = this._internalTextures[i];
  64473. this._textures.push(texture);
  64474. }
  64475. // Keeps references to frame buffer and stencil/depth buffer
  64476. this._texture = this._internalTextures[0];
  64477. };
  64478. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64479. get: function () {
  64480. return this._samples;
  64481. },
  64482. set: function (value) {
  64483. if (this._samples === value) {
  64484. return;
  64485. }
  64486. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64487. },
  64488. enumerable: true,
  64489. configurable: true
  64490. });
  64491. MultiRenderTarget.prototype.resize = function (size) {
  64492. this.releaseInternalTextures();
  64493. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64494. this._createInternalTextures();
  64495. };
  64496. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64497. var _this = this;
  64498. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64499. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64500. });
  64501. };
  64502. MultiRenderTarget.prototype.dispose = function () {
  64503. this.releaseInternalTextures();
  64504. _super.prototype.dispose.call(this);
  64505. };
  64506. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64507. if (!this._internalTextures) {
  64508. return;
  64509. }
  64510. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64511. if (this._internalTextures[i] !== undefined) {
  64512. this._internalTextures[i].dispose();
  64513. this._internalTextures.splice(i, 1);
  64514. }
  64515. }
  64516. };
  64517. return MultiRenderTarget;
  64518. }(BABYLON.RenderTargetTexture));
  64519. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64520. })(BABYLON || (BABYLON = {}));
  64521. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64522. var BABYLON;
  64523. (function (BABYLON) {
  64524. var MirrorTexture = /** @class */ (function (_super) {
  64525. __extends(MirrorTexture, _super);
  64526. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64527. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64529. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64530. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64531. _this.scene = scene;
  64532. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64533. _this._transformMatrix = BABYLON.Matrix.Zero();
  64534. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64535. _this._adaptiveBlurKernel = 0;
  64536. _this._blurKernelX = 0;
  64537. _this._blurKernelY = 0;
  64538. _this._blurRatio = 1.0;
  64539. _this.ignoreCameraViewport = true;
  64540. _this._updateGammaSpace();
  64541. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64542. _this._updateGammaSpace;
  64543. });
  64544. _this.onBeforeRenderObservable.add(function () {
  64545. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64546. _this._savedViewMatrix = scene.getViewMatrix();
  64547. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64548. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64549. scene.clipPlane = _this.mirrorPlane;
  64550. scene.getEngine().cullBackFaces = false;
  64551. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64552. });
  64553. _this.onAfterRenderObservable.add(function () {
  64554. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64555. scene.getEngine().cullBackFaces = true;
  64556. scene._mirroredCameraPosition = null;
  64557. delete scene.clipPlane;
  64558. });
  64559. return _this;
  64560. }
  64561. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64562. get: function () {
  64563. return this._blurRatio;
  64564. },
  64565. set: function (value) {
  64566. if (this._blurRatio === value) {
  64567. return;
  64568. }
  64569. this._blurRatio = value;
  64570. this._preparePostProcesses();
  64571. },
  64572. enumerable: true,
  64573. configurable: true
  64574. });
  64575. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64576. set: function (value) {
  64577. this._adaptiveBlurKernel = value;
  64578. this._autoComputeBlurKernel();
  64579. },
  64580. enumerable: true,
  64581. configurable: true
  64582. });
  64583. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64584. set: function (value) {
  64585. this.blurKernelX = value;
  64586. this.blurKernelY = value;
  64587. },
  64588. enumerable: true,
  64589. configurable: true
  64590. });
  64591. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64592. get: function () {
  64593. return this._blurKernelX;
  64594. },
  64595. set: function (value) {
  64596. if (this._blurKernelX === value) {
  64597. return;
  64598. }
  64599. this._blurKernelX = value;
  64600. this._preparePostProcesses();
  64601. },
  64602. enumerable: true,
  64603. configurable: true
  64604. });
  64605. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64606. get: function () {
  64607. return this._blurKernelY;
  64608. },
  64609. set: function (value) {
  64610. if (this._blurKernelY === value) {
  64611. return;
  64612. }
  64613. this._blurKernelY = value;
  64614. this._preparePostProcesses();
  64615. },
  64616. enumerable: true,
  64617. configurable: true
  64618. });
  64619. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64620. var engine = this.getScene().getEngine();
  64621. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64622. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64623. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64624. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64625. };
  64626. MirrorTexture.prototype._onRatioRescale = function () {
  64627. if (this._sizeRatio) {
  64628. this.resize(this._initialSizeParameter);
  64629. if (!this._adaptiveBlurKernel) {
  64630. this._preparePostProcesses();
  64631. }
  64632. }
  64633. if (this._adaptiveBlurKernel) {
  64634. this._autoComputeBlurKernel();
  64635. }
  64636. };
  64637. MirrorTexture.prototype._updateGammaSpace = function () {
  64638. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64639. };
  64640. MirrorTexture.prototype._preparePostProcesses = function () {
  64641. this.clearPostProcesses(true);
  64642. if (this._blurKernelX && this._blurKernelY) {
  64643. var engine = this.getScene().getEngine();
  64644. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64645. 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);
  64646. this._blurX.autoClear = false;
  64647. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64648. this._blurX.inputTexture = this._texture;
  64649. }
  64650. else {
  64651. this._blurX.alwaysForcePOT = true;
  64652. }
  64653. 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);
  64654. this._blurY.autoClear = false;
  64655. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64656. this.addPostProcess(this._blurX);
  64657. this.addPostProcess(this._blurY);
  64658. }
  64659. else {
  64660. if (this._blurY) {
  64661. this.removePostProcess(this._blurY);
  64662. this._blurY.dispose();
  64663. this._blurY = null;
  64664. }
  64665. if (this._blurX) {
  64666. this.removePostProcess(this._blurX);
  64667. this._blurX.dispose();
  64668. this._blurX = null;
  64669. }
  64670. }
  64671. };
  64672. MirrorTexture.prototype.clone = function () {
  64673. var scene = this.getScene();
  64674. if (!scene) {
  64675. return this;
  64676. }
  64677. var textureSize = this.getSize();
  64678. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64679. // Base texture
  64680. newTexture.hasAlpha = this.hasAlpha;
  64681. newTexture.level = this.level;
  64682. // Mirror Texture
  64683. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64684. if (this.renderList) {
  64685. newTexture.renderList = this.renderList.slice(0);
  64686. }
  64687. return newTexture;
  64688. };
  64689. MirrorTexture.prototype.serialize = function () {
  64690. if (!this.name) {
  64691. return null;
  64692. }
  64693. var serializationObject = _super.prototype.serialize.call(this);
  64694. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64695. return serializationObject;
  64696. };
  64697. MirrorTexture.prototype.dispose = function () {
  64698. _super.prototype.dispose.call(this);
  64699. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64700. };
  64701. return MirrorTexture;
  64702. }(BABYLON.RenderTargetTexture));
  64703. BABYLON.MirrorTexture = MirrorTexture;
  64704. })(BABYLON || (BABYLON = {}));
  64705. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64706. var BABYLON;
  64707. (function (BABYLON) {
  64708. /**
  64709. * Creates a refraction texture used by refraction channel of the standard material.
  64710. * @param name the texture name
  64711. * @param size size of the underlying texture
  64712. * @param scene root scene
  64713. */
  64714. var RefractionTexture = /** @class */ (function (_super) {
  64715. __extends(RefractionTexture, _super);
  64716. function RefractionTexture(name, size, scene, generateMipMaps) {
  64717. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64718. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64719. _this.depth = 2.0;
  64720. _this.onBeforeRenderObservable.add(function () {
  64721. scene.clipPlane = _this.refractionPlane;
  64722. });
  64723. _this.onAfterRenderObservable.add(function () {
  64724. delete scene.clipPlane;
  64725. });
  64726. return _this;
  64727. }
  64728. RefractionTexture.prototype.clone = function () {
  64729. var scene = this.getScene();
  64730. if (!scene) {
  64731. return this;
  64732. }
  64733. var textureSize = this.getSize();
  64734. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64735. // Base texture
  64736. newTexture.hasAlpha = this.hasAlpha;
  64737. newTexture.level = this.level;
  64738. // Refraction Texture
  64739. newTexture.refractionPlane = this.refractionPlane.clone();
  64740. if (this.renderList) {
  64741. newTexture.renderList = this.renderList.slice(0);
  64742. }
  64743. newTexture.depth = this.depth;
  64744. return newTexture;
  64745. };
  64746. RefractionTexture.prototype.serialize = function () {
  64747. if (!this.name) {
  64748. return null;
  64749. }
  64750. var serializationObject = _super.prototype.serialize.call(this);
  64751. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64752. serializationObject.depth = this.depth;
  64753. return serializationObject;
  64754. };
  64755. return RefractionTexture;
  64756. }(BABYLON.RenderTargetTexture));
  64757. BABYLON.RefractionTexture = RefractionTexture;
  64758. })(BABYLON || (BABYLON = {}));
  64759. //# sourceMappingURL=babylon.refractionTexture.js.map
  64760. var BABYLON;
  64761. (function (BABYLON) {
  64762. /**
  64763. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64764. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64765. */
  64766. var DynamicTexture = /** @class */ (function (_super) {
  64767. __extends(DynamicTexture, _super);
  64768. /**
  64769. * Creates a {BABYLON.DynamicTexture}
  64770. * @param name defines the name of the texture
  64771. * @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
  64772. * @param scene defines the scene where you want the texture
  64773. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64774. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64775. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64776. */
  64777. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64778. if (scene === void 0) { scene = null; }
  64779. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64780. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64781. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64782. _this.name = name;
  64783. _this._engine = _this.getScene().getEngine();
  64784. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64785. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64786. _this._generateMipMaps = generateMipMaps;
  64787. if (options.getContext) {
  64788. _this._canvas = options;
  64789. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64790. }
  64791. else {
  64792. _this._canvas = document.createElement("canvas");
  64793. if (options.width || options.width === 0) {
  64794. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64795. }
  64796. else {
  64797. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64798. }
  64799. }
  64800. var textureSize = _this.getSize();
  64801. _this._canvas.width = textureSize.width;
  64802. _this._canvas.height = textureSize.height;
  64803. _this._context = _this._canvas.getContext("2d");
  64804. return _this;
  64805. }
  64806. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64807. /**
  64808. * Gets the current state of canRescale
  64809. */
  64810. get: function () {
  64811. return true;
  64812. },
  64813. enumerable: true,
  64814. configurable: true
  64815. });
  64816. DynamicTexture.prototype._recreate = function (textureSize) {
  64817. this._canvas.width = textureSize.width;
  64818. this._canvas.height = textureSize.height;
  64819. this.releaseInternalTexture();
  64820. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64821. };
  64822. /**
  64823. * Scales the texture
  64824. * @param ratio the scale factor to apply to both width and height
  64825. */
  64826. DynamicTexture.prototype.scale = function (ratio) {
  64827. var textureSize = this.getSize();
  64828. textureSize.width *= ratio;
  64829. textureSize.height *= ratio;
  64830. this._recreate(textureSize);
  64831. };
  64832. /**
  64833. * Resizes the texture
  64834. * @param width the new width
  64835. * @param height the new height
  64836. */
  64837. DynamicTexture.prototype.scaleTo = function (width, height) {
  64838. var textureSize = this.getSize();
  64839. textureSize.width = width;
  64840. textureSize.height = height;
  64841. this._recreate(textureSize);
  64842. };
  64843. /**
  64844. * Gets the context of the canvas used by the texture
  64845. * @returns the canvas context of the dynamic texture
  64846. */
  64847. DynamicTexture.prototype.getContext = function () {
  64848. return this._context;
  64849. };
  64850. /**
  64851. * Clears the texture
  64852. */
  64853. DynamicTexture.prototype.clear = function () {
  64854. var size = this.getSize();
  64855. this._context.fillRect(0, 0, size.width, size.height);
  64856. };
  64857. /**
  64858. * Updates the texture
  64859. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64860. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64861. */
  64862. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64863. if (premulAlpha === void 0) { premulAlpha = false; }
  64864. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64865. };
  64866. /**
  64867. * Draws text onto the texture
  64868. * @param text defines the text to be drawn
  64869. * @param x defines the placement of the text from the left
  64870. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64871. * @param font defines the font to be used with font-style, font-size, font-name
  64872. * @param color defines the color used for the text
  64873. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64874. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64875. * @param update defines whether texture is immediately update (default is true)
  64876. */
  64877. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64878. if (update === void 0) { update = true; }
  64879. var size = this.getSize();
  64880. if (clearColor) {
  64881. this._context.fillStyle = clearColor;
  64882. this._context.fillRect(0, 0, size.width, size.height);
  64883. }
  64884. this._context.font = font;
  64885. if (x === null || x === undefined) {
  64886. var textSize = this._context.measureText(text);
  64887. x = (size.width - textSize.width) / 2;
  64888. }
  64889. if (y === null || y === undefined) {
  64890. var fontSize = parseInt((font.replace(/\D/g, '')));
  64891. y = (size.height / 2) + (fontSize / 3.65);
  64892. }
  64893. this._context.fillStyle = color;
  64894. this._context.fillText(text, x, y);
  64895. if (update) {
  64896. this.update(invertY);
  64897. }
  64898. };
  64899. /**
  64900. * Clones the texture
  64901. * @returns the clone of the texture.
  64902. */
  64903. DynamicTexture.prototype.clone = function () {
  64904. var scene = this.getScene();
  64905. if (!scene) {
  64906. return this;
  64907. }
  64908. var textureSize = this.getSize();
  64909. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64910. // Base texture
  64911. newTexture.hasAlpha = this.hasAlpha;
  64912. newTexture.level = this.level;
  64913. // Dynamic Texture
  64914. newTexture.wrapU = this.wrapU;
  64915. newTexture.wrapV = this.wrapV;
  64916. return newTexture;
  64917. };
  64918. /** @hidden */
  64919. DynamicTexture.prototype._rebuild = function () {
  64920. this.update();
  64921. };
  64922. return DynamicTexture;
  64923. }(BABYLON.Texture));
  64924. BABYLON.DynamicTexture = DynamicTexture;
  64925. })(BABYLON || (BABYLON = {}));
  64926. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64927. var BABYLON;
  64928. (function (BABYLON) {
  64929. var VideoTexture = /** @class */ (function (_super) {
  64930. __extends(VideoTexture, _super);
  64931. /**
  64932. * Creates a video texture.
  64933. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64934. * @param {string | null} name optional name, will detect from video source, if not defined
  64935. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64936. * @param {BABYLON.Scene} scene is obviously the current scene.
  64937. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64938. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64939. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64940. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64941. */
  64942. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64943. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64944. if (invertY === void 0) { invertY = false; }
  64945. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64946. if (settings === void 0) { settings = {
  64947. autoPlay: true,
  64948. loop: true,
  64949. autoUpdateTexture: true,
  64950. }; }
  64951. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64952. _this._onUserActionRequestedObservable = null;
  64953. _this._stillImageCaptured = false;
  64954. _this._createInternalTexture = function () {
  64955. if (_this._texture != null) {
  64956. return;
  64957. }
  64958. if (!_this._engine.needPOTTextures ||
  64959. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64960. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64961. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64962. }
  64963. else {
  64964. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64965. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64966. _this._generateMipMaps = false;
  64967. }
  64968. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64969. if (!_this.video.autoplay) {
  64970. var oldHandler_1 = _this.video.onplaying;
  64971. var error_1 = false;
  64972. _this.video.onplaying = function () {
  64973. _this.video.onplaying = oldHandler_1;
  64974. _this._texture.isReady = true;
  64975. _this._updateInternalTexture();
  64976. if (!error_1) {
  64977. _this.video.pause();
  64978. }
  64979. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64980. _this.onLoadObservable.notifyObservers(_this);
  64981. }
  64982. };
  64983. var playing = _this.video.play();
  64984. if (playing) {
  64985. playing.then(function () {
  64986. // Everything is good.
  64987. })
  64988. .catch(function () {
  64989. error_1 = true;
  64990. // On Chrome for instance, new policies might prevent playing without user interaction.
  64991. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64992. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64993. }
  64994. });
  64995. }
  64996. else {
  64997. _this.video.onplaying = oldHandler_1;
  64998. _this._texture.isReady = true;
  64999. _this._updateInternalTexture();
  65000. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65001. _this.onLoadObservable.notifyObservers(_this);
  65002. }
  65003. }
  65004. }
  65005. else {
  65006. _this._texture.isReady = true;
  65007. _this._updateInternalTexture();
  65008. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65009. _this.onLoadObservable.notifyObservers(_this);
  65010. }
  65011. }
  65012. };
  65013. _this.reset = function () {
  65014. if (_this._texture == null) {
  65015. return;
  65016. }
  65017. _this._texture.dispose();
  65018. _this._texture = null;
  65019. };
  65020. _this._updateInternalTexture = function (e) {
  65021. if (_this._texture == null || !_this._texture.isReady) {
  65022. return;
  65023. }
  65024. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65025. return;
  65026. }
  65027. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65028. };
  65029. _this._engine = _this.getScene().getEngine();
  65030. _this._generateMipMaps = generateMipMaps;
  65031. _this._samplingMode = samplingMode;
  65032. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65033. _this.name = name || _this._getName(src);
  65034. _this.video = _this._getVideo(src);
  65035. if (settings.poster) {
  65036. _this.video.poster = settings.poster;
  65037. }
  65038. if (settings.autoPlay !== undefined) {
  65039. _this.video.autoplay = settings.autoPlay;
  65040. }
  65041. if (settings.loop !== undefined) {
  65042. _this.video.loop = settings.loop;
  65043. }
  65044. _this.video.setAttribute("playsinline", "");
  65045. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65046. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65047. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65048. _this.video.addEventListener("emptied", _this.reset);
  65049. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65050. _this._createInternalTexture();
  65051. }
  65052. return _this;
  65053. }
  65054. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  65055. get: function () {
  65056. if (!this._onUserActionRequestedObservable) {
  65057. this._onUserActionRequestedObservable = new BABYLON.Observable();
  65058. }
  65059. return this._onUserActionRequestedObservable;
  65060. },
  65061. enumerable: true,
  65062. configurable: true
  65063. });
  65064. VideoTexture.prototype._getName = function (src) {
  65065. if (src instanceof HTMLVideoElement) {
  65066. return src.currentSrc;
  65067. }
  65068. if (typeof src === "object") {
  65069. return src.toString();
  65070. }
  65071. return src;
  65072. };
  65073. ;
  65074. VideoTexture.prototype._getVideo = function (src) {
  65075. if (src instanceof HTMLVideoElement) {
  65076. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65077. return src;
  65078. }
  65079. var video = document.createElement("video");
  65080. if (typeof src === "string") {
  65081. BABYLON.Tools.SetCorsBehavior(src, video);
  65082. video.src = src;
  65083. }
  65084. else {
  65085. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65086. src.forEach(function (url) {
  65087. var source = document.createElement("source");
  65088. source.src = url;
  65089. video.appendChild(source);
  65090. });
  65091. }
  65092. return video;
  65093. };
  65094. ;
  65095. /**
  65096. * Internal method to initiate `update`.
  65097. */
  65098. VideoTexture.prototype._rebuild = function () {
  65099. this.update();
  65100. };
  65101. /**
  65102. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65103. */
  65104. VideoTexture.prototype.update = function () {
  65105. if (!this.autoUpdateTexture) {
  65106. // Expecting user to call `updateTexture` manually
  65107. return;
  65108. }
  65109. this.updateTexture(true);
  65110. };
  65111. /**
  65112. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65113. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65114. */
  65115. VideoTexture.prototype.updateTexture = function (isVisible) {
  65116. if (!isVisible) {
  65117. return;
  65118. }
  65119. if (this.video.paused && this._stillImageCaptured) {
  65120. return;
  65121. }
  65122. this._stillImageCaptured = true;
  65123. this._updateInternalTexture();
  65124. };
  65125. /**
  65126. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65127. * @param url New url.
  65128. */
  65129. VideoTexture.prototype.updateURL = function (url) {
  65130. this.video.src = url;
  65131. };
  65132. VideoTexture.prototype.dispose = function () {
  65133. _super.prototype.dispose.call(this);
  65134. if (this._onUserActionRequestedObservable) {
  65135. this._onUserActionRequestedObservable.clear();
  65136. this._onUserActionRequestedObservable = null;
  65137. }
  65138. this.video.removeEventListener("canplay", this._createInternalTexture);
  65139. this.video.removeEventListener("paused", this._updateInternalTexture);
  65140. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65141. this.video.removeEventListener("emptied", this.reset);
  65142. this.video.pause();
  65143. };
  65144. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65145. var video = document.createElement("video");
  65146. video.setAttribute('autoplay', '');
  65147. video.setAttribute('muted', '');
  65148. video.setAttribute('playsinline', '');
  65149. var constraintsDeviceId;
  65150. if (constraints && constraints.deviceId) {
  65151. constraintsDeviceId = {
  65152. exact: constraints.deviceId,
  65153. };
  65154. }
  65155. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65156. if (navigator.mediaDevices) {
  65157. navigator.mediaDevices.getUserMedia({ video: constraints })
  65158. .then(function (stream) {
  65159. if (video.mozSrcObject !== undefined) {
  65160. // hack for Firefox < 19
  65161. video.mozSrcObject = stream;
  65162. }
  65163. else {
  65164. video.srcObject = stream;
  65165. }
  65166. var onPlaying = function () {
  65167. if (onReady) {
  65168. onReady(new VideoTexture("video", video, scene, true, true));
  65169. }
  65170. video.removeEventListener("playing", onPlaying);
  65171. };
  65172. video.addEventListener("playing", onPlaying);
  65173. video.play();
  65174. })
  65175. .catch(function (err) {
  65176. BABYLON.Tools.Error(err.name);
  65177. });
  65178. }
  65179. else {
  65180. navigator.getUserMedia =
  65181. navigator.getUserMedia ||
  65182. navigator.webkitGetUserMedia ||
  65183. navigator.mozGetUserMedia ||
  65184. navigator.msGetUserMedia;
  65185. if (navigator.getUserMedia) {
  65186. navigator.getUserMedia({
  65187. video: {
  65188. deviceId: constraintsDeviceId,
  65189. width: {
  65190. min: (constraints && constraints.minWidth) || 256,
  65191. max: (constraints && constraints.maxWidth) || 640,
  65192. },
  65193. height: {
  65194. min: (constraints && constraints.minHeight) || 256,
  65195. max: (constraints && constraints.maxHeight) || 480,
  65196. },
  65197. },
  65198. }, function (stream) {
  65199. if (video.mozSrcObject !== undefined) {
  65200. // hack for Firefox < 19
  65201. video.mozSrcObject = stream;
  65202. }
  65203. else {
  65204. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65205. }
  65206. video.play();
  65207. if (onReady) {
  65208. onReady(new VideoTexture("video", video, scene, true, true));
  65209. }
  65210. }, function (e) {
  65211. BABYLON.Tools.Error(e.name);
  65212. });
  65213. }
  65214. }
  65215. };
  65216. return VideoTexture;
  65217. }(BABYLON.Texture));
  65218. BABYLON.VideoTexture = VideoTexture;
  65219. })(BABYLON || (BABYLON = {}));
  65220. //# sourceMappingURL=babylon.videoTexture.js.map
  65221. var BABYLON;
  65222. (function (BABYLON) {
  65223. var RawTexture = /** @class */ (function (_super) {
  65224. __extends(RawTexture, _super);
  65225. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65226. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65227. if (invertY === void 0) { invertY = false; }
  65228. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65229. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65230. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65231. _this.format = format;
  65232. _this._engine = scene.getEngine();
  65233. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65234. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65235. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65236. return _this;
  65237. }
  65238. RawTexture.prototype.update = function (data) {
  65239. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65240. };
  65241. // Statics
  65242. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65243. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65244. if (invertY === void 0) { invertY = false; }
  65245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65246. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65247. };
  65248. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65249. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65250. if (invertY === void 0) { invertY = false; }
  65251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65252. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65253. };
  65254. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65255. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65256. if (invertY === void 0) { invertY = false; }
  65257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65258. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65259. };
  65260. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65261. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65262. if (invertY === void 0) { invertY = false; }
  65263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65264. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65265. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65266. };
  65267. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65268. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65269. if (invertY === void 0) { invertY = false; }
  65270. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65271. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65272. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65273. };
  65274. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65275. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65276. if (invertY === void 0) { invertY = false; }
  65277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65278. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65279. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  65280. };
  65281. return RawTexture;
  65282. }(BABYLON.Texture));
  65283. BABYLON.RawTexture = RawTexture;
  65284. })(BABYLON || (BABYLON = {}));
  65285. //# sourceMappingURL=babylon.rawTexture.js.map
  65286. var BABYLON;
  65287. (function (BABYLON) {
  65288. /**
  65289. * Class used to store 3D textures containing user data
  65290. */
  65291. var RawTexture3D = /** @class */ (function (_super) {
  65292. __extends(RawTexture3D, _super);
  65293. /**
  65294. * Create a new RawTexture3D
  65295. * @param data defines the data of the texture
  65296. * @param width defines the width of the texture
  65297. * @param height defines the height of the texture
  65298. * @param depth defines the depth of the texture
  65299. * @param format defines the texture format to use
  65300. * @param scene defines the hosting scene
  65301. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65302. * @param invertY defines if texture must be stored with Y axis inverted
  65303. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65304. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65305. */
  65306. function RawTexture3D(data, width, height, depth,
  65307. /** Gets or sets the texture format to use */
  65308. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65309. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65310. if (invertY === void 0) { invertY = false; }
  65311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65312. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65313. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65314. _this.format = format;
  65315. _this._engine = scene.getEngine();
  65316. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65317. _this.is3D = true;
  65318. return _this;
  65319. }
  65320. /**
  65321. * Update the texture with new data
  65322. * @param data defines the data to store in the texture
  65323. */
  65324. RawTexture3D.prototype.update = function (data) {
  65325. if (!this._texture) {
  65326. return;
  65327. }
  65328. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65329. };
  65330. return RawTexture3D;
  65331. }(BABYLON.Texture));
  65332. BABYLON.RawTexture3D = RawTexture3D;
  65333. })(BABYLON || (BABYLON = {}));
  65334. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65335. var BABYLON;
  65336. (function (BABYLON) {
  65337. /**
  65338. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65339. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65340. */
  65341. var PostProcessManager = /** @class */ (function () {
  65342. /**
  65343. * Creates a new instance PostProcess
  65344. * @param scene The scene that the post process is associated with.
  65345. */
  65346. function PostProcessManager(scene) {
  65347. this._vertexBuffers = {};
  65348. this._scene = scene;
  65349. }
  65350. PostProcessManager.prototype._prepareBuffers = function () {
  65351. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65352. return;
  65353. }
  65354. // VBO
  65355. var vertices = [];
  65356. vertices.push(1, 1);
  65357. vertices.push(-1, 1);
  65358. vertices.push(-1, -1);
  65359. vertices.push(1, -1);
  65360. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65361. this._buildIndexBuffer();
  65362. };
  65363. PostProcessManager.prototype._buildIndexBuffer = function () {
  65364. // Indices
  65365. var indices = [];
  65366. indices.push(0);
  65367. indices.push(1);
  65368. indices.push(2);
  65369. indices.push(0);
  65370. indices.push(2);
  65371. indices.push(3);
  65372. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65373. };
  65374. /**
  65375. * Rebuilds the vertex buffers of the manager.
  65376. */
  65377. PostProcessManager.prototype._rebuild = function () {
  65378. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65379. if (!vb) {
  65380. return;
  65381. }
  65382. vb._rebuild();
  65383. this._buildIndexBuffer();
  65384. };
  65385. // Methods
  65386. /**
  65387. * Prepares a frame to be run through a post process.
  65388. * @param sourceTexture The input texture to the post procesess. (default: null)
  65389. * @param postProcesses An array of post processes to be run. (default: null)
  65390. * @returns True if the post processes were able to be run.
  65391. */
  65392. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65393. if (sourceTexture === void 0) { sourceTexture = null; }
  65394. if (postProcesses === void 0) { postProcesses = null; }
  65395. var camera = this._scene.activeCamera;
  65396. if (!camera) {
  65397. return false;
  65398. }
  65399. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65400. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65401. return false;
  65402. }
  65403. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65404. return true;
  65405. };
  65406. /**
  65407. * Manually render a set of post processes to a texture.
  65408. * @param postProcesses An array of post processes to be run.
  65409. * @param targetTexture The target texture to render to.
  65410. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65411. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65412. * @param lodLevel defines which lod of the texture to render to
  65413. */
  65414. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65415. if (targetTexture === void 0) { targetTexture = null; }
  65416. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65417. if (faceIndex === void 0) { faceIndex = 0; }
  65418. if (lodLevel === void 0) { lodLevel = 0; }
  65419. var engine = this._scene.getEngine();
  65420. for (var index = 0; index < postProcesses.length; index++) {
  65421. if (index < postProcesses.length - 1) {
  65422. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65423. }
  65424. else {
  65425. if (targetTexture) {
  65426. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65427. }
  65428. else {
  65429. engine.restoreDefaultFramebuffer();
  65430. }
  65431. }
  65432. var pp = postProcesses[index];
  65433. var effect = pp.apply();
  65434. if (effect) {
  65435. pp.onBeforeRenderObservable.notifyObservers(effect);
  65436. // VBOs
  65437. this._prepareBuffers();
  65438. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65439. // Draw order
  65440. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65441. pp.onAfterRenderObservable.notifyObservers(effect);
  65442. }
  65443. }
  65444. // Restore depth buffer
  65445. engine.setDepthBuffer(true);
  65446. engine.setDepthWrite(true);
  65447. };
  65448. /**
  65449. * Finalize the result of the output of the postprocesses.
  65450. * @param doNotPresent If true the result will not be displayed to the screen.
  65451. * @param targetTexture The target texture to render to.
  65452. * @param faceIndex The index of the face to bind the target texture to.
  65453. * @param postProcesses The array of post processes to render.
  65454. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65455. */
  65456. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65457. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65458. var camera = this._scene.activeCamera;
  65459. if (!camera) {
  65460. return;
  65461. }
  65462. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65463. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65464. return;
  65465. }
  65466. var engine = this._scene.getEngine();
  65467. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65468. var pp = postProcesses[index];
  65469. if (index < len - 1) {
  65470. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65471. }
  65472. else {
  65473. if (targetTexture) {
  65474. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65475. pp._outputTexture = targetTexture;
  65476. }
  65477. else {
  65478. engine.restoreDefaultFramebuffer();
  65479. pp._outputTexture = null;
  65480. }
  65481. }
  65482. if (doNotPresent) {
  65483. break;
  65484. }
  65485. var effect = pp.apply();
  65486. if (effect) {
  65487. pp.onBeforeRenderObservable.notifyObservers(effect);
  65488. // VBOs
  65489. this._prepareBuffers();
  65490. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65491. // Draw order
  65492. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65493. pp.onAfterRenderObservable.notifyObservers(effect);
  65494. }
  65495. }
  65496. // Restore states
  65497. engine.setDepthBuffer(true);
  65498. engine.setDepthWrite(true);
  65499. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65500. };
  65501. /**
  65502. * Disposes of the post process manager.
  65503. */
  65504. PostProcessManager.prototype.dispose = function () {
  65505. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65506. if (buffer) {
  65507. buffer.dispose();
  65508. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65509. }
  65510. if (this._indexBuffer) {
  65511. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65512. this._indexBuffer = null;
  65513. }
  65514. };
  65515. return PostProcessManager;
  65516. }());
  65517. BABYLON.PostProcessManager = PostProcessManager;
  65518. })(BABYLON || (BABYLON = {}));
  65519. //# sourceMappingURL=babylon.postProcessManager.js.map
  65520. var BABYLON;
  65521. (function (BABYLON) {
  65522. /**
  65523. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65524. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65525. */
  65526. var PostProcess = /** @class */ (function () {
  65527. /**
  65528. * Creates a new instance PostProcess
  65529. * @param name The name of the PostProcess.
  65530. * @param fragmentUrl The url of the fragment shader to be used.
  65531. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65532. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65533. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65534. * @param camera The camera to apply the render pass to.
  65535. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65536. * @param engine The engine which the post process will be applied. (default: current engine)
  65537. * @param reusable If the post process can be reused on the same frame. (default: false)
  65538. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65539. * @param textureType Type of textures used when performing the post process. (default: 0)
  65540. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65541. * @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
  65542. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65543. */
  65544. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65546. if (defines === void 0) { defines = null; }
  65547. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65548. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65549. if (blockCompilation === void 0) { blockCompilation = false; }
  65550. this.name = name;
  65551. /**
  65552. * Width of the texture to apply the post process on
  65553. */
  65554. this.width = -1;
  65555. /**
  65556. * Height of the texture to apply the post process on
  65557. */
  65558. this.height = -1;
  65559. /**
  65560. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65561. */
  65562. this._outputTexture = null;
  65563. /**
  65564. * If the buffer needs to be cleared before applying the post process. (default: true)
  65565. * Should be set to false if shader will overwrite all previous pixels.
  65566. */
  65567. this.autoClear = true;
  65568. /**
  65569. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65570. */
  65571. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65572. /**
  65573. * Animations to be used for the post processing
  65574. */
  65575. this.animations = new Array();
  65576. /**
  65577. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65578. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65579. */
  65580. this.enablePixelPerfectMode = false;
  65581. /**
  65582. * Force the postprocess to be applied without taking in account viewport
  65583. */
  65584. this.forceFullscreenViewport = true;
  65585. /**
  65586. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65587. *
  65588. * | Value | Type | Description |
  65589. * | ----- | ----------------------------------- | ----------- |
  65590. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65591. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65592. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65593. *
  65594. */
  65595. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65596. /**
  65597. * Force textures to be a power of two (default: false)
  65598. */
  65599. this.alwaysForcePOT = false;
  65600. /**
  65601. * Number of sample textures (default: 1)
  65602. */
  65603. this.samples = 1;
  65604. /**
  65605. * Modify the scale of the post process to be the same as the viewport (default: false)
  65606. */
  65607. this.adaptScaleToCurrentViewport = false;
  65608. this._reusable = false;
  65609. /**
  65610. * Smart array of input and output textures for the post process.
  65611. */
  65612. this._textures = new BABYLON.SmartArray(2);
  65613. /**
  65614. * The index in _textures that corresponds to the output texture.
  65615. */
  65616. this._currentRenderTextureInd = 0;
  65617. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65618. this._texelSize = BABYLON.Vector2.Zero();
  65619. // Events
  65620. /**
  65621. * An event triggered when the postprocess is activated.
  65622. */
  65623. this.onActivateObservable = new BABYLON.Observable();
  65624. /**
  65625. * An event triggered when the postprocess changes its size.
  65626. */
  65627. this.onSizeChangedObservable = new BABYLON.Observable();
  65628. /**
  65629. * An event triggered when the postprocess applies its effect.
  65630. */
  65631. this.onApplyObservable = new BABYLON.Observable();
  65632. /**
  65633. * An event triggered before rendering the postprocess
  65634. */
  65635. this.onBeforeRenderObservable = new BABYLON.Observable();
  65636. /**
  65637. * An event triggered after rendering the postprocess
  65638. */
  65639. this.onAfterRenderObservable = new BABYLON.Observable();
  65640. if (camera != null) {
  65641. this._camera = camera;
  65642. this._scene = camera.getScene();
  65643. camera.attachPostProcess(this);
  65644. this._engine = this._scene.getEngine();
  65645. this._scene.postProcesses.push(this);
  65646. }
  65647. else if (engine) {
  65648. this._engine = engine;
  65649. this._engine.postProcesses.push(this);
  65650. }
  65651. this._options = options;
  65652. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65653. this._reusable = reusable || false;
  65654. this._textureType = textureType;
  65655. this._samplers = samplers || [];
  65656. this._samplers.push("textureSampler");
  65657. this._fragmentUrl = fragmentUrl;
  65658. this._vertexUrl = vertexUrl;
  65659. this._parameters = parameters || [];
  65660. this._parameters.push("scale");
  65661. this._indexParameters = indexParameters;
  65662. if (!blockCompilation) {
  65663. this.updateEffect(defines);
  65664. }
  65665. }
  65666. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65667. /**
  65668. * A function that is added to the onActivateObservable
  65669. */
  65670. set: function (callback) {
  65671. if (this._onActivateObserver) {
  65672. this.onActivateObservable.remove(this._onActivateObserver);
  65673. }
  65674. if (callback) {
  65675. this._onActivateObserver = this.onActivateObservable.add(callback);
  65676. }
  65677. },
  65678. enumerable: true,
  65679. configurable: true
  65680. });
  65681. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65682. /**
  65683. * A function that is added to the onSizeChangedObservable
  65684. */
  65685. set: function (callback) {
  65686. if (this._onSizeChangedObserver) {
  65687. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65688. }
  65689. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65690. },
  65691. enumerable: true,
  65692. configurable: true
  65693. });
  65694. Object.defineProperty(PostProcess.prototype, "onApply", {
  65695. /**
  65696. * A function that is added to the onApplyObservable
  65697. */
  65698. set: function (callback) {
  65699. if (this._onApplyObserver) {
  65700. this.onApplyObservable.remove(this._onApplyObserver);
  65701. }
  65702. this._onApplyObserver = this.onApplyObservable.add(callback);
  65703. },
  65704. enumerable: true,
  65705. configurable: true
  65706. });
  65707. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65708. /**
  65709. * A function that is added to the onBeforeRenderObservable
  65710. */
  65711. set: function (callback) {
  65712. if (this._onBeforeRenderObserver) {
  65713. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65714. }
  65715. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65716. },
  65717. enumerable: true,
  65718. configurable: true
  65719. });
  65720. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65721. /**
  65722. * A function that is added to the onAfterRenderObservable
  65723. */
  65724. set: function (callback) {
  65725. if (this._onAfterRenderObserver) {
  65726. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65727. }
  65728. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65729. },
  65730. enumerable: true,
  65731. configurable: true
  65732. });
  65733. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65734. /**
  65735. * 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
  65736. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65737. */
  65738. get: function () {
  65739. return this._textures.data[this._currentRenderTextureInd];
  65740. },
  65741. set: function (value) {
  65742. this._forcedOutputTexture = value;
  65743. },
  65744. enumerable: true,
  65745. configurable: true
  65746. });
  65747. /**
  65748. * Gets the camera which post process is applied to.
  65749. * @returns The camera the post process is applied to.
  65750. */
  65751. PostProcess.prototype.getCamera = function () {
  65752. return this._camera;
  65753. };
  65754. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65755. /**
  65756. * Gets the texel size of the postprocess.
  65757. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65758. */
  65759. get: function () {
  65760. if (this._shareOutputWithPostProcess) {
  65761. return this._shareOutputWithPostProcess.texelSize;
  65762. }
  65763. if (this._forcedOutputTexture) {
  65764. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65765. }
  65766. return this._texelSize;
  65767. },
  65768. enumerable: true,
  65769. configurable: true
  65770. });
  65771. /**
  65772. * Gets the engine which this post process belongs to.
  65773. * @returns The engine the post process was enabled with.
  65774. */
  65775. PostProcess.prototype.getEngine = function () {
  65776. return this._engine;
  65777. };
  65778. /**
  65779. * The effect that is created when initializing the post process.
  65780. * @returns The created effect corrisponding the the postprocess.
  65781. */
  65782. PostProcess.prototype.getEffect = function () {
  65783. return this._effect;
  65784. };
  65785. /**
  65786. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65787. * @param postProcess The post process to share the output with.
  65788. * @returns This post process.
  65789. */
  65790. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65791. this._disposeTextures();
  65792. this._shareOutputWithPostProcess = postProcess;
  65793. return this;
  65794. };
  65795. /**
  65796. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65797. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65798. */
  65799. PostProcess.prototype.useOwnOutput = function () {
  65800. if (this._textures.length == 0) {
  65801. this._textures = new BABYLON.SmartArray(2);
  65802. }
  65803. this._shareOutputWithPostProcess = null;
  65804. };
  65805. /**
  65806. * Updates the effect with the current post process compile time values and recompiles the shader.
  65807. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65808. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65809. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65810. * @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
  65811. * @param onCompiled Called when the shader has been compiled.
  65812. * @param onError Called if there is an error when compiling a shader.
  65813. */
  65814. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65815. if (defines === void 0) { defines = null; }
  65816. if (uniforms === void 0) { uniforms = null; }
  65817. if (samplers === void 0) { samplers = null; }
  65818. 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);
  65819. };
  65820. /**
  65821. * The post process is reusable if it can be used multiple times within one frame.
  65822. * @returns If the post process is reusable
  65823. */
  65824. PostProcess.prototype.isReusable = function () {
  65825. return this._reusable;
  65826. };
  65827. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65828. PostProcess.prototype.markTextureDirty = function () {
  65829. this.width = -1;
  65830. };
  65831. /**
  65832. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65833. * 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.
  65834. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65835. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65836. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65837. * @returns The target texture that was bound to be written to.
  65838. */
  65839. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65840. var _this = this;
  65841. if (sourceTexture === void 0) { sourceTexture = null; }
  65842. camera = camera || this._camera;
  65843. var scene = camera.getScene();
  65844. var engine = scene.getEngine();
  65845. var maxSize = engine.getCaps().maxTextureSize;
  65846. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65847. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65848. // 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
  65849. var webVRCamera = camera.parent;
  65850. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65851. requiredWidth /= 2;
  65852. }
  65853. var desiredWidth = (this._options.width || requiredWidth);
  65854. var desiredHeight = this._options.height || requiredHeight;
  65855. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65856. if (this.adaptScaleToCurrentViewport) {
  65857. var currentViewport = engine.currentViewport;
  65858. if (currentViewport) {
  65859. desiredWidth *= currentViewport.width;
  65860. desiredHeight *= currentViewport.height;
  65861. }
  65862. }
  65863. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65864. if (!this._options.width) {
  65865. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65866. }
  65867. if (!this._options.height) {
  65868. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65869. }
  65870. }
  65871. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65872. if (this._textures.length > 0) {
  65873. for (var i = 0; i < this._textures.length; i++) {
  65874. this._engine._releaseTexture(this._textures.data[i]);
  65875. }
  65876. this._textures.reset();
  65877. }
  65878. this.width = desiredWidth;
  65879. this.height = desiredHeight;
  65880. var textureSize = { width: this.width, height: this.height };
  65881. var textureOptions = {
  65882. generateMipMaps: false,
  65883. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65884. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65885. samplingMode: this.renderTargetSamplingMode,
  65886. type: this._textureType
  65887. };
  65888. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65889. if (this._reusable) {
  65890. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65891. }
  65892. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65893. this.onSizeChangedObservable.notifyObservers(this);
  65894. }
  65895. this._textures.forEach(function (texture) {
  65896. if (texture.samples !== _this.samples) {
  65897. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65898. }
  65899. });
  65900. }
  65901. var target;
  65902. if (this._shareOutputWithPostProcess) {
  65903. target = this._shareOutputWithPostProcess.inputTexture;
  65904. }
  65905. else if (this._forcedOutputTexture) {
  65906. target = this._forcedOutputTexture;
  65907. this.width = this._forcedOutputTexture.width;
  65908. this.height = this._forcedOutputTexture.height;
  65909. }
  65910. else {
  65911. target = this.inputTexture;
  65912. }
  65913. // Bind the input of this post process to be used as the output of the previous post process.
  65914. if (this.enablePixelPerfectMode) {
  65915. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65916. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65917. }
  65918. else {
  65919. this._scaleRatio.copyFromFloats(1, 1);
  65920. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65921. }
  65922. this.onActivateObservable.notifyObservers(camera);
  65923. // Clear
  65924. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65925. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65926. }
  65927. if (this._reusable) {
  65928. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65929. }
  65930. return target;
  65931. };
  65932. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65933. /**
  65934. * If the post process is supported.
  65935. */
  65936. get: function () {
  65937. return this._effect.isSupported;
  65938. },
  65939. enumerable: true,
  65940. configurable: true
  65941. });
  65942. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65943. /**
  65944. * The aspect ratio of the output texture.
  65945. */
  65946. get: function () {
  65947. if (this._shareOutputWithPostProcess) {
  65948. return this._shareOutputWithPostProcess.aspectRatio;
  65949. }
  65950. if (this._forcedOutputTexture) {
  65951. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65952. }
  65953. return this.width / this.height;
  65954. },
  65955. enumerable: true,
  65956. configurable: true
  65957. });
  65958. /**
  65959. * Get a value indicating if the post-process is ready to be used
  65960. * @returns true if the post-process is ready (shader is compiled)
  65961. */
  65962. PostProcess.prototype.isReady = function () {
  65963. return this._effect && this._effect.isReady();
  65964. };
  65965. /**
  65966. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65967. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65968. */
  65969. PostProcess.prototype.apply = function () {
  65970. // Check
  65971. if (!this._effect || !this._effect.isReady())
  65972. return null;
  65973. // States
  65974. this._engine.enableEffect(this._effect);
  65975. this._engine.setState(false);
  65976. this._engine.setDepthBuffer(false);
  65977. this._engine.setDepthWrite(false);
  65978. // Alpha
  65979. this._engine.setAlphaMode(this.alphaMode);
  65980. if (this.alphaConstants) {
  65981. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65982. }
  65983. // Bind the output texture of the preivous post process as the input to this post process.
  65984. var source;
  65985. if (this._shareOutputWithPostProcess) {
  65986. source = this._shareOutputWithPostProcess.inputTexture;
  65987. }
  65988. else if (this._forcedOutputTexture) {
  65989. source = this._forcedOutputTexture;
  65990. }
  65991. else {
  65992. source = this.inputTexture;
  65993. }
  65994. this._effect._bindTexture("textureSampler", source);
  65995. // Parameters
  65996. this._effect.setVector2("scale", this._scaleRatio);
  65997. this.onApplyObservable.notifyObservers(this._effect);
  65998. return this._effect;
  65999. };
  66000. PostProcess.prototype._disposeTextures = function () {
  66001. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  66002. return;
  66003. }
  66004. if (this._textures.length > 0) {
  66005. for (var i = 0; i < this._textures.length; i++) {
  66006. this._engine._releaseTexture(this._textures.data[i]);
  66007. }
  66008. }
  66009. this._textures.dispose();
  66010. };
  66011. /**
  66012. * Disposes the post process.
  66013. * @param camera The camera to dispose the post process on.
  66014. */
  66015. PostProcess.prototype.dispose = function (camera) {
  66016. camera = camera || this._camera;
  66017. this._disposeTextures();
  66018. if (this._scene) {
  66019. var index_1 = this._scene.postProcesses.indexOf(this);
  66020. if (index_1 !== -1) {
  66021. this._scene.postProcesses.splice(index_1, 1);
  66022. }
  66023. }
  66024. else {
  66025. var index_2 = this._engine.postProcesses.indexOf(this);
  66026. if (index_2 !== -1) {
  66027. this._engine.postProcesses.splice(index_2, 1);
  66028. }
  66029. }
  66030. if (!camera) {
  66031. return;
  66032. }
  66033. camera.detachPostProcess(this);
  66034. var index = camera._postProcesses.indexOf(this);
  66035. if (index === 0 && camera._postProcesses.length > 0) {
  66036. var firstPostProcess = this._camera._getFirstPostProcess();
  66037. if (firstPostProcess) {
  66038. firstPostProcess.markTextureDirty();
  66039. }
  66040. }
  66041. this.onActivateObservable.clear();
  66042. this.onAfterRenderObservable.clear();
  66043. this.onApplyObservable.clear();
  66044. this.onBeforeRenderObservable.clear();
  66045. this.onSizeChangedObservable.clear();
  66046. };
  66047. return PostProcess;
  66048. }());
  66049. BABYLON.PostProcess = PostProcess;
  66050. })(BABYLON || (BABYLON = {}));
  66051. //# sourceMappingURL=babylon.postProcess.js.map
  66052. var BABYLON;
  66053. (function (BABYLON) {
  66054. var PassPostProcess = /** @class */ (function (_super) {
  66055. __extends(PassPostProcess, _super);
  66056. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  66057. if (camera === void 0) { camera = null; }
  66058. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66059. if (blockCompilation === void 0) { blockCompilation = false; }
  66060. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  66061. }
  66062. return PassPostProcess;
  66063. }(BABYLON.PostProcess));
  66064. BABYLON.PassPostProcess = PassPostProcess;
  66065. })(BABYLON || (BABYLON = {}));
  66066. //# sourceMappingURL=babylon.passPostProcess.js.map
  66067. var __assign = (this && this.__assign) || Object.assign || function(t) {
  66068. for (var s, i = 1, n = arguments.length; i < n; i++) {
  66069. s = arguments[i];
  66070. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  66071. t[p] = s[p];
  66072. }
  66073. return t;
  66074. };
  66075. var BABYLON;
  66076. (function (BABYLON) {
  66077. /**
  66078. * Default implementation IShadowGenerator.
  66079. * This is the main object responsible of generating shadows in the framework.
  66080. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66081. */
  66082. var ShadowGenerator = /** @class */ (function () {
  66083. /**
  66084. * Creates a ShadowGenerator object.
  66085. * A ShadowGenerator is the required tool to use the shadows.
  66086. * Each light casting shadows needs to use its own ShadowGenerator.
  66087. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  66088. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  66089. * @param light The light object generating the shadows.
  66090. * @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.
  66091. */
  66092. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  66093. this._bias = 0.00005;
  66094. this._normalBias = 0;
  66095. this._blurBoxOffset = 1;
  66096. this._blurScale = 2;
  66097. this._blurKernel = 1;
  66098. this._useKernelBlur = false;
  66099. this._filter = ShadowGenerator.FILTER_NONE;
  66100. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66101. this._contactHardeningLightSizeUVRatio = 0.1;
  66102. this._darkness = 0;
  66103. this._transparencyShadow = false;
  66104. /**
  66105. * Controls the extent to which the shadows fade out at the edge of the frustum
  66106. * Used only by directionals and spots
  66107. */
  66108. this.frustumEdgeFalloff = 0;
  66109. /**
  66110. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66111. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66112. * It might on the other hand introduce peter panning.
  66113. */
  66114. this.forceBackFacesOnly = false;
  66115. this._lightDirection = BABYLON.Vector3.Zero();
  66116. this._viewMatrix = BABYLON.Matrix.Zero();
  66117. this._projectionMatrix = BABYLON.Matrix.Zero();
  66118. this._transformMatrix = BABYLON.Matrix.Zero();
  66119. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66120. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66121. this._currentFaceIndex = 0;
  66122. this._currentFaceIndexCache = 0;
  66123. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66124. this._mapSize = mapSize;
  66125. this._light = light;
  66126. this._scene = light.getScene();
  66127. light._shadowGenerator = this;
  66128. // Texture type fallback from float to int if not supported.
  66129. var caps = this._scene.getEngine().getCaps();
  66130. if (!useFullFloatFirst) {
  66131. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66132. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66133. }
  66134. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66135. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66136. }
  66137. else {
  66138. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66139. }
  66140. }
  66141. else {
  66142. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66143. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66144. }
  66145. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66146. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66147. }
  66148. else {
  66149. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66150. }
  66151. }
  66152. this._initializeGenerator();
  66153. this._applyFilterValues();
  66154. }
  66155. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66156. /**
  66157. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66158. */
  66159. get: function () {
  66160. return this._bias;
  66161. },
  66162. /**
  66163. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66164. */
  66165. set: function (bias) {
  66166. this._bias = bias;
  66167. },
  66168. enumerable: true,
  66169. configurable: true
  66170. });
  66171. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66172. /**
  66173. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66174. */
  66175. get: function () {
  66176. return this._normalBias;
  66177. },
  66178. /**
  66179. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66180. */
  66181. set: function (normalBias) {
  66182. this._normalBias = normalBias;
  66183. },
  66184. enumerable: true,
  66185. configurable: true
  66186. });
  66187. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66188. /**
  66189. * Gets the blur box offset: offset applied during the blur pass.
  66190. * Only usefull if useKernelBlur = false
  66191. */
  66192. get: function () {
  66193. return this._blurBoxOffset;
  66194. },
  66195. /**
  66196. * Sets the blur box offset: offset applied during the blur pass.
  66197. * Only usefull if useKernelBlur = false
  66198. */
  66199. set: function (value) {
  66200. if (this._blurBoxOffset === value) {
  66201. return;
  66202. }
  66203. this._blurBoxOffset = value;
  66204. this._disposeBlurPostProcesses();
  66205. },
  66206. enumerable: true,
  66207. configurable: true
  66208. });
  66209. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66210. /**
  66211. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66212. * 2 means half of the size.
  66213. */
  66214. get: function () {
  66215. return this._blurScale;
  66216. },
  66217. /**
  66218. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66219. * 2 means half of the size.
  66220. */
  66221. set: function (value) {
  66222. if (this._blurScale === value) {
  66223. return;
  66224. }
  66225. this._blurScale = value;
  66226. this._disposeBlurPostProcesses();
  66227. },
  66228. enumerable: true,
  66229. configurable: true
  66230. });
  66231. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66232. /**
  66233. * Gets the blur kernel: kernel size of the blur pass.
  66234. * Only usefull if useKernelBlur = true
  66235. */
  66236. get: function () {
  66237. return this._blurKernel;
  66238. },
  66239. /**
  66240. * Sets the blur kernel: kernel size of the blur pass.
  66241. * Only usefull if useKernelBlur = true
  66242. */
  66243. set: function (value) {
  66244. if (this._blurKernel === value) {
  66245. return;
  66246. }
  66247. this._blurKernel = value;
  66248. this._disposeBlurPostProcesses();
  66249. },
  66250. enumerable: true,
  66251. configurable: true
  66252. });
  66253. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66254. /**
  66255. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66256. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66257. */
  66258. get: function () {
  66259. return this._useKernelBlur;
  66260. },
  66261. /**
  66262. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66263. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66264. */
  66265. set: function (value) {
  66266. if (this._useKernelBlur === value) {
  66267. return;
  66268. }
  66269. this._useKernelBlur = value;
  66270. this._disposeBlurPostProcesses();
  66271. },
  66272. enumerable: true,
  66273. configurable: true
  66274. });
  66275. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66276. /**
  66277. * Gets the depth scale used in ESM mode.
  66278. */
  66279. get: function () {
  66280. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66281. },
  66282. /**
  66283. * Sets the depth scale used in ESM mode.
  66284. * This can override the scale stored on the light.
  66285. */
  66286. set: function (value) {
  66287. this._depthScale = value;
  66288. },
  66289. enumerable: true,
  66290. configurable: true
  66291. });
  66292. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66293. /**
  66294. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66295. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66296. */
  66297. get: function () {
  66298. return this._filter;
  66299. },
  66300. /**
  66301. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66302. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66303. */
  66304. set: function (value) {
  66305. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66306. if (this._light.needCube()) {
  66307. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66308. this.useExponentialShadowMap = true;
  66309. return;
  66310. }
  66311. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66312. this.useCloseExponentialShadowMap = true;
  66313. return;
  66314. }
  66315. // PCF on cubemap would also be expensive
  66316. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66317. this.usePoissonSampling = true;
  66318. return;
  66319. }
  66320. }
  66321. // Weblg1 fallback for PCF.
  66322. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66323. if (this._scene.getEngine().webGLVersion === 1) {
  66324. this.usePoissonSampling = true;
  66325. return;
  66326. }
  66327. }
  66328. if (this._filter === value) {
  66329. return;
  66330. }
  66331. this._filter = value;
  66332. this._disposeBlurPostProcesses();
  66333. this._applyFilterValues();
  66334. this._light._markMeshesAsLightDirty();
  66335. },
  66336. enumerable: true,
  66337. configurable: true
  66338. });
  66339. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66340. /**
  66341. * Gets if the current filter is set to Poisson Sampling.
  66342. */
  66343. get: function () {
  66344. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66345. },
  66346. /**
  66347. * Sets the current filter to Poisson Sampling.
  66348. */
  66349. set: function (value) {
  66350. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66351. return;
  66352. }
  66353. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66354. },
  66355. enumerable: true,
  66356. configurable: true
  66357. });
  66358. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66359. /**
  66360. * Gets if the current filter is set to VSM.
  66361. * DEPRECATED. Should use useExponentialShadowMap instead.
  66362. */
  66363. get: function () {
  66364. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66365. return this.useExponentialShadowMap;
  66366. },
  66367. /**
  66368. * Sets the current filter is to VSM.
  66369. * DEPRECATED. Should use useExponentialShadowMap instead.
  66370. */
  66371. set: function (value) {
  66372. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66373. this.useExponentialShadowMap = value;
  66374. },
  66375. enumerable: true,
  66376. configurable: true
  66377. });
  66378. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66379. /**
  66380. * Gets if the current filter is set to blurred VSM.
  66381. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66382. */
  66383. get: function () {
  66384. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66385. return this.useBlurExponentialShadowMap;
  66386. },
  66387. /**
  66388. * Sets the current filter is to blurred VSM.
  66389. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66390. */
  66391. set: function (value) {
  66392. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66393. this.useBlurExponentialShadowMap = value;
  66394. },
  66395. enumerable: true,
  66396. configurable: true
  66397. });
  66398. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66399. /**
  66400. * Gets if the current filter is set to ESM.
  66401. */
  66402. get: function () {
  66403. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66404. },
  66405. /**
  66406. * Sets the current filter is to ESM.
  66407. */
  66408. set: function (value) {
  66409. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66410. return;
  66411. }
  66412. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66413. },
  66414. enumerable: true,
  66415. configurable: true
  66416. });
  66417. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66418. /**
  66419. * Gets if the current filter is set to filtered ESM.
  66420. */
  66421. get: function () {
  66422. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66423. },
  66424. /**
  66425. * Gets if the current filter is set to filtered ESM.
  66426. */
  66427. set: function (value) {
  66428. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66429. return;
  66430. }
  66431. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66432. },
  66433. enumerable: true,
  66434. configurable: true
  66435. });
  66436. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66437. /**
  66438. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66439. * exponential to prevent steep falloff artifacts).
  66440. */
  66441. get: function () {
  66442. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66443. },
  66444. /**
  66445. * Sets the current filter to "close ESM" (using the inverse of the
  66446. * exponential to prevent steep falloff artifacts).
  66447. */
  66448. set: function (value) {
  66449. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66450. return;
  66451. }
  66452. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66453. },
  66454. enumerable: true,
  66455. configurable: true
  66456. });
  66457. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66458. /**
  66459. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66460. * exponential to prevent steep falloff artifacts).
  66461. */
  66462. get: function () {
  66463. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66464. },
  66465. /**
  66466. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66467. * exponential to prevent steep falloff artifacts).
  66468. */
  66469. set: function (value) {
  66470. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66471. return;
  66472. }
  66473. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66474. },
  66475. enumerable: true,
  66476. configurable: true
  66477. });
  66478. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66479. /**
  66480. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66481. */
  66482. get: function () {
  66483. return this.filter === ShadowGenerator.FILTER_PCF;
  66484. },
  66485. /**
  66486. * Sets the current filter to "PCF" (percentage closer filtering).
  66487. */
  66488. set: function (value) {
  66489. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66490. return;
  66491. }
  66492. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66493. },
  66494. enumerable: true,
  66495. configurable: true
  66496. });
  66497. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66498. /**
  66499. * Gets the PCF or PCSS Quality.
  66500. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66501. */
  66502. get: function () {
  66503. return this._filteringQuality;
  66504. },
  66505. /**
  66506. * Sets the PCF or PCSS Quality.
  66507. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66508. */
  66509. set: function (filteringQuality) {
  66510. this._filteringQuality = filteringQuality;
  66511. },
  66512. enumerable: true,
  66513. configurable: true
  66514. });
  66515. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66516. /**
  66517. * Gets if the current filter is set to "PCSS" (contact hardening).
  66518. */
  66519. get: function () {
  66520. return this.filter === ShadowGenerator.FILTER_PCSS;
  66521. },
  66522. /**
  66523. * Sets the current filter to "PCSS" (contact hardening).
  66524. */
  66525. set: function (value) {
  66526. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66527. return;
  66528. }
  66529. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66530. },
  66531. enumerable: true,
  66532. configurable: true
  66533. });
  66534. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66535. /**
  66536. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66537. * Using a ratio helps keeping shape stability independently of the map size.
  66538. *
  66539. * It does not account for the light projection as it was having too much
  66540. * instability during the light setup or during light position changes.
  66541. *
  66542. * Only valid if useContactHardeningShadow is true.
  66543. */
  66544. get: function () {
  66545. return this._contactHardeningLightSizeUVRatio;
  66546. },
  66547. /**
  66548. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66549. * Using a ratio helps keeping shape stability independently of the map size.
  66550. *
  66551. * It does not account for the light projection as it was having too much
  66552. * instability during the light setup or during light position changes.
  66553. *
  66554. * Only valid if useContactHardeningShadow is true.
  66555. */
  66556. set: function (contactHardeningLightSizeUVRatio) {
  66557. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66558. },
  66559. enumerable: true,
  66560. configurable: true
  66561. });
  66562. /**
  66563. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66564. * 0 means strongest and 1 would means no shadow.
  66565. * @returns the darkness.
  66566. */
  66567. ShadowGenerator.prototype.getDarkness = function () {
  66568. return this._darkness;
  66569. };
  66570. /**
  66571. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66572. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66573. * @returns the shadow generator allowing fluent coding.
  66574. */
  66575. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66576. if (darkness >= 1.0)
  66577. this._darkness = 1.0;
  66578. else if (darkness <= 0.0)
  66579. this._darkness = 0.0;
  66580. else
  66581. this._darkness = darkness;
  66582. return this;
  66583. };
  66584. /**
  66585. * Sets the ability to have transparent shadow (boolean).
  66586. * @param transparent True if transparent else False
  66587. * @returns the shadow generator allowing fluent coding
  66588. */
  66589. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66590. this._transparencyShadow = transparent;
  66591. return this;
  66592. };
  66593. /**
  66594. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66595. * @returns The render target texture if present otherwise, null
  66596. */
  66597. ShadowGenerator.prototype.getShadowMap = function () {
  66598. return this._shadowMap;
  66599. };
  66600. /**
  66601. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66602. * @returns The render target texture if the shadow map is present otherwise, null
  66603. */
  66604. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66605. if (this._shadowMap2) {
  66606. return this._shadowMap2;
  66607. }
  66608. return this._shadowMap;
  66609. };
  66610. /**
  66611. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66612. * @param mesh Mesh to add
  66613. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66614. * @returns the Shadow Generator itself
  66615. */
  66616. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66617. if (includeDescendants === void 0) { includeDescendants = true; }
  66618. if (!this._shadowMap) {
  66619. return this;
  66620. }
  66621. if (!this._shadowMap.renderList) {
  66622. this._shadowMap.renderList = [];
  66623. }
  66624. this._shadowMap.renderList.push(mesh);
  66625. if (includeDescendants) {
  66626. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66627. }
  66628. return this;
  66629. var _a;
  66630. };
  66631. /**
  66632. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66633. * @param mesh Mesh to remove
  66634. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66635. * @returns the Shadow Generator itself
  66636. */
  66637. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66638. if (includeDescendants === void 0) { includeDescendants = true; }
  66639. if (!this._shadowMap || !this._shadowMap.renderList) {
  66640. return this;
  66641. }
  66642. var index = this._shadowMap.renderList.indexOf(mesh);
  66643. if (index !== -1) {
  66644. this._shadowMap.renderList.splice(index, 1);
  66645. }
  66646. if (includeDescendants) {
  66647. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66648. var child = _a[_i];
  66649. this.removeShadowCaster(child);
  66650. }
  66651. }
  66652. return this;
  66653. };
  66654. /**
  66655. * Returns the associated light object.
  66656. * @returns the light generating the shadow
  66657. */
  66658. ShadowGenerator.prototype.getLight = function () {
  66659. return this._light;
  66660. };
  66661. ShadowGenerator.prototype._initializeGenerator = function () {
  66662. this._light._markMeshesAsLightDirty();
  66663. this._initializeShadowMap();
  66664. };
  66665. ShadowGenerator.prototype._initializeShadowMap = function () {
  66666. var _this = this;
  66667. // Render target
  66668. var engine = this._scene.getEngine();
  66669. if (engine.webGLVersion > 1) {
  66670. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66671. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66672. }
  66673. else {
  66674. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66675. }
  66676. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66677. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66678. this._shadowMap.anisotropicFilteringLevel = 1;
  66679. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66680. this._shadowMap.renderParticles = false;
  66681. this._shadowMap.ignoreCameraViewport = true;
  66682. // Record Face Index before render.
  66683. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66684. _this._currentFaceIndex = faceIndex;
  66685. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66686. engine.setColorWrite(false);
  66687. }
  66688. });
  66689. // Custom render function.
  66690. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66691. // Blur if required afer render.
  66692. this._shadowMap.onAfterUnbindObservable.add(function () {
  66693. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66694. engine.setColorWrite(true);
  66695. }
  66696. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66697. return;
  66698. }
  66699. var shadowMap = _this.getShadowMapForRendering();
  66700. if (shadowMap) {
  66701. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66702. }
  66703. });
  66704. // Clear according to the chosen filter.
  66705. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66706. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66707. this._shadowMap.onClearObservable.add(function (engine) {
  66708. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66709. engine.clear(clearOne, false, true, false);
  66710. }
  66711. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66712. engine.clear(clearZero, true, true, false);
  66713. }
  66714. else {
  66715. engine.clear(clearOne, true, true, false);
  66716. }
  66717. });
  66718. };
  66719. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66720. var _this = this;
  66721. var engine = this._scene.getEngine();
  66722. var targetSize = this._mapSize / this.blurScale;
  66723. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66724. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66725. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66726. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66727. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66728. }
  66729. if (this.useKernelBlur) {
  66730. 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);
  66731. this._kernelBlurXPostprocess.width = targetSize;
  66732. this._kernelBlurXPostprocess.height = targetSize;
  66733. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66734. effect.setTexture("textureSampler", _this._shadowMap);
  66735. });
  66736. 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);
  66737. this._kernelBlurXPostprocess.autoClear = false;
  66738. this._kernelBlurYPostprocess.autoClear = false;
  66739. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66740. this._kernelBlurXPostprocess.packedFloat = true;
  66741. this._kernelBlurYPostprocess.packedFloat = true;
  66742. }
  66743. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66744. }
  66745. else {
  66746. 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);
  66747. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66748. effect.setFloat2("screenSize", targetSize, targetSize);
  66749. effect.setTexture("textureSampler", _this._shadowMap);
  66750. });
  66751. this._boxBlurPostprocess.autoClear = false;
  66752. this._blurPostProcesses = [this._boxBlurPostprocess];
  66753. }
  66754. };
  66755. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66756. var index;
  66757. var engine = this._scene.getEngine();
  66758. if (depthOnlySubMeshes.length) {
  66759. engine.setColorWrite(false);
  66760. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66761. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66762. }
  66763. engine.setColorWrite(true);
  66764. }
  66765. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66766. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66767. }
  66768. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66769. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66770. }
  66771. if (this._transparencyShadow) {
  66772. for (index = 0; index < transparentSubMeshes.length; index++) {
  66773. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66774. }
  66775. }
  66776. };
  66777. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66778. var _this = this;
  66779. var mesh = subMesh.getRenderingMesh();
  66780. var scene = this._scene;
  66781. var engine = scene.getEngine();
  66782. var material = subMesh.getMaterial();
  66783. if (!material) {
  66784. return;
  66785. }
  66786. // Culling
  66787. engine.setState(material.backFaceCulling);
  66788. // Managing instances
  66789. var batch = mesh._getInstancesRenderList(subMesh._id);
  66790. if (batch.mustReturn) {
  66791. return;
  66792. }
  66793. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66794. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66795. engine.enableEffect(this._effect);
  66796. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66797. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66798. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66799. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66800. this._effect.setVector3("lightData", this._cachedDirection);
  66801. }
  66802. else {
  66803. this._effect.setVector3("lightData", this._cachedPosition);
  66804. }
  66805. if (scene.activeCamera) {
  66806. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66807. }
  66808. // Alpha test
  66809. if (material && material.needAlphaTesting()) {
  66810. var alphaTexture = material.getAlphaTestTexture();
  66811. if (alphaTexture) {
  66812. this._effect.setTexture("diffuseSampler", alphaTexture);
  66813. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66814. }
  66815. }
  66816. // Bones
  66817. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66818. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66819. }
  66820. // Morph targets
  66821. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66822. if (this.forceBackFacesOnly) {
  66823. engine.setState(true, 0, false, true);
  66824. }
  66825. // Draw
  66826. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66827. if (this.forceBackFacesOnly) {
  66828. engine.setState(true, 0, false, false);
  66829. }
  66830. }
  66831. else {
  66832. // Need to reset refresh rate of the shadowMap
  66833. if (this._shadowMap) {
  66834. this._shadowMap.resetRefreshCounter();
  66835. }
  66836. }
  66837. };
  66838. ShadowGenerator.prototype._applyFilterValues = function () {
  66839. if (!this._shadowMap) {
  66840. return;
  66841. }
  66842. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66843. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66844. }
  66845. else {
  66846. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66847. }
  66848. };
  66849. /**
  66850. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66851. * @param onCompiled Callback triggered at the and of the effects compilation
  66852. * @param options Sets of optional options forcing the compilation with different modes
  66853. */
  66854. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66855. var _this = this;
  66856. var localOptions = __assign({ useInstances: false }, options);
  66857. var shadowMap = this.getShadowMap();
  66858. if (!shadowMap) {
  66859. if (onCompiled) {
  66860. onCompiled(this);
  66861. }
  66862. return;
  66863. }
  66864. var renderList = shadowMap.renderList;
  66865. if (!renderList) {
  66866. if (onCompiled) {
  66867. onCompiled(this);
  66868. }
  66869. return;
  66870. }
  66871. var subMeshes = new Array();
  66872. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66873. var mesh = renderList_1[_i];
  66874. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66875. }
  66876. if (subMeshes.length === 0) {
  66877. if (onCompiled) {
  66878. onCompiled(this);
  66879. }
  66880. return;
  66881. }
  66882. var currentIndex = 0;
  66883. var checkReady = function () {
  66884. if (!_this._scene || !_this._scene.getEngine()) {
  66885. return;
  66886. }
  66887. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66888. currentIndex++;
  66889. if (currentIndex >= subMeshes.length) {
  66890. if (onCompiled) {
  66891. onCompiled(_this);
  66892. }
  66893. return;
  66894. }
  66895. }
  66896. setTimeout(checkReady, 16);
  66897. };
  66898. checkReady();
  66899. };
  66900. /**
  66901. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66902. * @param options Sets of optional options forcing the compilation with different modes
  66903. * @returns A promise that resolves when the compilation completes
  66904. */
  66905. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66906. var _this = this;
  66907. return new Promise(function (resolve) {
  66908. _this.forceCompilation(function () {
  66909. resolve();
  66910. }, options);
  66911. });
  66912. };
  66913. /**
  66914. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66915. * @param subMesh The submesh we want to render in the shadow map
  66916. * @param useInstances Defines wether will draw in the map using instances
  66917. * @returns true if ready otherwise, false
  66918. */
  66919. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66920. var defines = [];
  66921. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66922. defines.push("#define FLOAT");
  66923. }
  66924. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66925. defines.push("#define ESM");
  66926. }
  66927. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66928. defines.push("#define DEPTHTEXTURE");
  66929. }
  66930. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66931. var mesh = subMesh.getMesh();
  66932. var material = subMesh.getMaterial();
  66933. // Normal bias.
  66934. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66935. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66936. defines.push("#define NORMAL");
  66937. if (mesh.nonUniformScaling) {
  66938. defines.push("#define NONUNIFORMSCALING");
  66939. }
  66940. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66941. defines.push("#define DIRECTIONINLIGHTDATA");
  66942. }
  66943. }
  66944. // Alpha test
  66945. if (material && material.needAlphaTesting()) {
  66946. var alphaTexture = material.getAlphaTestTexture();
  66947. if (alphaTexture) {
  66948. defines.push("#define ALPHATEST");
  66949. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66950. attribs.push(BABYLON.VertexBuffer.UVKind);
  66951. defines.push("#define UV1");
  66952. }
  66953. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66954. if (alphaTexture.coordinatesIndex === 1) {
  66955. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66956. defines.push("#define UV2");
  66957. }
  66958. }
  66959. }
  66960. }
  66961. // Bones
  66962. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66963. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66964. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66965. if (mesh.numBoneInfluencers > 4) {
  66966. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66967. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66968. }
  66969. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66970. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66971. }
  66972. else {
  66973. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66974. }
  66975. // Morph targets
  66976. var manager = mesh.morphTargetManager;
  66977. var morphInfluencers = 0;
  66978. if (manager) {
  66979. if (manager.numInfluencers > 0) {
  66980. defines.push("#define MORPHTARGETS");
  66981. morphInfluencers = manager.numInfluencers;
  66982. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66983. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66984. }
  66985. }
  66986. // Instances
  66987. if (useInstances) {
  66988. defines.push("#define INSTANCES");
  66989. attribs.push("world0");
  66990. attribs.push("world1");
  66991. attribs.push("world2");
  66992. attribs.push("world3");
  66993. }
  66994. // Get correct effect
  66995. var join = defines.join("\n");
  66996. if (this._cachedDefines !== join) {
  66997. this._cachedDefines = join;
  66998. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66999. }
  67000. if (!this._effect.isReady()) {
  67001. return false;
  67002. }
  67003. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67004. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  67005. this._initializeBlurRTTAndPostProcesses();
  67006. }
  67007. }
  67008. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  67009. return false;
  67010. }
  67011. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  67012. return false;
  67013. }
  67014. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  67015. return false;
  67016. }
  67017. return true;
  67018. };
  67019. /**
  67020. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  67021. * @param defines Defines of the material we want to update
  67022. * @param lightIndex Index of the light in the enabled light list of the material
  67023. */
  67024. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  67025. var scene = this._scene;
  67026. var light = this._light;
  67027. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67028. return;
  67029. }
  67030. defines["SHADOW" + lightIndex] = true;
  67031. if (this.useContactHardeningShadow) {
  67032. defines["SHADOWPCSS" + lightIndex] = true;
  67033. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67034. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67035. }
  67036. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67037. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67038. }
  67039. // else default to high.
  67040. }
  67041. if (this.usePercentageCloserFiltering) {
  67042. defines["SHADOWPCF" + lightIndex] = true;
  67043. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67044. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67045. }
  67046. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67047. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67048. }
  67049. // else default to high.
  67050. }
  67051. else if (this.usePoissonSampling) {
  67052. defines["SHADOWPOISSON" + lightIndex] = true;
  67053. }
  67054. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67055. defines["SHADOWESM" + lightIndex] = true;
  67056. }
  67057. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67058. defines["SHADOWCLOSEESM" + lightIndex] = true;
  67059. }
  67060. if (light.needCube()) {
  67061. defines["SHADOWCUBE" + lightIndex] = true;
  67062. }
  67063. };
  67064. /**
  67065. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  67066. * defined in the generator but impacting the effect).
  67067. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  67068. * @param effect The effect we are binfing the information for
  67069. */
  67070. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  67071. var light = this._light;
  67072. var scene = this._scene;
  67073. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67074. return;
  67075. }
  67076. var camera = scene.activeCamera;
  67077. if (!camera) {
  67078. return;
  67079. }
  67080. var shadowMap = this.getShadowMap();
  67081. if (!shadowMap) {
  67082. return;
  67083. }
  67084. if (!light.needCube()) {
  67085. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  67086. }
  67087. // Only PCF uses depth stencil texture.
  67088. if (this._filter === ShadowGenerator.FILTER_PCF) {
  67089. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67090. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67091. }
  67092. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  67093. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67094. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  67095. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67096. }
  67097. else {
  67098. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67099. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67100. }
  67101. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67102. };
  67103. /**
  67104. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67105. * (eq to shadow prjection matrix * light transform matrix)
  67106. * @returns The transform matrix used to create the shadow map
  67107. */
  67108. ShadowGenerator.prototype.getTransformMatrix = function () {
  67109. var scene = this._scene;
  67110. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67111. return this._transformMatrix;
  67112. }
  67113. this._currentRenderID = scene.getRenderId();
  67114. this._currentFaceIndexCache = this._currentFaceIndex;
  67115. var lightPosition = this._light.position;
  67116. if (this._light.computeTransformedInformation()) {
  67117. lightPosition = this._light.transformedPosition;
  67118. }
  67119. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67120. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67121. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67122. }
  67123. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67124. this._cachedPosition.copyFrom(lightPosition);
  67125. this._cachedDirection.copyFrom(this._lightDirection);
  67126. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67127. var shadowMap = this.getShadowMap();
  67128. if (shadowMap) {
  67129. var renderList = shadowMap.renderList;
  67130. if (renderList) {
  67131. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67132. }
  67133. }
  67134. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67135. }
  67136. return this._transformMatrix;
  67137. };
  67138. /**
  67139. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67140. * Cube and 2D textures for instance.
  67141. */
  67142. ShadowGenerator.prototype.recreateShadowMap = function () {
  67143. var shadowMap = this._shadowMap;
  67144. if (!shadowMap) {
  67145. return;
  67146. }
  67147. // Track render list.
  67148. var renderList = shadowMap.renderList;
  67149. // Clean up existing data.
  67150. this._disposeRTTandPostProcesses();
  67151. // Reinitializes.
  67152. this._initializeGenerator();
  67153. // Reaffect the filter to ensure a correct fallback if necessary.
  67154. this.filter = this.filter;
  67155. // Reaffect the filter.
  67156. this._applyFilterValues();
  67157. // Reaffect Render List.
  67158. this._shadowMap.renderList = renderList;
  67159. };
  67160. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67161. if (this._shadowMap2) {
  67162. this._shadowMap2.dispose();
  67163. this._shadowMap2 = null;
  67164. }
  67165. if (this._boxBlurPostprocess) {
  67166. this._boxBlurPostprocess.dispose();
  67167. this._boxBlurPostprocess = null;
  67168. }
  67169. if (this._kernelBlurXPostprocess) {
  67170. this._kernelBlurXPostprocess.dispose();
  67171. this._kernelBlurXPostprocess = null;
  67172. }
  67173. if (this._kernelBlurYPostprocess) {
  67174. this._kernelBlurYPostprocess.dispose();
  67175. this._kernelBlurYPostprocess = null;
  67176. }
  67177. this._blurPostProcesses = [];
  67178. };
  67179. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67180. if (this._shadowMap) {
  67181. this._shadowMap.dispose();
  67182. this._shadowMap = null;
  67183. }
  67184. this._disposeBlurPostProcesses();
  67185. };
  67186. /**
  67187. * Disposes the ShadowGenerator.
  67188. * Returns nothing.
  67189. */
  67190. ShadowGenerator.prototype.dispose = function () {
  67191. this._disposeRTTandPostProcesses();
  67192. if (this._light) {
  67193. this._light._shadowGenerator = null;
  67194. this._light._markMeshesAsLightDirty();
  67195. }
  67196. };
  67197. /**
  67198. * Serializes the shadow generator setup to a json object.
  67199. * @returns The serialized JSON object
  67200. */
  67201. ShadowGenerator.prototype.serialize = function () {
  67202. var serializationObject = {};
  67203. var shadowMap = this.getShadowMap();
  67204. if (!shadowMap) {
  67205. return serializationObject;
  67206. }
  67207. serializationObject.lightId = this._light.id;
  67208. serializationObject.mapSize = shadowMap.getRenderSize();
  67209. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67210. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67211. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67212. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67213. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67214. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67215. serializationObject.depthScale = this.depthScale;
  67216. serializationObject.darkness = this.getDarkness();
  67217. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67218. serializationObject.blurKernel = this.blurKernel;
  67219. serializationObject.blurScale = this.blurScale;
  67220. serializationObject.useKernelBlur = this.useKernelBlur;
  67221. serializationObject.transparencyShadow = this._transparencyShadow;
  67222. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67223. serializationObject.bias = this.bias;
  67224. serializationObject.normalBias = this.normalBias;
  67225. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67226. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67227. serializationObject.filteringQuality = this.filteringQuality;
  67228. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67229. serializationObject.renderList = [];
  67230. if (shadowMap.renderList) {
  67231. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67232. var mesh = shadowMap.renderList[meshIndex];
  67233. serializationObject.renderList.push(mesh.id);
  67234. }
  67235. }
  67236. return serializationObject;
  67237. };
  67238. /**
  67239. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67240. * @param parsedShadowGenerator The JSON object to parse
  67241. * @param scene The scene to create the shadow map for
  67242. * @returns The parsed shadow generator
  67243. */
  67244. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67245. //casting to point light, as light is missing the position attr and typescript complains.
  67246. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67247. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67248. var shadowMap = shadowGenerator.getShadowMap();
  67249. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67250. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67251. meshes.forEach(function (mesh) {
  67252. if (!shadowMap) {
  67253. return;
  67254. }
  67255. if (!shadowMap.renderList) {
  67256. shadowMap.renderList = [];
  67257. }
  67258. shadowMap.renderList.push(mesh);
  67259. });
  67260. }
  67261. if (parsedShadowGenerator.usePoissonSampling) {
  67262. shadowGenerator.usePoissonSampling = true;
  67263. }
  67264. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67265. shadowGenerator.useExponentialShadowMap = true;
  67266. }
  67267. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67268. shadowGenerator.useBlurExponentialShadowMap = true;
  67269. }
  67270. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67271. shadowGenerator.useCloseExponentialShadowMap = true;
  67272. }
  67273. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67274. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67275. }
  67276. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67277. shadowGenerator.usePercentageCloserFiltering = true;
  67278. }
  67279. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67280. shadowGenerator.useContactHardeningShadow = true;
  67281. }
  67282. if (parsedShadowGenerator.filteringQuality) {
  67283. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67284. }
  67285. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67286. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67287. }
  67288. // Backward compat
  67289. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67290. shadowGenerator.useExponentialShadowMap = true;
  67291. }
  67292. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67293. shadowGenerator.useBlurExponentialShadowMap = true;
  67294. }
  67295. if (parsedShadowGenerator.depthScale) {
  67296. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67297. }
  67298. if (parsedShadowGenerator.blurScale) {
  67299. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67300. }
  67301. if (parsedShadowGenerator.blurBoxOffset) {
  67302. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67303. }
  67304. if (parsedShadowGenerator.useKernelBlur) {
  67305. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67306. }
  67307. if (parsedShadowGenerator.blurKernel) {
  67308. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67309. }
  67310. if (parsedShadowGenerator.bias !== undefined) {
  67311. shadowGenerator.bias = parsedShadowGenerator.bias;
  67312. }
  67313. if (parsedShadowGenerator.normalBias !== undefined) {
  67314. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67315. }
  67316. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67317. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67318. }
  67319. if (parsedShadowGenerator.darkness) {
  67320. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67321. }
  67322. if (parsedShadowGenerator.transparencyShadow) {
  67323. shadowGenerator.setTransparencyShadow(true);
  67324. }
  67325. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67326. return shadowGenerator;
  67327. };
  67328. /**
  67329. * Shadow generator mode None: no filtering applied.
  67330. */
  67331. ShadowGenerator.FILTER_NONE = 0;
  67332. /**
  67333. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67334. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67335. */
  67336. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67337. /**
  67338. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67339. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67340. */
  67341. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67342. /**
  67343. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67344. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67345. */
  67346. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67347. /**
  67348. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67349. * edge artifacts on steep falloff.
  67350. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67351. */
  67352. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67353. /**
  67354. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67355. * edge artifacts on steep falloff.
  67356. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67357. */
  67358. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67359. /**
  67360. * Shadow generator mode PCF: Percentage Closer Filtering
  67361. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67362. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67363. */
  67364. ShadowGenerator.FILTER_PCF = 6;
  67365. /**
  67366. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67367. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67368. * Contact Hardening
  67369. */
  67370. ShadowGenerator.FILTER_PCSS = 7;
  67371. /**
  67372. * Reserved for PCF and PCSS
  67373. * Highest Quality.
  67374. *
  67375. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67376. *
  67377. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67378. */
  67379. ShadowGenerator.QUALITY_HIGH = 0;
  67380. /**
  67381. * Reserved for PCF and PCSS
  67382. * Good tradeoff for quality/perf cross devices
  67383. *
  67384. * Execute PCF on a 3*3 kernel.
  67385. *
  67386. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67387. */
  67388. ShadowGenerator.QUALITY_MEDIUM = 1;
  67389. /**
  67390. * Reserved for PCF and PCSS
  67391. * The lowest quality but the fastest.
  67392. *
  67393. * Execute PCF on a 1*1 kernel.
  67394. *
  67395. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67396. */
  67397. ShadowGenerator.QUALITY_LOW = 2;
  67398. return ShadowGenerator;
  67399. }());
  67400. BABYLON.ShadowGenerator = ShadowGenerator;
  67401. })(BABYLON || (BABYLON = {}));
  67402. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67403. var BABYLON;
  67404. (function (BABYLON) {
  67405. var DefaultLoadingScreen = /** @class */ (function () {
  67406. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67407. if (_loadingText === void 0) { _loadingText = ""; }
  67408. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67409. var _this = this;
  67410. this._renderingCanvas = _renderingCanvas;
  67411. this._loadingText = _loadingText;
  67412. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67413. // Resize
  67414. this._resizeLoadingUI = function () {
  67415. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67416. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67417. if (!_this._loadingDiv) {
  67418. return;
  67419. }
  67420. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67421. _this._loadingDiv.style.left = canvasRect.left + "px";
  67422. _this._loadingDiv.style.top = canvasRect.top + "px";
  67423. _this._loadingDiv.style.width = canvasRect.width + "px";
  67424. _this._loadingDiv.style.height = canvasRect.height + "px";
  67425. };
  67426. }
  67427. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67428. if (this._loadingDiv) {
  67429. // Do not add a loading screen if there is already one
  67430. return;
  67431. }
  67432. this._loadingDiv = document.createElement("div");
  67433. this._loadingDiv.id = "babylonjsLoadingDiv";
  67434. this._loadingDiv.style.opacity = "0";
  67435. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67436. this._loadingDiv.style.pointerEvents = "none";
  67437. // Loading text
  67438. this._loadingTextDiv = document.createElement("div");
  67439. this._loadingTextDiv.style.position = "absolute";
  67440. this._loadingTextDiv.style.left = "0";
  67441. this._loadingTextDiv.style.top = "50%";
  67442. this._loadingTextDiv.style.marginTop = "80px";
  67443. this._loadingTextDiv.style.width = "100%";
  67444. this._loadingTextDiv.style.height = "20px";
  67445. this._loadingTextDiv.style.fontFamily = "Arial";
  67446. this._loadingTextDiv.style.fontSize = "14px";
  67447. this._loadingTextDiv.style.color = "white";
  67448. this._loadingTextDiv.style.textAlign = "center";
  67449. this._loadingTextDiv.innerHTML = "Loading";
  67450. this._loadingDiv.appendChild(this._loadingTextDiv);
  67451. //set the predefined text
  67452. this._loadingTextDiv.innerHTML = this._loadingText;
  67453. // Generating keyframes
  67454. var style = document.createElement('style');
  67455. style.type = 'text/css';
  67456. 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 }";
  67457. style.innerHTML = keyFrames;
  67458. document.getElementsByTagName('head')[0].appendChild(style);
  67459. // Loading img
  67460. var imgBack = new Image();
  67461. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3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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";
  67462. imgBack.style.position = "absolute";
  67463. imgBack.style.left = "50%";
  67464. imgBack.style.top = "50%";
  67465. imgBack.style.marginLeft = "-60px";
  67466. imgBack.style.marginTop = "-60px";
  67467. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67468. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67469. imgBack.style.transformOrigin = "50% 50%";
  67470. imgBack.style.webkitTransformOrigin = "50% 50%";
  67471. this._loadingDiv.appendChild(imgBack);
  67472. this._resizeLoadingUI();
  67473. window.addEventListener("resize", this._resizeLoadingUI);
  67474. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67475. document.body.appendChild(this._loadingDiv);
  67476. this._loadingDiv.style.opacity = "1";
  67477. };
  67478. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67479. var _this = this;
  67480. if (!this._loadingDiv) {
  67481. return;
  67482. }
  67483. var onTransitionEnd = function () {
  67484. if (!_this._loadingDiv) {
  67485. return;
  67486. }
  67487. document.body.removeChild(_this._loadingDiv);
  67488. window.removeEventListener("resize", _this._resizeLoadingUI);
  67489. _this._loadingDiv = null;
  67490. };
  67491. this._loadingDiv.style.opacity = "0";
  67492. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67493. };
  67494. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67495. set: function (text) {
  67496. this._loadingText = text;
  67497. if (this._loadingTextDiv) {
  67498. this._loadingTextDiv.innerHTML = this._loadingText;
  67499. }
  67500. },
  67501. enumerable: true,
  67502. configurable: true
  67503. });
  67504. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67505. get: function () {
  67506. return this._loadingDivBackgroundColor;
  67507. },
  67508. set: function (color) {
  67509. this._loadingDivBackgroundColor = color;
  67510. if (!this._loadingDiv) {
  67511. return;
  67512. }
  67513. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67514. },
  67515. enumerable: true,
  67516. configurable: true
  67517. });
  67518. return DefaultLoadingScreen;
  67519. }());
  67520. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67521. })(BABYLON || (BABYLON = {}));
  67522. //# sourceMappingURL=babylon.loadingScreen.js.map
  67523. var BABYLON;
  67524. (function (BABYLON) {
  67525. var SceneLoaderProgressEvent = /** @class */ (function () {
  67526. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67527. this.lengthComputable = lengthComputable;
  67528. this.loaded = loaded;
  67529. this.total = total;
  67530. }
  67531. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67532. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67533. };
  67534. return SceneLoaderProgressEvent;
  67535. }());
  67536. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67537. var SceneLoader = /** @class */ (function () {
  67538. function SceneLoader() {
  67539. }
  67540. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67541. get: function () {
  67542. return 0;
  67543. },
  67544. enumerable: true,
  67545. configurable: true
  67546. });
  67547. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67548. get: function () {
  67549. return 1;
  67550. },
  67551. enumerable: true,
  67552. configurable: true
  67553. });
  67554. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67555. get: function () {
  67556. return 2;
  67557. },
  67558. enumerable: true,
  67559. configurable: true
  67560. });
  67561. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67562. get: function () {
  67563. return 3;
  67564. },
  67565. enumerable: true,
  67566. configurable: true
  67567. });
  67568. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67569. get: function () {
  67570. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67571. },
  67572. set: function (value) {
  67573. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67574. },
  67575. enumerable: true,
  67576. configurable: true
  67577. });
  67578. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67579. get: function () {
  67580. return SceneLoader._ShowLoadingScreen;
  67581. },
  67582. set: function (value) {
  67583. SceneLoader._ShowLoadingScreen = value;
  67584. },
  67585. enumerable: true,
  67586. configurable: true
  67587. });
  67588. Object.defineProperty(SceneLoader, "loggingLevel", {
  67589. get: function () {
  67590. return SceneLoader._loggingLevel;
  67591. },
  67592. set: function (value) {
  67593. SceneLoader._loggingLevel = value;
  67594. },
  67595. enumerable: true,
  67596. configurable: true
  67597. });
  67598. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67599. get: function () {
  67600. return SceneLoader._CleanBoneMatrixWeights;
  67601. },
  67602. set: function (value) {
  67603. SceneLoader._CleanBoneMatrixWeights = value;
  67604. },
  67605. enumerable: true,
  67606. configurable: true
  67607. });
  67608. SceneLoader._getDefaultPlugin = function () {
  67609. return SceneLoader._registeredPlugins[".babylon"];
  67610. };
  67611. SceneLoader._getPluginForExtension = function (extension) {
  67612. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67613. if (registeredPlugin) {
  67614. return registeredPlugin;
  67615. }
  67616. 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");
  67617. return SceneLoader._getDefaultPlugin();
  67618. };
  67619. SceneLoader._getPluginForDirectLoad = function (data) {
  67620. for (var extension in SceneLoader._registeredPlugins) {
  67621. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67622. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67623. return SceneLoader._registeredPlugins[extension];
  67624. }
  67625. }
  67626. return SceneLoader._getDefaultPlugin();
  67627. };
  67628. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67629. if (sceneFilename.name) {
  67630. sceneFilename = sceneFilename.name;
  67631. }
  67632. var queryStringPosition = sceneFilename.indexOf("?");
  67633. if (queryStringPosition !== -1) {
  67634. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67635. }
  67636. var dotPosition = sceneFilename.lastIndexOf(".");
  67637. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67638. return SceneLoader._getPluginForExtension(extension);
  67639. };
  67640. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67641. SceneLoader._getDirectLoad = function (sceneFilename) {
  67642. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67643. return sceneFilename.substr(5);
  67644. }
  67645. return null;
  67646. };
  67647. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67648. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67649. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67650. var plugin;
  67651. if (registeredPlugin.plugin.createPlugin) {
  67652. plugin = registeredPlugin.plugin.createPlugin();
  67653. }
  67654. else {
  67655. plugin = registeredPlugin.plugin;
  67656. }
  67657. var useArrayBuffer = registeredPlugin.isBinary;
  67658. var database;
  67659. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67660. var dataCallback = function (data, responseURL) {
  67661. if (scene.isDisposed) {
  67662. onError("Scene has been disposed");
  67663. return;
  67664. }
  67665. scene.database = database;
  67666. onSuccess(plugin, data, responseURL);
  67667. };
  67668. var request = null;
  67669. var pluginDisposed = false;
  67670. var onDisposeObservable = plugin.onDisposeObservable;
  67671. if (onDisposeObservable) {
  67672. onDisposeObservable.add(function () {
  67673. pluginDisposed = true;
  67674. if (request) {
  67675. request.abort();
  67676. request = null;
  67677. }
  67678. onDispose();
  67679. });
  67680. }
  67681. var manifestChecked = function () {
  67682. if (pluginDisposed) {
  67683. return;
  67684. }
  67685. var url = rootUrl + sceneFilename;
  67686. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67687. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67688. } : undefined, database, useArrayBuffer, function (request, exception) {
  67689. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67690. });
  67691. };
  67692. if (directLoad) {
  67693. dataCallback(directLoad);
  67694. return plugin;
  67695. }
  67696. if (rootUrl.indexOf("file:") === -1) {
  67697. var engine = scene.getEngine();
  67698. var canUseOfflineSupport = engine.enableOfflineSupport;
  67699. if (canUseOfflineSupport) {
  67700. // Also check for exceptions
  67701. var exceptionFound = false;
  67702. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67703. var regex = _a[_i];
  67704. if (regex.test(rootUrl + sceneFilename)) {
  67705. exceptionFound = true;
  67706. break;
  67707. }
  67708. }
  67709. canUseOfflineSupport = !exceptionFound;
  67710. }
  67711. if (canUseOfflineSupport) {
  67712. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67713. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67714. }
  67715. else {
  67716. manifestChecked();
  67717. }
  67718. }
  67719. // Loading file from disk via input file or drag'n'drop
  67720. else {
  67721. var fileOrString = sceneFilename;
  67722. if (fileOrString.name) { // File
  67723. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67724. }
  67725. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67726. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67727. }
  67728. else {
  67729. onError("Unable to find file named " + sceneFilename);
  67730. }
  67731. }
  67732. return plugin;
  67733. };
  67734. // Public functions
  67735. SceneLoader.GetPluginForExtension = function (extension) {
  67736. return SceneLoader._getPluginForExtension(extension).plugin;
  67737. };
  67738. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67739. return !!SceneLoader._registeredPlugins[extension];
  67740. };
  67741. SceneLoader.RegisterPlugin = function (plugin) {
  67742. if (typeof plugin.extensions === "string") {
  67743. var extension = plugin.extensions;
  67744. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67745. plugin: plugin,
  67746. isBinary: false
  67747. };
  67748. }
  67749. else {
  67750. var extensions = plugin.extensions;
  67751. Object.keys(extensions).forEach(function (extension) {
  67752. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67753. plugin: plugin,
  67754. isBinary: extensions[extension].isBinary
  67755. };
  67756. });
  67757. }
  67758. };
  67759. /**
  67760. * Import meshes into a scene
  67761. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67762. * @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)
  67763. * @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)
  67764. * @param scene the instance of BABYLON.Scene to append to
  67765. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67766. * @param onProgress a callback with a progress event for each file being loaded
  67767. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67768. * @param pluginExtension the extension used to determine the plugin
  67769. * @returns The loaded plugin
  67770. */
  67771. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67772. if (sceneFilename === void 0) { sceneFilename = ""; }
  67773. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67774. if (onSuccess === void 0) { onSuccess = null; }
  67775. if (onProgress === void 0) { onProgress = null; }
  67776. if (onError === void 0) { onError = null; }
  67777. if (pluginExtension === void 0) { pluginExtension = null; }
  67778. if (!scene) {
  67779. BABYLON.Tools.Error("No scene available to import mesh to");
  67780. return null;
  67781. }
  67782. if (!sceneFilename) {
  67783. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67784. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67785. }
  67786. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67787. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67788. return null;
  67789. }
  67790. var loadingToken = {};
  67791. scene._addPendingData(loadingToken);
  67792. var disposeHandler = function () {
  67793. scene._removePendingData(loadingToken);
  67794. };
  67795. var errorHandler = function (message, exception) {
  67796. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67797. if (onError) {
  67798. onError(scene, errorMessage, exception);
  67799. }
  67800. else {
  67801. BABYLON.Tools.Error(errorMessage);
  67802. // should the exception be thrown?
  67803. }
  67804. disposeHandler();
  67805. };
  67806. var progressHandler = onProgress ? function (event) {
  67807. try {
  67808. onProgress(event);
  67809. }
  67810. catch (e) {
  67811. errorHandler("Error in onProgress callback", e);
  67812. }
  67813. } : undefined;
  67814. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67815. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67816. if (onSuccess) {
  67817. try {
  67818. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67819. }
  67820. catch (e) {
  67821. errorHandler("Error in onSuccess callback", e);
  67822. }
  67823. }
  67824. scene._removePendingData(loadingToken);
  67825. };
  67826. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67827. if (plugin.rewriteRootURL) {
  67828. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67829. }
  67830. if (sceneFilename === "") {
  67831. if (sceneFilename === "") {
  67832. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67833. }
  67834. }
  67835. if (plugin.importMesh) {
  67836. var syncedPlugin = plugin;
  67837. var meshes = new Array();
  67838. var particleSystems = new Array();
  67839. var skeletons = new Array();
  67840. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67841. return;
  67842. }
  67843. scene.loadingPluginName = plugin.name;
  67844. successHandler(meshes, particleSystems, skeletons, []);
  67845. }
  67846. else {
  67847. var asyncedPlugin = plugin;
  67848. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67849. scene.loadingPluginName = plugin.name;
  67850. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67851. }).catch(function (error) {
  67852. errorHandler(error.message, error);
  67853. });
  67854. }
  67855. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67856. };
  67857. /**
  67858. * Import meshes into a scene
  67859. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67860. * @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)
  67861. * @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)
  67862. * @param scene the instance of BABYLON.Scene to append to
  67863. * @param onProgress a callback with a progress event for each file being loaded
  67864. * @param pluginExtension the extension used to determine the plugin
  67865. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67866. */
  67867. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67868. if (sceneFilename === void 0) { sceneFilename = ""; }
  67869. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67870. if (onProgress === void 0) { onProgress = null; }
  67871. if (pluginExtension === void 0) { pluginExtension = null; }
  67872. return new Promise(function (resolve, reject) {
  67873. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67874. resolve({
  67875. meshes: meshes,
  67876. particleSystems: particleSystems,
  67877. skeletons: skeletons,
  67878. animationGroups: animationGroups
  67879. });
  67880. }, onProgress, function (scene, message, exception) {
  67881. reject(exception || new Error(message));
  67882. }, pluginExtension);
  67883. });
  67884. };
  67885. /**
  67886. * Load a scene
  67887. * @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)
  67888. * @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)
  67889. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67890. * @param onSuccess a callback with the scene when import succeeds
  67891. * @param onProgress a callback with a progress event for each file being loaded
  67892. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67893. * @param pluginExtension the extension used to determine the plugin
  67894. * @returns The loaded plugin
  67895. */
  67896. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67897. if (onSuccess === void 0) { onSuccess = null; }
  67898. if (onProgress === void 0) { onProgress = null; }
  67899. if (onError === void 0) { onError = null; }
  67900. if (pluginExtension === void 0) { pluginExtension = null; }
  67901. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67902. };
  67903. /**
  67904. * Load a scene
  67905. * @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)
  67906. * @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)
  67907. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67908. * @param onProgress a callback with a progress event for each file being loaded
  67909. * @param pluginExtension the extension used to determine the plugin
  67910. * @returns The loaded scene
  67911. */
  67912. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67913. if (onProgress === void 0) { onProgress = null; }
  67914. if (pluginExtension === void 0) { pluginExtension = null; }
  67915. return new Promise(function (resolve, reject) {
  67916. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67917. resolve(scene);
  67918. }, onProgress, function (scene, message, exception) {
  67919. reject(exception || new Error(message));
  67920. }, pluginExtension);
  67921. });
  67922. };
  67923. /**
  67924. * Append a scene
  67925. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67926. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67927. * @param scene is the instance of BABYLON.Scene to append to
  67928. * @param onSuccess a callback with the scene when import succeeds
  67929. * @param onProgress a callback with a progress event for each file being loaded
  67930. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67931. * @param pluginExtension the extension used to determine the plugin
  67932. * @returns The loaded plugin
  67933. */
  67934. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67935. if (sceneFilename === void 0) { sceneFilename = ""; }
  67936. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67937. if (onSuccess === void 0) { onSuccess = null; }
  67938. if (onProgress === void 0) { onProgress = null; }
  67939. if (onError === void 0) { onError = null; }
  67940. if (pluginExtension === void 0) { pluginExtension = null; }
  67941. if (!scene) {
  67942. BABYLON.Tools.Error("No scene available to append to");
  67943. return null;
  67944. }
  67945. if (!sceneFilename) {
  67946. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67947. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67948. }
  67949. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67950. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67951. return null;
  67952. }
  67953. if (SceneLoader.ShowLoadingScreen) {
  67954. scene.getEngine().displayLoadingUI();
  67955. }
  67956. var loadingToken = {};
  67957. scene._addPendingData(loadingToken);
  67958. var disposeHandler = function () {
  67959. scene._removePendingData(loadingToken);
  67960. scene.getEngine().hideLoadingUI();
  67961. };
  67962. var errorHandler = function (message, exception) {
  67963. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67964. if (onError) {
  67965. onError(scene, errorMessage, exception);
  67966. }
  67967. else {
  67968. BABYLON.Tools.Error(errorMessage);
  67969. // should the exception be thrown?
  67970. }
  67971. disposeHandler();
  67972. };
  67973. var progressHandler = onProgress ? function (event) {
  67974. try {
  67975. onProgress(event);
  67976. }
  67977. catch (e) {
  67978. errorHandler("Error in onProgress callback", e);
  67979. }
  67980. } : undefined;
  67981. var successHandler = function () {
  67982. if (onSuccess) {
  67983. try {
  67984. onSuccess(scene);
  67985. }
  67986. catch (e) {
  67987. errorHandler("Error in onSuccess callback", e);
  67988. }
  67989. }
  67990. scene._removePendingData(loadingToken);
  67991. };
  67992. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67993. if (sceneFilename === "") {
  67994. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67995. }
  67996. if (plugin.load) {
  67997. var syncedPlugin = plugin;
  67998. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67999. return;
  68000. }
  68001. scene.loadingPluginName = plugin.name;
  68002. successHandler();
  68003. }
  68004. else {
  68005. var asyncedPlugin = plugin;
  68006. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  68007. scene.loadingPluginName = plugin.name;
  68008. successHandler();
  68009. }).catch(function (error) {
  68010. errorHandler(error.message, error);
  68011. });
  68012. }
  68013. if (SceneLoader.ShowLoadingScreen) {
  68014. scene.executeWhenReady(function () {
  68015. scene.getEngine().hideLoadingUI();
  68016. });
  68017. }
  68018. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68019. };
  68020. /**
  68021. * Append a scene
  68022. * @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)
  68023. * @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)
  68024. * @param scene is the instance of BABYLON.Scene to append to
  68025. * @param onProgress a callback with a progress event for each file being loaded
  68026. * @param pluginExtension the extension used to determine the plugin
  68027. * @returns The given scene
  68028. */
  68029. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68030. if (sceneFilename === void 0) { sceneFilename = ""; }
  68031. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68032. if (onProgress === void 0) { onProgress = null; }
  68033. if (pluginExtension === void 0) { pluginExtension = null; }
  68034. return new Promise(function (resolve, reject) {
  68035. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  68036. resolve(scene);
  68037. }, onProgress, function (scene, message, exception) {
  68038. reject(exception || new Error(message));
  68039. }, pluginExtension);
  68040. });
  68041. };
  68042. /**
  68043. * Load a scene into an asset container
  68044. * @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)
  68045. * @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)
  68046. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  68047. * @param onSuccess a callback with the scene when import succeeds
  68048. * @param onProgress a callback with a progress event for each file being loaded
  68049. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68050. * @param pluginExtension the extension used to determine the plugin
  68051. * @returns The loaded plugin
  68052. */
  68053. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68054. if (sceneFilename === void 0) { sceneFilename = ""; }
  68055. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68056. if (onSuccess === void 0) { onSuccess = null; }
  68057. if (onProgress === void 0) { onProgress = null; }
  68058. if (onError === void 0) { onError = null; }
  68059. if (pluginExtension === void 0) { pluginExtension = null; }
  68060. if (!scene) {
  68061. BABYLON.Tools.Error("No scene available to load asset container to");
  68062. return null;
  68063. }
  68064. if (!sceneFilename) {
  68065. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68066. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68067. }
  68068. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68069. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68070. return null;
  68071. }
  68072. var loadingToken = {};
  68073. scene._addPendingData(loadingToken);
  68074. var disposeHandler = function () {
  68075. scene._removePendingData(loadingToken);
  68076. };
  68077. var errorHandler = function (message, exception) {
  68078. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68079. if (onError) {
  68080. onError(scene, errorMessage, exception);
  68081. }
  68082. else {
  68083. BABYLON.Tools.Error(errorMessage);
  68084. // should the exception be thrown?
  68085. }
  68086. disposeHandler();
  68087. };
  68088. var progressHandler = onProgress ? function (event) {
  68089. try {
  68090. onProgress(event);
  68091. }
  68092. catch (e) {
  68093. errorHandler("Error in onProgress callback", e);
  68094. }
  68095. } : undefined;
  68096. var successHandler = function (assets) {
  68097. if (onSuccess) {
  68098. try {
  68099. onSuccess(assets);
  68100. }
  68101. catch (e) {
  68102. errorHandler("Error in onSuccess callback", e);
  68103. }
  68104. }
  68105. scene._removePendingData(loadingToken);
  68106. };
  68107. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68108. if (plugin.loadAssetContainer) {
  68109. var syncedPlugin = plugin;
  68110. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68111. if (!assetContainer) {
  68112. return;
  68113. }
  68114. scene.loadingPluginName = plugin.name;
  68115. successHandler(assetContainer);
  68116. }
  68117. else if (plugin.loadAssetContainerAsync) {
  68118. var asyncedPlugin = plugin;
  68119. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68120. scene.loadingPluginName = plugin.name;
  68121. successHandler(assetContainer);
  68122. }).catch(function (error) {
  68123. errorHandler(error.message, error);
  68124. });
  68125. }
  68126. else {
  68127. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68128. }
  68129. if (SceneLoader.ShowLoadingScreen) {
  68130. scene.executeWhenReady(function () {
  68131. scene.getEngine().hideLoadingUI();
  68132. });
  68133. }
  68134. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68135. };
  68136. /**
  68137. * Load a scene into an asset container
  68138. * @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)
  68139. * @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)
  68140. * @param scene is the instance of BABYLON.Scene to append to
  68141. * @param onProgress a callback with a progress event for each file being loaded
  68142. * @param pluginExtension the extension used to determine the plugin
  68143. * @returns The loaded asset container
  68144. */
  68145. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68146. if (sceneFilename === void 0) { sceneFilename = ""; }
  68147. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68148. if (onProgress === void 0) { onProgress = null; }
  68149. if (pluginExtension === void 0) { pluginExtension = null; }
  68150. return new Promise(function (resolve, reject) {
  68151. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68152. resolve(assetContainer);
  68153. }, onProgress, function (scene, message, exception) {
  68154. reject(exception || new Error(message));
  68155. }, pluginExtension);
  68156. });
  68157. };
  68158. // Flags
  68159. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68160. SceneLoader._ShowLoadingScreen = true;
  68161. SceneLoader._CleanBoneMatrixWeights = false;
  68162. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68163. // Members
  68164. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68165. SceneLoader._registeredPlugins = {};
  68166. return SceneLoader;
  68167. }());
  68168. BABYLON.SceneLoader = SceneLoader;
  68169. ;
  68170. })(BABYLON || (BABYLON = {}));
  68171. //# sourceMappingURL=babylon.sceneLoader.js.map
  68172. var BABYLON;
  68173. (function (BABYLON) {
  68174. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68175. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68176. var parsedMaterial = parsedData.materials[index];
  68177. if (parsedMaterial.id === id) {
  68178. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68179. }
  68180. }
  68181. return null;
  68182. };
  68183. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68184. for (var i in names) {
  68185. if (mesh.name === names[i]) {
  68186. hierarchyIds.push(mesh.id);
  68187. return true;
  68188. }
  68189. }
  68190. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68191. hierarchyIds.push(mesh.id);
  68192. return true;
  68193. }
  68194. return false;
  68195. };
  68196. var logOperation = function (operation, producer) {
  68197. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68198. };
  68199. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68200. if (addToScene === void 0) { addToScene = false; }
  68201. var container = new BABYLON.AssetContainer(scene);
  68202. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68203. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68204. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68205. // and avoid problems with multiple concurrent .babylon loads.
  68206. var log = "importScene has failed JSON parse";
  68207. try {
  68208. var parsedData = JSON.parse(data);
  68209. log = "";
  68210. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68211. var index;
  68212. var cache;
  68213. // Lights
  68214. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68215. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68216. var parsedLight = parsedData.lights[index];
  68217. var light = BABYLON.Light.Parse(parsedLight, scene);
  68218. if (light) {
  68219. container.lights.push(light);
  68220. log += (index === 0 ? "\n\tLights:" : "");
  68221. log += "\n\t\t" + light.toString(fullDetails);
  68222. }
  68223. }
  68224. }
  68225. // Animations
  68226. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68227. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68228. var parsedAnimation = parsedData.animations[index];
  68229. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68230. scene.animations.push(animation);
  68231. container.animations.push(animation);
  68232. log += (index === 0 ? "\n\tAnimations:" : "");
  68233. log += "\n\t\t" + animation.toString(fullDetails);
  68234. }
  68235. }
  68236. // Materials
  68237. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68238. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68239. var parsedMaterial = parsedData.materials[index];
  68240. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68241. container.materials.push(mat);
  68242. log += (index === 0 ? "\n\tMaterials:" : "");
  68243. log += "\n\t\t" + mat.toString(fullDetails);
  68244. }
  68245. }
  68246. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68247. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68248. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68249. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68250. container.multiMaterials.push(mmat);
  68251. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68252. log += "\n\t\t" + mmat.toString(fullDetails);
  68253. }
  68254. }
  68255. // Morph targets
  68256. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68257. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68258. var managerData = _a[_i];
  68259. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68260. }
  68261. }
  68262. // Skeletons
  68263. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68264. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68265. var parsedSkeleton = parsedData.skeletons[index];
  68266. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68267. container.skeletons.push(skeleton);
  68268. log += (index === 0 ? "\n\tSkeletons:" : "");
  68269. log += "\n\t\t" + skeleton.toString(fullDetails);
  68270. }
  68271. }
  68272. // Geometries
  68273. var geometries = parsedData.geometries;
  68274. if (geometries !== undefined && geometries !== null) {
  68275. var addedGeometry = new Array();
  68276. // Boxes
  68277. var boxes = geometries.boxes;
  68278. if (boxes !== undefined && boxes !== null) {
  68279. for (index = 0, cache = boxes.length; index < cache; index++) {
  68280. var parsedBox = boxes[index];
  68281. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68282. }
  68283. }
  68284. // Spheres
  68285. var spheres = geometries.spheres;
  68286. if (spheres !== undefined && spheres !== null) {
  68287. for (index = 0, cache = spheres.length; index < cache; index++) {
  68288. var parsedSphere = spheres[index];
  68289. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68290. }
  68291. }
  68292. // Cylinders
  68293. var cylinders = geometries.cylinders;
  68294. if (cylinders !== undefined && cylinders !== null) {
  68295. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68296. var parsedCylinder = cylinders[index];
  68297. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68298. }
  68299. }
  68300. // Toruses
  68301. var toruses = geometries.toruses;
  68302. if (toruses !== undefined && toruses !== null) {
  68303. for (index = 0, cache = toruses.length; index < cache; index++) {
  68304. var parsedTorus = toruses[index];
  68305. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68306. }
  68307. }
  68308. // Grounds
  68309. var grounds = geometries.grounds;
  68310. if (grounds !== undefined && grounds !== null) {
  68311. for (index = 0, cache = grounds.length; index < cache; index++) {
  68312. var parsedGround = grounds[index];
  68313. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68314. }
  68315. }
  68316. // Planes
  68317. var planes = geometries.planes;
  68318. if (planes !== undefined && planes !== null) {
  68319. for (index = 0, cache = planes.length; index < cache; index++) {
  68320. var parsedPlane = planes[index];
  68321. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68322. }
  68323. }
  68324. // TorusKnots
  68325. var torusKnots = geometries.torusKnots;
  68326. if (torusKnots !== undefined && torusKnots !== null) {
  68327. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68328. var parsedTorusKnot = torusKnots[index];
  68329. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68330. }
  68331. }
  68332. // VertexData
  68333. var vertexData = geometries.vertexData;
  68334. if (vertexData !== undefined && vertexData !== null) {
  68335. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68336. var parsedVertexData = vertexData[index];
  68337. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68338. }
  68339. }
  68340. addedGeometry.forEach(function (g) {
  68341. if (g) {
  68342. container.geometries.push(g);
  68343. }
  68344. });
  68345. }
  68346. // Transform nodes
  68347. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68348. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68349. var parsedTransformNode = parsedData.transformNodes[index];
  68350. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68351. container.transformNodes.push(node);
  68352. }
  68353. }
  68354. // Meshes
  68355. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68356. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68357. var parsedMesh = parsedData.meshes[index];
  68358. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68359. container.meshes.push(mesh);
  68360. log += (index === 0 ? "\n\tMeshes:" : "");
  68361. log += "\n\t\t" + mesh.toString(fullDetails);
  68362. }
  68363. }
  68364. // Cameras
  68365. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68366. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68367. var parsedCamera = parsedData.cameras[index];
  68368. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68369. container.cameras.push(camera);
  68370. log += (index === 0 ? "\n\tCameras:" : "");
  68371. log += "\n\t\t" + camera.toString(fullDetails);
  68372. }
  68373. }
  68374. // Browsing all the graph to connect the dots
  68375. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68376. var camera = scene.cameras[index];
  68377. if (camera._waitingParentId) {
  68378. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68379. camera._waitingParentId = null;
  68380. }
  68381. }
  68382. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68383. var light_1 = scene.lights[index];
  68384. if (light_1 && light_1._waitingParentId) {
  68385. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68386. light_1._waitingParentId = null;
  68387. }
  68388. }
  68389. // Sounds
  68390. // TODO: add sound
  68391. var loadedSounds = [];
  68392. var loadedSound;
  68393. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68394. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68395. var parsedSound = parsedData.sounds[index];
  68396. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68397. if (!parsedSound.url)
  68398. parsedSound.url = parsedSound.name;
  68399. if (!loadedSounds[parsedSound.url]) {
  68400. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68401. loadedSounds[parsedSound.url] = loadedSound;
  68402. container.sounds.push(loadedSound);
  68403. }
  68404. else {
  68405. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68406. }
  68407. }
  68408. else {
  68409. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68410. }
  68411. }
  68412. }
  68413. loadedSounds = [];
  68414. // Connect parents & children and parse actions
  68415. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68416. var transformNode = scene.transformNodes[index];
  68417. if (transformNode._waitingParentId) {
  68418. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68419. transformNode._waitingParentId = null;
  68420. }
  68421. }
  68422. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68423. var mesh = scene.meshes[index];
  68424. if (mesh._waitingParentId) {
  68425. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68426. mesh._waitingParentId = null;
  68427. }
  68428. if (mesh._waitingActions) {
  68429. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68430. mesh._waitingActions = null;
  68431. }
  68432. }
  68433. // freeze world matrix application
  68434. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68435. var currentMesh = scene.meshes[index];
  68436. if (currentMesh._waitingFreezeWorldMatrix) {
  68437. currentMesh.freezeWorldMatrix();
  68438. currentMesh._waitingFreezeWorldMatrix = null;
  68439. }
  68440. else {
  68441. currentMesh.computeWorldMatrix(true);
  68442. }
  68443. }
  68444. // Particles Systems
  68445. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68446. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68447. var parsedParticleSystem = parsedData.particleSystems[index];
  68448. if (parsedParticleSystem.activeParticleCount) {
  68449. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68450. container.particleSystems.push(ps);
  68451. }
  68452. else {
  68453. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68454. container.particleSystems.push(ps);
  68455. }
  68456. }
  68457. }
  68458. // Shadows
  68459. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68460. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68461. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68462. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68463. // SG would be available on their associated lights
  68464. }
  68465. }
  68466. // Lights exclusions / inclusions
  68467. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68468. var light_2 = scene.lights[index];
  68469. // Excluded check
  68470. if (light_2._excludedMeshesIds.length > 0) {
  68471. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68472. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68473. if (excludedMesh) {
  68474. light_2.excludedMeshes.push(excludedMesh);
  68475. }
  68476. }
  68477. light_2._excludedMeshesIds = [];
  68478. }
  68479. // Included check
  68480. if (light_2._includedOnlyMeshesIds.length > 0) {
  68481. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68482. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68483. if (includedOnlyMesh) {
  68484. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68485. }
  68486. }
  68487. light_2._includedOnlyMeshesIds = [];
  68488. }
  68489. }
  68490. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  68491. // Actions (scene)
  68492. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68493. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68494. }
  68495. if (!addToScene) {
  68496. container.removeAllFromScene();
  68497. }
  68498. }
  68499. catch (err) {
  68500. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68501. if (onError) {
  68502. onError(msg, err);
  68503. }
  68504. else {
  68505. BABYLON.Tools.Log(msg);
  68506. throw err;
  68507. }
  68508. }
  68509. finally {
  68510. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68511. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68512. }
  68513. }
  68514. return container;
  68515. };
  68516. BABYLON.SceneLoader.RegisterPlugin({
  68517. name: "babylon.js",
  68518. extensions: ".babylon",
  68519. canDirectLoad: function (data) {
  68520. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68521. return true;
  68522. }
  68523. return false;
  68524. },
  68525. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68526. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68527. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68528. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68529. // and avoid problems with multiple concurrent .babylon loads.
  68530. var log = "importMesh has failed JSON parse";
  68531. try {
  68532. var parsedData = JSON.parse(data);
  68533. log = "";
  68534. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68535. if (!meshesNames) {
  68536. meshesNames = null;
  68537. }
  68538. else if (!Array.isArray(meshesNames)) {
  68539. meshesNames = [meshesNames];
  68540. }
  68541. var hierarchyIds = new Array();
  68542. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68543. var loadedSkeletonsIds = [];
  68544. var loadedMaterialsIds = [];
  68545. var index;
  68546. var cache;
  68547. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68548. var parsedMesh = parsedData.meshes[index];
  68549. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68550. if (meshesNames !== null) {
  68551. // Remove found mesh name from list.
  68552. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68553. }
  68554. //Geometry?
  68555. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68556. //does the file contain geometries?
  68557. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68558. //find the correct geometry and add it to the scene
  68559. var found = false;
  68560. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68561. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68562. return;
  68563. }
  68564. else {
  68565. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68566. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68567. switch (geometryType) {
  68568. case "boxes":
  68569. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68570. break;
  68571. case "spheres":
  68572. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68573. break;
  68574. case "cylinders":
  68575. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68576. break;
  68577. case "toruses":
  68578. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68579. break;
  68580. case "grounds":
  68581. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68582. break;
  68583. case "planes":
  68584. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68585. break;
  68586. case "torusKnots":
  68587. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68588. break;
  68589. case "vertexData":
  68590. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68591. break;
  68592. }
  68593. found = true;
  68594. }
  68595. });
  68596. }
  68597. });
  68598. if (found === false) {
  68599. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68600. }
  68601. }
  68602. }
  68603. // Material ?
  68604. if (parsedMesh.materialId) {
  68605. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68606. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68607. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68608. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68609. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68610. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68611. var subMatId = parsedMultiMaterial.materials[matIndex];
  68612. loadedMaterialsIds.push(subMatId);
  68613. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68614. if (mat) {
  68615. log += "\n\tMaterial " + mat.toString(fullDetails);
  68616. }
  68617. }
  68618. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68619. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68620. if (mmat) {
  68621. materialFound = true;
  68622. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68623. }
  68624. break;
  68625. }
  68626. }
  68627. }
  68628. if (materialFound === false) {
  68629. loadedMaterialsIds.push(parsedMesh.materialId);
  68630. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68631. if (!mat) {
  68632. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68633. }
  68634. else {
  68635. log += "\n\tMaterial " + mat.toString(fullDetails);
  68636. }
  68637. }
  68638. }
  68639. // Skeleton ?
  68640. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68641. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68642. if (skeletonAlreadyLoaded === false) {
  68643. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68644. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68645. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68646. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68647. skeletons.push(skeleton);
  68648. loadedSkeletonsIds.push(parsedSkeleton.id);
  68649. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68650. }
  68651. }
  68652. }
  68653. }
  68654. // Morph targets ?
  68655. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68656. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68657. var managerData = _a[_i];
  68658. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68659. }
  68660. }
  68661. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68662. meshes.push(mesh);
  68663. log += "\n\tMesh " + mesh.toString(fullDetails);
  68664. }
  68665. }
  68666. // Connecting parents
  68667. var currentMesh;
  68668. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68669. currentMesh = scene.meshes[index];
  68670. if (currentMesh._waitingParentId) {
  68671. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68672. currentMesh._waitingParentId = null;
  68673. }
  68674. }
  68675. // freeze and compute world matrix application
  68676. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68677. currentMesh = scene.meshes[index];
  68678. if (currentMesh._waitingFreezeWorldMatrix) {
  68679. currentMesh.freezeWorldMatrix();
  68680. currentMesh._waitingFreezeWorldMatrix = null;
  68681. }
  68682. else {
  68683. currentMesh.computeWorldMatrix(true);
  68684. }
  68685. }
  68686. }
  68687. // Particles
  68688. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68689. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68690. var parsedParticleSystem = parsedData.particleSystems[index];
  68691. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68692. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68693. }
  68694. }
  68695. }
  68696. return true;
  68697. }
  68698. catch (err) {
  68699. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68700. if (onError) {
  68701. onError(msg, err);
  68702. }
  68703. else {
  68704. BABYLON.Tools.Log(msg);
  68705. throw err;
  68706. }
  68707. }
  68708. finally {
  68709. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68710. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68711. }
  68712. }
  68713. return false;
  68714. },
  68715. load: function (scene, data, rootUrl, onError) {
  68716. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68717. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68718. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68719. // and avoid problems with multiple concurrent .babylon loads.
  68720. var log = "importScene has failed JSON parse";
  68721. try {
  68722. var parsedData = JSON.parse(data);
  68723. log = "";
  68724. // Scene
  68725. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68726. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68727. }
  68728. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68729. scene.autoClear = parsedData.autoClear;
  68730. }
  68731. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68732. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68733. }
  68734. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68735. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68736. }
  68737. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68738. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68739. }
  68740. // Fog
  68741. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68742. scene.fogMode = parsedData.fogMode;
  68743. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68744. scene.fogStart = parsedData.fogStart;
  68745. scene.fogEnd = parsedData.fogEnd;
  68746. scene.fogDensity = parsedData.fogDensity;
  68747. log += "\tFog mode for scene: ";
  68748. switch (scene.fogMode) {
  68749. // getters not compiling, so using hardcoded
  68750. case 1:
  68751. log += "exp\n";
  68752. break;
  68753. case 2:
  68754. log += "exp2\n";
  68755. break;
  68756. case 3:
  68757. log += "linear\n";
  68758. break;
  68759. }
  68760. }
  68761. //Physics
  68762. if (parsedData.physicsEnabled) {
  68763. var physicsPlugin;
  68764. if (parsedData.physicsEngine === "cannon") {
  68765. physicsPlugin = new BABYLON.CannonJSPlugin();
  68766. }
  68767. else if (parsedData.physicsEngine === "oimo") {
  68768. physicsPlugin = new BABYLON.OimoJSPlugin();
  68769. }
  68770. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68771. //else - default engine, which is currently oimo
  68772. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68773. scene.enablePhysics(physicsGravity, physicsPlugin);
  68774. }
  68775. // Metadata
  68776. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68777. scene.metadata = parsedData.metadata;
  68778. }
  68779. //collisions, if defined. otherwise, default is true
  68780. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68781. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68782. }
  68783. scene.workerCollisions = !!parsedData.workerCollisions;
  68784. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68785. if (!container) {
  68786. return false;
  68787. }
  68788. if (parsedData.autoAnimate) {
  68789. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68790. }
  68791. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68792. scene.setActiveCameraByID(parsedData.activeCameraID);
  68793. }
  68794. // Environment texture
  68795. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68796. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68797. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68798. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68799. if (parsedData.environmentTextureRotationY) {
  68800. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68801. }
  68802. scene.environmentTexture = hdrTexture;
  68803. }
  68804. else {
  68805. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68806. if (parsedData.environmentTextureRotationY) {
  68807. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68808. }
  68809. scene.environmentTexture = cubeTexture;
  68810. }
  68811. if (parsedData.createDefaultSkybox === true) {
  68812. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68813. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68814. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68815. }
  68816. }
  68817. // Finish
  68818. return true;
  68819. }
  68820. catch (err) {
  68821. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68822. if (onError) {
  68823. onError(msg, err);
  68824. }
  68825. else {
  68826. BABYLON.Tools.Log(msg);
  68827. throw err;
  68828. }
  68829. }
  68830. finally {
  68831. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68832. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68833. }
  68834. }
  68835. return false;
  68836. },
  68837. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68838. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68839. return container;
  68840. }
  68841. });
  68842. })(BABYLON || (BABYLON = {}));
  68843. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68844. var BABYLON;
  68845. (function (BABYLON) {
  68846. var FilesInput = /** @class */ (function () {
  68847. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68848. this.onProcessFileCallback = function () { return true; };
  68849. this._engine = engine;
  68850. this._currentScene = scene;
  68851. this._sceneLoadedCallback = sceneLoadedCallback;
  68852. this._progressCallback = progressCallback;
  68853. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68854. this._textureLoadingCallback = textureLoadingCallback;
  68855. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68856. this._onReloadCallback = onReloadCallback;
  68857. this._errorCallback = errorCallback;
  68858. }
  68859. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68860. var _this = this;
  68861. if (elementToMonitor) {
  68862. this._elementToMonitor = elementToMonitor;
  68863. this._dragEnterHandler = function (e) { _this.drag(e); };
  68864. this._dragOverHandler = function (e) { _this.drag(e); };
  68865. this._dropHandler = function (e) { _this.drop(e); };
  68866. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68867. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68868. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68869. }
  68870. };
  68871. FilesInput.prototype.dispose = function () {
  68872. if (!this._elementToMonitor) {
  68873. return;
  68874. }
  68875. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68876. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68877. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68878. };
  68879. FilesInput.prototype.renderFunction = function () {
  68880. if (this._additionalRenderLoopLogicCallback) {
  68881. this._additionalRenderLoopLogicCallback();
  68882. }
  68883. if (this._currentScene) {
  68884. if (this._textureLoadingCallback) {
  68885. var remaining = this._currentScene.getWaitingItemsCount();
  68886. if (remaining > 0) {
  68887. this._textureLoadingCallback(remaining);
  68888. }
  68889. }
  68890. this._currentScene.render();
  68891. }
  68892. };
  68893. FilesInput.prototype.drag = function (e) {
  68894. e.stopPropagation();
  68895. e.preventDefault();
  68896. };
  68897. FilesInput.prototype.drop = function (eventDrop) {
  68898. eventDrop.stopPropagation();
  68899. eventDrop.preventDefault();
  68900. this.loadFiles(eventDrop);
  68901. };
  68902. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68903. var _this = this;
  68904. var reader = folder.createReader();
  68905. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68906. reader.readEntries(function (entries) {
  68907. remaining.count += entries.length;
  68908. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68909. var entry = entries_1[_i];
  68910. if (entry.isFile) {
  68911. entry.file(function (file) {
  68912. file.correctName = relativePath + file.name;
  68913. files.push(file);
  68914. if (--remaining.count === 0) {
  68915. callback();
  68916. }
  68917. });
  68918. }
  68919. else if (entry.isDirectory) {
  68920. _this._traverseFolder(entry, files, remaining, callback);
  68921. }
  68922. }
  68923. if (--remaining.count) {
  68924. callback();
  68925. }
  68926. });
  68927. };
  68928. FilesInput.prototype._processFiles = function (files) {
  68929. for (var i = 0; i < files.length; i++) {
  68930. var name = files[i].correctName.toLowerCase();
  68931. var extension = name.split('.').pop();
  68932. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68933. continue;
  68934. }
  68935. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68936. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68937. this._sceneFileToLoad = files[i];
  68938. }
  68939. else {
  68940. FilesInput.FilesToLoad[name] = files[i];
  68941. }
  68942. }
  68943. };
  68944. FilesInput.prototype.loadFiles = function (event) {
  68945. var _this = this;
  68946. if (this._startingProcessingFilesCallback)
  68947. this._startingProcessingFilesCallback();
  68948. // Handling data transfer via drag'n'drop
  68949. if (event && event.dataTransfer && event.dataTransfer.files) {
  68950. this._filesToLoad = event.dataTransfer.files;
  68951. }
  68952. // Handling files from input files
  68953. if (event && event.target && event.target.files) {
  68954. this._filesToLoad = event.target.files;
  68955. }
  68956. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68957. var files_1 = new Array();
  68958. var folders = [];
  68959. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68960. for (var i = 0; i < this._filesToLoad.length; i++) {
  68961. var fileToLoad = this._filesToLoad[i];
  68962. var name_1 = fileToLoad.name.toLowerCase();
  68963. var entry = void 0;
  68964. fileToLoad.correctName = name_1;
  68965. if (items) {
  68966. var item = items[i];
  68967. if (item.getAsEntry) {
  68968. entry = item.getAsEntry();
  68969. }
  68970. else if (item.webkitGetAsEntry) {
  68971. entry = item.webkitGetAsEntry();
  68972. }
  68973. }
  68974. if (!entry) {
  68975. files_1.push(fileToLoad);
  68976. }
  68977. else {
  68978. if (entry.isDirectory) {
  68979. folders.push(entry);
  68980. }
  68981. else {
  68982. files_1.push(fileToLoad);
  68983. }
  68984. }
  68985. }
  68986. if (folders.length === 0) {
  68987. this._processFiles(files_1);
  68988. this._processReload();
  68989. }
  68990. else {
  68991. var remaining = { count: folders.length };
  68992. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68993. var folder = folders_1[_i];
  68994. this._traverseFolder(folder, files_1, remaining, function () {
  68995. _this._processFiles(files_1);
  68996. if (remaining.count === 0) {
  68997. _this._processReload();
  68998. }
  68999. });
  69000. }
  69001. }
  69002. }
  69003. };
  69004. FilesInput.prototype._processReload = function () {
  69005. if (this._onReloadCallback) {
  69006. this._onReloadCallback(this._sceneFileToLoad);
  69007. }
  69008. else {
  69009. this.reload();
  69010. }
  69011. };
  69012. FilesInput.prototype.reload = function () {
  69013. var _this = this;
  69014. // If a scene file has been provided
  69015. if (this._sceneFileToLoad) {
  69016. if (this._currentScene) {
  69017. if (BABYLON.Tools.errorsCount > 0) {
  69018. BABYLON.Tools.ClearLogCache();
  69019. }
  69020. this._engine.stopRenderLoop();
  69021. }
  69022. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  69023. if (_this._progressCallback) {
  69024. _this._progressCallback(progress);
  69025. }
  69026. }).then(function (scene) {
  69027. if (_this._currentScene) {
  69028. _this._currentScene.dispose();
  69029. }
  69030. _this._currentScene = scene;
  69031. if (_this._sceneLoadedCallback) {
  69032. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  69033. }
  69034. // Wait for textures and shaders to be ready
  69035. _this._currentScene.executeWhenReady(function () {
  69036. _this._engine.runRenderLoop(function () {
  69037. _this.renderFunction();
  69038. });
  69039. });
  69040. }).catch(function (error) {
  69041. if (_this._errorCallback) {
  69042. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  69043. }
  69044. });
  69045. }
  69046. else {
  69047. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  69048. }
  69049. };
  69050. FilesInput.FilesToLoad = {};
  69051. return FilesInput;
  69052. }());
  69053. BABYLON.FilesInput = FilesInput;
  69054. })(BABYLON || (BABYLON = {}));
  69055. //# sourceMappingURL=babylon.filesInput.js.map
  69056. var BABYLON;
  69057. (function (BABYLON) {
  69058. /**
  69059. * This class implement a typical dictionary using a string as key and the generic type T as value.
  69060. * The underlying implementation relies on an associative array to ensure the best performances.
  69061. * The value can be anything including 'null' but except 'undefined'
  69062. */
  69063. var StringDictionary = /** @class */ (function () {
  69064. function StringDictionary() {
  69065. this._count = 0;
  69066. this._data = {};
  69067. }
  69068. /**
  69069. * This will clear this dictionary and copy the content from the 'source' one.
  69070. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  69071. * @param source the dictionary to take the content from and copy to this dictionary
  69072. */
  69073. StringDictionary.prototype.copyFrom = function (source) {
  69074. var _this = this;
  69075. this.clear();
  69076. source.forEach(function (t, v) { return _this.add(t, v); });
  69077. };
  69078. /**
  69079. * Get a value based from its key
  69080. * @param key the given key to get the matching value from
  69081. * @return the value if found, otherwise undefined is returned
  69082. */
  69083. StringDictionary.prototype.get = function (key) {
  69084. var val = this._data[key];
  69085. if (val !== undefined) {
  69086. return val;
  69087. }
  69088. return undefined;
  69089. };
  69090. /**
  69091. * Get a value from its key or add it if it doesn't exist.
  69092. * This method will ensure you that a given key/data will be present in the dictionary.
  69093. * @param key the given key to get the matching value from
  69094. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69095. * The factory will only be invoked if there's no data for the given key.
  69096. * @return the value corresponding to the key.
  69097. */
  69098. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69099. var val = this.get(key);
  69100. if (val !== undefined) {
  69101. return val;
  69102. }
  69103. val = factory(key);
  69104. if (val) {
  69105. this.add(key, val);
  69106. }
  69107. return val;
  69108. };
  69109. /**
  69110. * Get a value from its key if present in the dictionary otherwise add it
  69111. * @param key the key to get the value from
  69112. * @param val if there's no such key/value pair in the dictionary add it with this value
  69113. * @return the value corresponding to the key
  69114. */
  69115. StringDictionary.prototype.getOrAdd = function (key, val) {
  69116. var curVal = this.get(key);
  69117. if (curVal !== undefined) {
  69118. return curVal;
  69119. }
  69120. this.add(key, val);
  69121. return val;
  69122. };
  69123. /**
  69124. * Check if there's a given key in the dictionary
  69125. * @param key the key to check for
  69126. * @return true if the key is present, false otherwise
  69127. */
  69128. StringDictionary.prototype.contains = function (key) {
  69129. return this._data[key] !== undefined;
  69130. };
  69131. /**
  69132. * Add a new key and its corresponding value
  69133. * @param key the key to add
  69134. * @param value the value corresponding to the key
  69135. * @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
  69136. */
  69137. StringDictionary.prototype.add = function (key, value) {
  69138. if (this._data[key] !== undefined) {
  69139. return false;
  69140. }
  69141. this._data[key] = value;
  69142. ++this._count;
  69143. return true;
  69144. };
  69145. StringDictionary.prototype.set = function (key, value) {
  69146. if (this._data[key] === undefined) {
  69147. return false;
  69148. }
  69149. this._data[key] = value;
  69150. return true;
  69151. };
  69152. /**
  69153. * Get the element of the given key and remove it from the dictionary
  69154. * @param key
  69155. */
  69156. StringDictionary.prototype.getAndRemove = function (key) {
  69157. var val = this.get(key);
  69158. if (val !== undefined) {
  69159. delete this._data[key];
  69160. --this._count;
  69161. return val;
  69162. }
  69163. return null;
  69164. };
  69165. /**
  69166. * Remove a key/value from the dictionary.
  69167. * @param key the key to remove
  69168. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69169. */
  69170. StringDictionary.prototype.remove = function (key) {
  69171. if (this.contains(key)) {
  69172. delete this._data[key];
  69173. --this._count;
  69174. return true;
  69175. }
  69176. return false;
  69177. };
  69178. /**
  69179. * Clear the whole content of the dictionary
  69180. */
  69181. StringDictionary.prototype.clear = function () {
  69182. this._data = {};
  69183. this._count = 0;
  69184. };
  69185. Object.defineProperty(StringDictionary.prototype, "count", {
  69186. get: function () {
  69187. return this._count;
  69188. },
  69189. enumerable: true,
  69190. configurable: true
  69191. });
  69192. /**
  69193. * Execute a callback on each key/val of the dictionary.
  69194. * Note that you can remove any element in this dictionary in the callback implementation
  69195. * @param callback the callback to execute on a given key/value pair
  69196. */
  69197. StringDictionary.prototype.forEach = function (callback) {
  69198. for (var cur in this._data) {
  69199. var val = this._data[cur];
  69200. callback(cur, val);
  69201. }
  69202. };
  69203. /**
  69204. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69205. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69206. * Note that you can remove any element in this dictionary in the callback implementation
  69207. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69208. */
  69209. StringDictionary.prototype.first = function (callback) {
  69210. for (var cur in this._data) {
  69211. var val = this._data[cur];
  69212. var res = callback(cur, val);
  69213. if (res) {
  69214. return res;
  69215. }
  69216. }
  69217. return null;
  69218. };
  69219. return StringDictionary;
  69220. }());
  69221. BABYLON.StringDictionary = StringDictionary;
  69222. })(BABYLON || (BABYLON = {}));
  69223. //# sourceMappingURL=babylon.stringDictionary.js.map
  69224. var BABYLON;
  69225. (function (BABYLON) {
  69226. var Tags = /** @class */ (function () {
  69227. function Tags() {
  69228. }
  69229. Tags.EnableFor = function (obj) {
  69230. obj._tags = obj._tags || {};
  69231. obj.hasTags = function () {
  69232. return Tags.HasTags(obj);
  69233. };
  69234. obj.addTags = function (tagsString) {
  69235. return Tags.AddTagsTo(obj, tagsString);
  69236. };
  69237. obj.removeTags = function (tagsString) {
  69238. return Tags.RemoveTagsFrom(obj, tagsString);
  69239. };
  69240. obj.matchesTagsQuery = function (tagsQuery) {
  69241. return Tags.MatchesQuery(obj, tagsQuery);
  69242. };
  69243. };
  69244. Tags.DisableFor = function (obj) {
  69245. delete obj._tags;
  69246. delete obj.hasTags;
  69247. delete obj.addTags;
  69248. delete obj.removeTags;
  69249. delete obj.matchesTagsQuery;
  69250. };
  69251. Tags.HasTags = function (obj) {
  69252. if (!obj._tags) {
  69253. return false;
  69254. }
  69255. return !BABYLON.Tools.IsEmpty(obj._tags);
  69256. };
  69257. Tags.GetTags = function (obj, asString) {
  69258. if (asString === void 0) { asString = true; }
  69259. if (!obj._tags) {
  69260. return null;
  69261. }
  69262. if (asString) {
  69263. var tagsArray = [];
  69264. for (var tag in obj._tags) {
  69265. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69266. tagsArray.push(tag);
  69267. }
  69268. }
  69269. return tagsArray.join(" ");
  69270. }
  69271. else {
  69272. return obj._tags;
  69273. }
  69274. };
  69275. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69276. // a tag cannot start with '||', '&&', and '!'
  69277. // it cannot contain whitespaces
  69278. Tags.AddTagsTo = function (obj, tagsString) {
  69279. if (!tagsString) {
  69280. return;
  69281. }
  69282. if (typeof tagsString !== "string") {
  69283. return;
  69284. }
  69285. var tags = tagsString.split(" ");
  69286. tags.forEach(function (tag, index, array) {
  69287. Tags._AddTagTo(obj, tag);
  69288. });
  69289. };
  69290. Tags._AddTagTo = function (obj, tag) {
  69291. tag = tag.trim();
  69292. if (tag === "" || tag === "true" || tag === "false") {
  69293. return;
  69294. }
  69295. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69296. return;
  69297. }
  69298. Tags.EnableFor(obj);
  69299. obj._tags[tag] = true;
  69300. };
  69301. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69302. if (!Tags.HasTags(obj)) {
  69303. return;
  69304. }
  69305. var tags = tagsString.split(" ");
  69306. for (var t in tags) {
  69307. Tags._RemoveTagFrom(obj, tags[t]);
  69308. }
  69309. };
  69310. Tags._RemoveTagFrom = function (obj, tag) {
  69311. delete obj._tags[tag];
  69312. };
  69313. Tags.MatchesQuery = function (obj, tagsQuery) {
  69314. if (tagsQuery === undefined) {
  69315. return true;
  69316. }
  69317. if (tagsQuery === "") {
  69318. return Tags.HasTags(obj);
  69319. }
  69320. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69321. };
  69322. return Tags;
  69323. }());
  69324. BABYLON.Tags = Tags;
  69325. })(BABYLON || (BABYLON = {}));
  69326. //# sourceMappingURL=babylon.tags.js.map
  69327. var BABYLON;
  69328. (function (BABYLON) {
  69329. /**
  69330. * Class used to evalaute queries containing `and` and `or` operators
  69331. */
  69332. var AndOrNotEvaluator = /** @class */ (function () {
  69333. function AndOrNotEvaluator() {
  69334. }
  69335. /**
  69336. * Evaluate a query
  69337. * @param query defines the query to evaluate
  69338. * @param evaluateCallback defines the callback used to filter result
  69339. * @returns true if the query matches
  69340. */
  69341. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69342. if (!query.match(/\([^\(\)]*\)/g)) {
  69343. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69344. }
  69345. else {
  69346. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69347. // remove parenthesis
  69348. r = r.slice(1, r.length - 1);
  69349. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69350. });
  69351. }
  69352. if (query === "true") {
  69353. return true;
  69354. }
  69355. if (query === "false") {
  69356. return false;
  69357. }
  69358. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69359. };
  69360. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69361. evaluateCallback = evaluateCallback || (function (r) {
  69362. return r === "true" ? true : false;
  69363. });
  69364. var result;
  69365. var or = parenthesisContent.split("||");
  69366. for (var i in or) {
  69367. if (or.hasOwnProperty(i)) {
  69368. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69369. var and = ori.split("&&");
  69370. if (and.length > 1) {
  69371. for (var j = 0; j < and.length; ++j) {
  69372. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69373. if (andj !== "true" && andj !== "false") {
  69374. if (andj[0] === "!") {
  69375. result = !evaluateCallback(andj.substring(1));
  69376. }
  69377. else {
  69378. result = evaluateCallback(andj);
  69379. }
  69380. }
  69381. else {
  69382. result = andj === "true" ? true : false;
  69383. }
  69384. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69385. ori = "false";
  69386. break;
  69387. }
  69388. }
  69389. }
  69390. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69391. result = true;
  69392. break;
  69393. }
  69394. // result equals false (or undefined)
  69395. if (ori !== "true" && ori !== "false") {
  69396. if (ori[0] === "!") {
  69397. result = !evaluateCallback(ori.substring(1));
  69398. }
  69399. else {
  69400. result = evaluateCallback(ori);
  69401. }
  69402. }
  69403. else {
  69404. result = ori === "true" ? true : false;
  69405. }
  69406. }
  69407. }
  69408. // the whole parenthesis scope is replaced by 'true' or 'false'
  69409. return result ? "true" : "false";
  69410. };
  69411. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69412. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69413. // remove whitespaces
  69414. r = r.replace(/[\s]/g, function () { return ""; });
  69415. return r.length % 2 ? "!" : "";
  69416. });
  69417. booleanString = booleanString.trim();
  69418. if (booleanString === "!true") {
  69419. booleanString = "false";
  69420. }
  69421. else if (booleanString === "!false") {
  69422. booleanString = "true";
  69423. }
  69424. return booleanString;
  69425. };
  69426. return AndOrNotEvaluator;
  69427. }());
  69428. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69429. })(BABYLON || (BABYLON = {}));
  69430. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69431. var BABYLON;
  69432. (function (BABYLON) {
  69433. /**
  69434. * Class used to enable access to IndexedDB
  69435. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69436. */
  69437. var Database = /** @class */ (function () {
  69438. /**
  69439. * Creates a new Database
  69440. * @param urlToScene defines the url to load the scene
  69441. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69442. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69443. */
  69444. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69445. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69446. var _this = this;
  69447. // Handling various flavors of prefixed version of IndexedDB
  69448. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69449. this.callbackManifestChecked = callbackManifestChecked;
  69450. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69451. this.db = null;
  69452. this._enableSceneOffline = false;
  69453. this._enableTexturesOffline = false;
  69454. this.manifestVersionFound = 0;
  69455. this.mustUpdateRessources = false;
  69456. this.hasReachedQuota = false;
  69457. if (!Database.IDBStorageEnabled) {
  69458. this.callbackManifestChecked(true);
  69459. }
  69460. else {
  69461. if (disableManifestCheck) {
  69462. this._enableSceneOffline = true;
  69463. this._enableTexturesOffline = true;
  69464. this.manifestVersionFound = 1;
  69465. BABYLON.Tools.SetImmediate(function () {
  69466. _this.callbackManifestChecked(true);
  69467. });
  69468. }
  69469. else {
  69470. this._checkManifestFile();
  69471. }
  69472. }
  69473. }
  69474. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69475. /**
  69476. * Gets a boolean indicating if scene must be saved in the database
  69477. */
  69478. get: function () {
  69479. return this._enableSceneOffline;
  69480. },
  69481. enumerable: true,
  69482. configurable: true
  69483. });
  69484. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69485. /**
  69486. * Gets a boolean indicating if textures must be saved in the database
  69487. */
  69488. get: function () {
  69489. return this._enableTexturesOffline;
  69490. },
  69491. enumerable: true,
  69492. configurable: true
  69493. });
  69494. Database.prototype._checkManifestFile = function () {
  69495. var _this = this;
  69496. var noManifestFile = function () {
  69497. _this._enableSceneOffline = false;
  69498. _this._enableTexturesOffline = false;
  69499. _this.callbackManifestChecked(false);
  69500. };
  69501. var timeStampUsed = false;
  69502. var manifestURL = this.currentSceneUrl + ".manifest";
  69503. var xhr = new XMLHttpRequest();
  69504. if (navigator.onLine) {
  69505. // Adding a timestamp to by-pass browsers' cache
  69506. timeStampUsed = true;
  69507. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69508. }
  69509. xhr.open("GET", manifestURL, true);
  69510. xhr.addEventListener("load", function () {
  69511. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69512. try {
  69513. var manifestFile = JSON.parse(xhr.response);
  69514. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69515. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69516. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69517. _this.manifestVersionFound = manifestFile.version;
  69518. }
  69519. if (_this.callbackManifestChecked) {
  69520. _this.callbackManifestChecked(true);
  69521. }
  69522. }
  69523. catch (ex) {
  69524. noManifestFile();
  69525. }
  69526. }
  69527. else {
  69528. noManifestFile();
  69529. }
  69530. }, false);
  69531. xhr.addEventListener("error", function (event) {
  69532. if (timeStampUsed) {
  69533. timeStampUsed = false;
  69534. // Let's retry without the timeStamp
  69535. // It could fail when coupled with HTML5 Offline API
  69536. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69537. xhr.open("GET", retryManifestURL, true);
  69538. xhr.send();
  69539. }
  69540. else {
  69541. noManifestFile();
  69542. }
  69543. }, false);
  69544. try {
  69545. xhr.send();
  69546. }
  69547. catch (ex) {
  69548. BABYLON.Tools.Error("Error on XHR send request.");
  69549. this.callbackManifestChecked(false);
  69550. }
  69551. };
  69552. /**
  69553. * Open the database and make it available
  69554. * @param successCallback defines the callback to call on success
  69555. * @param errorCallback defines the callback to call on error
  69556. */
  69557. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69558. var _this = this;
  69559. var handleError = function () {
  69560. _this.isSupported = false;
  69561. if (errorCallback)
  69562. errorCallback();
  69563. };
  69564. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69565. // Your browser doesn't support IndexedDB
  69566. this.isSupported = false;
  69567. if (errorCallback)
  69568. errorCallback();
  69569. }
  69570. else {
  69571. // If the DB hasn't been opened or created yet
  69572. if (!this.db) {
  69573. this.hasReachedQuota = false;
  69574. this.isSupported = true;
  69575. var request = this.idbFactory.open("babylonjs", 1);
  69576. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69577. request.onerror = function (event) {
  69578. handleError();
  69579. };
  69580. // executes when a version change transaction cannot complete due to other active transactions
  69581. request.onblocked = function (event) {
  69582. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69583. handleError();
  69584. };
  69585. // DB has been opened successfully
  69586. request.onsuccess = function (event) {
  69587. _this.db = request.result;
  69588. successCallback();
  69589. };
  69590. // Initialization of the DB. Creating Scenes & Textures stores
  69591. request.onupgradeneeded = function (event) {
  69592. _this.db = (event.target).result;
  69593. if (_this.db) {
  69594. try {
  69595. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69596. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69597. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69598. }
  69599. catch (ex) {
  69600. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69601. handleError();
  69602. }
  69603. }
  69604. };
  69605. }
  69606. // DB has already been created and opened
  69607. else {
  69608. if (successCallback)
  69609. successCallback();
  69610. }
  69611. }
  69612. };
  69613. /**
  69614. * Loads an image from the database
  69615. * @param url defines the url to load from
  69616. * @param image defines the target DOM image
  69617. */
  69618. Database.prototype.loadImageFromDB = function (url, image) {
  69619. var _this = this;
  69620. var completeURL = Database._ReturnFullUrlLocation(url);
  69621. var saveAndLoadImage = function () {
  69622. if (!_this.hasReachedQuota && _this.db !== null) {
  69623. // the texture is not yet in the DB, let's try to save it
  69624. _this._saveImageIntoDBAsync(completeURL, image);
  69625. }
  69626. // If the texture is not in the DB and we've reached the DB quota limit
  69627. // let's load it directly from the web
  69628. else {
  69629. image.src = url;
  69630. }
  69631. };
  69632. if (!this.mustUpdateRessources) {
  69633. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69634. }
  69635. // First time we're download the images or update requested in the manifest file by a version change
  69636. else {
  69637. saveAndLoadImage();
  69638. }
  69639. };
  69640. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69641. if (this.isSupported && this.db !== null) {
  69642. var texture;
  69643. var transaction = this.db.transaction(["textures"]);
  69644. transaction.onabort = function (event) {
  69645. image.src = url;
  69646. };
  69647. transaction.oncomplete = function (event) {
  69648. var blobTextureURL;
  69649. if (texture) {
  69650. var URL = window.URL || window.webkitURL;
  69651. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69652. image.onerror = function () {
  69653. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69654. image.src = url;
  69655. };
  69656. image.src = blobTextureURL;
  69657. }
  69658. else {
  69659. notInDBCallback();
  69660. }
  69661. };
  69662. var getRequest = transaction.objectStore("textures").get(url);
  69663. getRequest.onsuccess = function (event) {
  69664. texture = (event.target).result;
  69665. };
  69666. getRequest.onerror = function (event) {
  69667. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69668. image.src = url;
  69669. };
  69670. }
  69671. else {
  69672. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69673. image.src = url;
  69674. }
  69675. };
  69676. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69677. var _this = this;
  69678. if (this.isSupported) {
  69679. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69680. var generateBlobUrl = function () {
  69681. var blobTextureURL;
  69682. if (blob) {
  69683. var URL = window.URL || window.webkitURL;
  69684. try {
  69685. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69686. }
  69687. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69688. catch (ex) {
  69689. blobTextureURL = URL.createObjectURL(blob);
  69690. }
  69691. }
  69692. if (blobTextureURL) {
  69693. image.src = blobTextureURL;
  69694. }
  69695. };
  69696. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69697. var xhr = new XMLHttpRequest(), blob;
  69698. xhr.open("GET", url, true);
  69699. xhr.responseType = "blob";
  69700. xhr.addEventListener("load", function () {
  69701. if (xhr.status === 200 && _this.db) {
  69702. // Blob as response (XHR2)
  69703. blob = xhr.response;
  69704. var transaction = _this.db.transaction(["textures"], "readwrite");
  69705. // the transaction could abort because of a QuotaExceededError error
  69706. transaction.onabort = function (event) {
  69707. try {
  69708. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69709. var srcElement = (event.srcElement || event.target);
  69710. var error = srcElement.error;
  69711. if (error && error.name === "QuotaExceededError") {
  69712. _this.hasReachedQuota = true;
  69713. }
  69714. }
  69715. catch (ex) { }
  69716. generateBlobUrl();
  69717. };
  69718. transaction.oncomplete = function (event) {
  69719. generateBlobUrl();
  69720. };
  69721. var newTexture = { textureUrl: url, data: blob };
  69722. try {
  69723. // Put the blob into the dabase
  69724. var addRequest = transaction.objectStore("textures").put(newTexture);
  69725. addRequest.onsuccess = function (event) {
  69726. };
  69727. addRequest.onerror = function (event) {
  69728. generateBlobUrl();
  69729. };
  69730. }
  69731. catch (ex) {
  69732. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69733. if (ex.code === 25) {
  69734. Database.IsUASupportingBlobStorage = false;
  69735. }
  69736. image.src = url;
  69737. }
  69738. }
  69739. else {
  69740. image.src = url;
  69741. }
  69742. }, false);
  69743. xhr.addEventListener("error", function (event) {
  69744. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69745. image.src = url;
  69746. }, false);
  69747. xhr.send();
  69748. }
  69749. else {
  69750. image.src = url;
  69751. }
  69752. }
  69753. else {
  69754. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69755. image.src = url;
  69756. }
  69757. };
  69758. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69759. var _this = this;
  69760. var updateVersion = function () {
  69761. // the version is not yet in the DB or we need to update it
  69762. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69763. };
  69764. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69765. };
  69766. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69767. var _this = this;
  69768. if (this.isSupported && this.db) {
  69769. var version;
  69770. try {
  69771. var transaction = this.db.transaction(["versions"]);
  69772. transaction.oncomplete = function (event) {
  69773. if (version) {
  69774. // If the version in the JSON file is different from the version in DB
  69775. if (_this.manifestVersionFound !== version.data) {
  69776. _this.mustUpdateRessources = true;
  69777. updateInDBCallback();
  69778. }
  69779. else {
  69780. callback(version.data);
  69781. }
  69782. }
  69783. // version was not found in DB
  69784. else {
  69785. _this.mustUpdateRessources = true;
  69786. updateInDBCallback();
  69787. }
  69788. };
  69789. transaction.onabort = function (event) {
  69790. callback(-1);
  69791. };
  69792. var getRequest = transaction.objectStore("versions").get(url);
  69793. getRequest.onsuccess = function (event) {
  69794. version = (event.target).result;
  69795. };
  69796. getRequest.onerror = function (event) {
  69797. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69798. callback(-1);
  69799. };
  69800. }
  69801. catch (ex) {
  69802. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69803. callback(-1);
  69804. }
  69805. }
  69806. else {
  69807. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69808. callback(-1);
  69809. }
  69810. };
  69811. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69812. var _this = this;
  69813. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69814. try {
  69815. // Open a transaction to the database
  69816. var transaction = this.db.transaction(["versions"], "readwrite");
  69817. // the transaction could abort because of a QuotaExceededError error
  69818. transaction.onabort = function (event) {
  69819. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69820. var error = event.srcElement['error'];
  69821. if (error && error.name === "QuotaExceededError") {
  69822. _this.hasReachedQuota = true;
  69823. }
  69824. }
  69825. catch (ex) { }
  69826. callback(-1);
  69827. };
  69828. transaction.oncomplete = function (event) {
  69829. callback(_this.manifestVersionFound);
  69830. };
  69831. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69832. // Put the scene into the database
  69833. var addRequest = transaction.objectStore("versions").put(newVersion);
  69834. addRequest.onsuccess = function (event) {
  69835. };
  69836. addRequest.onerror = function (event) {
  69837. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69838. };
  69839. }
  69840. catch (ex) {
  69841. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69842. callback(-1);
  69843. }
  69844. }
  69845. else {
  69846. callback(-1);
  69847. }
  69848. };
  69849. /**
  69850. * Loads a file from database
  69851. * @param url defines the URL to load from
  69852. * @param sceneLoaded defines a callback to call on success
  69853. * @param progressCallBack defines a callback to call when progress changed
  69854. * @param errorCallback defines a callback to call on error
  69855. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69856. */
  69857. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69858. var _this = this;
  69859. var completeUrl = Database._ReturnFullUrlLocation(url);
  69860. var saveAndLoadFile = function () {
  69861. // the scene is not yet in the DB, let's try to save it
  69862. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69863. };
  69864. this._checkVersionFromDB(completeUrl, function (version) {
  69865. if (version !== -1) {
  69866. if (!_this.mustUpdateRessources) {
  69867. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69868. }
  69869. else {
  69870. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69871. }
  69872. }
  69873. else {
  69874. if (errorCallback) {
  69875. errorCallback();
  69876. }
  69877. }
  69878. });
  69879. };
  69880. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69881. if (this.isSupported && this.db) {
  69882. var targetStore;
  69883. if (url.indexOf(".babylon") !== -1) {
  69884. targetStore = "scenes";
  69885. }
  69886. else {
  69887. targetStore = "textures";
  69888. }
  69889. var file;
  69890. var transaction = this.db.transaction([targetStore]);
  69891. transaction.oncomplete = function (event) {
  69892. if (file) {
  69893. callback(file.data);
  69894. }
  69895. // file was not found in DB
  69896. else {
  69897. notInDBCallback();
  69898. }
  69899. };
  69900. transaction.onabort = function (event) {
  69901. notInDBCallback();
  69902. };
  69903. var getRequest = transaction.objectStore(targetStore).get(url);
  69904. getRequest.onsuccess = function (event) {
  69905. file = (event.target).result;
  69906. };
  69907. getRequest.onerror = function (event) {
  69908. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69909. notInDBCallback();
  69910. };
  69911. }
  69912. else {
  69913. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69914. callback();
  69915. }
  69916. };
  69917. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69918. var _this = this;
  69919. if (this.isSupported) {
  69920. var targetStore;
  69921. if (url.indexOf(".babylon") !== -1) {
  69922. targetStore = "scenes";
  69923. }
  69924. else {
  69925. targetStore = "textures";
  69926. }
  69927. // Create XHR
  69928. var xhr = new XMLHttpRequest();
  69929. var fileData;
  69930. xhr.open("GET", url, true);
  69931. if (useArrayBuffer) {
  69932. xhr.responseType = "arraybuffer";
  69933. }
  69934. if (progressCallback) {
  69935. xhr.onprogress = progressCallback;
  69936. }
  69937. xhr.addEventListener("load", function () {
  69938. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69939. // Blob as response (XHR2)
  69940. //fileData = xhr.responseText;
  69941. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69942. if (!_this.hasReachedQuota && _this.db) {
  69943. // Open a transaction to the database
  69944. var transaction = _this.db.transaction([targetStore], "readwrite");
  69945. // the transaction could abort because of a QuotaExceededError error
  69946. transaction.onabort = function (event) {
  69947. try {
  69948. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69949. var error = event.srcElement['error'];
  69950. if (error && error.name === "QuotaExceededError") {
  69951. _this.hasReachedQuota = true;
  69952. }
  69953. }
  69954. catch (ex) { }
  69955. callback(fileData);
  69956. };
  69957. transaction.oncomplete = function (event) {
  69958. callback(fileData);
  69959. };
  69960. var newFile;
  69961. if (targetStore === "scenes") {
  69962. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69963. }
  69964. else {
  69965. newFile = { textureUrl: url, data: fileData };
  69966. }
  69967. try {
  69968. // Put the scene into the database
  69969. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69970. addRequest.onsuccess = function (event) {
  69971. };
  69972. addRequest.onerror = function (event) {
  69973. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69974. };
  69975. }
  69976. catch (ex) {
  69977. callback(fileData);
  69978. }
  69979. }
  69980. else {
  69981. callback(fileData);
  69982. }
  69983. }
  69984. else {
  69985. callback();
  69986. }
  69987. }, false);
  69988. xhr.addEventListener("error", function (event) {
  69989. BABYLON.Tools.Error("error on XHR request.");
  69990. callback();
  69991. }, false);
  69992. xhr.send();
  69993. }
  69994. else {
  69995. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69996. callback();
  69997. }
  69998. };
  69999. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  70000. Database.IsUASupportingBlobStorage = true;
  70001. /** Gets a boolean indicating if Database storate is enabled */
  70002. Database.IDBStorageEnabled = true;
  70003. Database._ParseURL = function (url) {
  70004. var a = document.createElement('a');
  70005. a.href = url;
  70006. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  70007. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  70008. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  70009. return absLocation;
  70010. };
  70011. Database._ReturnFullUrlLocation = function (url) {
  70012. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  70013. return (Database._ParseURL(window.location.href) + url);
  70014. }
  70015. else {
  70016. return url;
  70017. }
  70018. };
  70019. return Database;
  70020. }());
  70021. BABYLON.Database = Database;
  70022. })(BABYLON || (BABYLON = {}));
  70023. //# sourceMappingURL=babylon.database.js.map
  70024. var BABYLON;
  70025. (function (BABYLON) {
  70026. var FresnelParameters = /** @class */ (function () {
  70027. function FresnelParameters() {
  70028. this._isEnabled = true;
  70029. this.leftColor = BABYLON.Color3.White();
  70030. this.rightColor = BABYLON.Color3.Black();
  70031. this.bias = 0;
  70032. this.power = 1;
  70033. }
  70034. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  70035. get: function () {
  70036. return this._isEnabled;
  70037. },
  70038. set: function (value) {
  70039. if (this._isEnabled === value) {
  70040. return;
  70041. }
  70042. this._isEnabled = value;
  70043. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  70044. },
  70045. enumerable: true,
  70046. configurable: true
  70047. });
  70048. FresnelParameters.prototype.clone = function () {
  70049. var newFresnelParameters = new FresnelParameters();
  70050. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  70051. return newFresnelParameters;
  70052. };
  70053. FresnelParameters.prototype.serialize = function () {
  70054. var serializationObject = {};
  70055. serializationObject.isEnabled = this.isEnabled;
  70056. serializationObject.leftColor = this.leftColor.asArray();
  70057. serializationObject.rightColor = this.rightColor.asArray();
  70058. serializationObject.bias = this.bias;
  70059. serializationObject.power = this.power;
  70060. return serializationObject;
  70061. };
  70062. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70063. var fresnelParameters = new FresnelParameters();
  70064. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70065. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70066. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70067. fresnelParameters.bias = parsedFresnelParameters.bias;
  70068. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70069. return fresnelParameters;
  70070. };
  70071. return FresnelParameters;
  70072. }());
  70073. BABYLON.FresnelParameters = FresnelParameters;
  70074. })(BABYLON || (BABYLON = {}));
  70075. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70076. var BABYLON;
  70077. (function (BABYLON) {
  70078. var MultiMaterial = /** @class */ (function (_super) {
  70079. __extends(MultiMaterial, _super);
  70080. function MultiMaterial(name, scene) {
  70081. var _this = _super.call(this, name, scene, true) || this;
  70082. scene.multiMaterials.push(_this);
  70083. _this.subMaterials = new Array();
  70084. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70085. return _this;
  70086. }
  70087. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70088. get: function () {
  70089. return this._subMaterials;
  70090. },
  70091. set: function (value) {
  70092. this._subMaterials = value;
  70093. this._hookArray(value);
  70094. },
  70095. enumerable: true,
  70096. configurable: true
  70097. });
  70098. MultiMaterial.prototype._hookArray = function (array) {
  70099. var _this = this;
  70100. var oldPush = array.push;
  70101. array.push = function () {
  70102. var items = [];
  70103. for (var _i = 0; _i < arguments.length; _i++) {
  70104. items[_i] = arguments[_i];
  70105. }
  70106. var result = oldPush.apply(array, items);
  70107. _this._markAllSubMeshesAsTexturesDirty();
  70108. return result;
  70109. };
  70110. var oldSplice = array.splice;
  70111. array.splice = function (index, deleteCount) {
  70112. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70113. _this._markAllSubMeshesAsTexturesDirty();
  70114. return deleted;
  70115. };
  70116. };
  70117. // Properties
  70118. MultiMaterial.prototype.getSubMaterial = function (index) {
  70119. if (index < 0 || index >= this.subMaterials.length) {
  70120. return this.getScene().defaultMaterial;
  70121. }
  70122. return this.subMaterials[index];
  70123. };
  70124. MultiMaterial.prototype.getActiveTextures = function () {
  70125. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70126. if (subMaterial) {
  70127. return subMaterial.getActiveTextures();
  70128. }
  70129. else {
  70130. return [];
  70131. }
  70132. }));
  70133. var _a;
  70134. };
  70135. // Methods
  70136. MultiMaterial.prototype.getClassName = function () {
  70137. return "MultiMaterial";
  70138. };
  70139. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70140. for (var index = 0; index < this.subMaterials.length; index++) {
  70141. var subMaterial = this.subMaterials[index];
  70142. if (subMaterial) {
  70143. if (subMaterial.storeEffectOnSubMeshes) {
  70144. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70145. return false;
  70146. }
  70147. continue;
  70148. }
  70149. if (!subMaterial.isReady(mesh)) {
  70150. return false;
  70151. }
  70152. }
  70153. }
  70154. return true;
  70155. };
  70156. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70157. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70158. for (var index = 0; index < this.subMaterials.length; index++) {
  70159. var subMaterial = null;
  70160. var current = this.subMaterials[index];
  70161. if (cloneChildren && current) {
  70162. subMaterial = current.clone(name + "-" + current.name);
  70163. }
  70164. else {
  70165. subMaterial = this.subMaterials[index];
  70166. }
  70167. newMultiMaterial.subMaterials.push(subMaterial);
  70168. }
  70169. return newMultiMaterial;
  70170. };
  70171. MultiMaterial.prototype.serialize = function () {
  70172. var serializationObject = {};
  70173. serializationObject.name = this.name;
  70174. serializationObject.id = this.id;
  70175. if (BABYLON.Tags) {
  70176. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70177. }
  70178. serializationObject.materials = [];
  70179. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70180. var subMat = this.subMaterials[matIndex];
  70181. if (subMat) {
  70182. serializationObject.materials.push(subMat.id);
  70183. }
  70184. else {
  70185. serializationObject.materials.push(null);
  70186. }
  70187. }
  70188. return serializationObject;
  70189. };
  70190. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70191. var scene = this.getScene();
  70192. if (!scene) {
  70193. return;
  70194. }
  70195. var index = scene.multiMaterials.indexOf(this);
  70196. if (index >= 0) {
  70197. scene.multiMaterials.splice(index, 1);
  70198. }
  70199. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70200. };
  70201. return MultiMaterial;
  70202. }(BABYLON.Material));
  70203. BABYLON.MultiMaterial = MultiMaterial;
  70204. })(BABYLON || (BABYLON = {}));
  70205. //# sourceMappingURL=babylon.multiMaterial.js.map
  70206. var BABYLON;
  70207. (function (BABYLON) {
  70208. var FreeCameraTouchInput = /** @class */ (function () {
  70209. function FreeCameraTouchInput() {
  70210. this._offsetX = null;
  70211. this._offsetY = null;
  70212. this._pointerPressed = new Array();
  70213. this.touchAngularSensibility = 200000.0;
  70214. this.touchMoveSensibility = 250.0;
  70215. }
  70216. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70217. var _this = this;
  70218. var previousPosition = null;
  70219. if (this._pointerInput === undefined) {
  70220. this._onLostFocus = function (evt) {
  70221. _this._offsetX = null;
  70222. _this._offsetY = null;
  70223. };
  70224. this._pointerInput = function (p, s) {
  70225. var evt = p.event;
  70226. if (evt.pointerType === "mouse") {
  70227. return;
  70228. }
  70229. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70230. if (!noPreventDefault) {
  70231. evt.preventDefault();
  70232. }
  70233. _this._pointerPressed.push(evt.pointerId);
  70234. if (_this._pointerPressed.length !== 1) {
  70235. return;
  70236. }
  70237. previousPosition = {
  70238. x: evt.clientX,
  70239. y: evt.clientY
  70240. };
  70241. }
  70242. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70243. if (!noPreventDefault) {
  70244. evt.preventDefault();
  70245. }
  70246. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70247. if (index === -1) {
  70248. return;
  70249. }
  70250. _this._pointerPressed.splice(index, 1);
  70251. if (index != 0) {
  70252. return;
  70253. }
  70254. previousPosition = null;
  70255. _this._offsetX = null;
  70256. _this._offsetY = null;
  70257. }
  70258. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70259. if (!noPreventDefault) {
  70260. evt.preventDefault();
  70261. }
  70262. if (!previousPosition) {
  70263. return;
  70264. }
  70265. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70266. if (index != 0) {
  70267. return;
  70268. }
  70269. _this._offsetX = evt.clientX - previousPosition.x;
  70270. _this._offsetY = -(evt.clientY - previousPosition.y);
  70271. }
  70272. };
  70273. }
  70274. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70275. if (this._onLostFocus) {
  70276. element.addEventListener("blur", this._onLostFocus);
  70277. }
  70278. };
  70279. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70280. if (this._pointerInput && element) {
  70281. if (this._observer) {
  70282. this.camera.getScene().onPointerObservable.remove(this._observer);
  70283. this._observer = null;
  70284. }
  70285. if (this._onLostFocus) {
  70286. element.removeEventListener("blur", this._onLostFocus);
  70287. this._onLostFocus = null;
  70288. }
  70289. this._pointerPressed = [];
  70290. this._offsetX = null;
  70291. this._offsetY = null;
  70292. }
  70293. };
  70294. FreeCameraTouchInput.prototype.checkInputs = function () {
  70295. if (this._offsetX && this._offsetY) {
  70296. var camera = this.camera;
  70297. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70298. if (this._pointerPressed.length > 1) {
  70299. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70300. }
  70301. else {
  70302. var speed = camera._computeLocalCameraSpeed();
  70303. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70304. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70305. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70306. }
  70307. }
  70308. };
  70309. FreeCameraTouchInput.prototype.getClassName = function () {
  70310. return "FreeCameraTouchInput";
  70311. };
  70312. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70313. return "touch";
  70314. };
  70315. __decorate([
  70316. BABYLON.serialize()
  70317. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70318. __decorate([
  70319. BABYLON.serialize()
  70320. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70321. return FreeCameraTouchInput;
  70322. }());
  70323. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70324. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70325. })(BABYLON || (BABYLON = {}));
  70326. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70327. var BABYLON;
  70328. (function (BABYLON) {
  70329. // We're mainly based on the logic defined into the FreeCamera code
  70330. var TouchCamera = /** @class */ (function (_super) {
  70331. __extends(TouchCamera, _super);
  70332. //-- end properties for backward compatibility for inputs
  70333. function TouchCamera(name, position, scene) {
  70334. var _this = _super.call(this, name, position, scene) || this;
  70335. _this.inputs.addTouch();
  70336. _this._setupInputs();
  70337. return _this;
  70338. }
  70339. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70340. //-- Begin properties for backward compatibility for inputs
  70341. get: function () {
  70342. var touch = this.inputs.attached["touch"];
  70343. if (touch)
  70344. return touch.touchAngularSensibility;
  70345. return 0;
  70346. },
  70347. set: function (value) {
  70348. var touch = this.inputs.attached["touch"];
  70349. if (touch)
  70350. touch.touchAngularSensibility = value;
  70351. },
  70352. enumerable: true,
  70353. configurable: true
  70354. });
  70355. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70356. get: function () {
  70357. var touch = this.inputs.attached["touch"];
  70358. if (touch)
  70359. return touch.touchMoveSensibility;
  70360. return 0;
  70361. },
  70362. set: function (value) {
  70363. var touch = this.inputs.attached["touch"];
  70364. if (touch)
  70365. touch.touchMoveSensibility = value;
  70366. },
  70367. enumerable: true,
  70368. configurable: true
  70369. });
  70370. TouchCamera.prototype.getClassName = function () {
  70371. return "TouchCamera";
  70372. };
  70373. TouchCamera.prototype._setupInputs = function () {
  70374. var mouse = this.inputs.attached["mouse"];
  70375. if (mouse) {
  70376. mouse.touchEnabled = false;
  70377. }
  70378. };
  70379. return TouchCamera;
  70380. }(BABYLON.FreeCamera));
  70381. BABYLON.TouchCamera = TouchCamera;
  70382. })(BABYLON || (BABYLON = {}));
  70383. //# sourceMappingURL=babylon.touchCamera.js.map
  70384. var BABYLON;
  70385. (function (BABYLON) {
  70386. var ProceduralTexture = /** @class */ (function (_super) {
  70387. __extends(ProceduralTexture, _super);
  70388. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70389. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70390. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70391. if (isCube === void 0) { isCube = false; }
  70392. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70393. _this.isCube = isCube;
  70394. _this.isEnabled = true;
  70395. _this._currentRefreshId = -1;
  70396. _this._refreshRate = 1;
  70397. _this._vertexBuffers = {};
  70398. _this._uniforms = new Array();
  70399. _this._samplers = new Array();
  70400. _this._textures = {};
  70401. _this._floats = {};
  70402. _this._floatsArrays = {};
  70403. _this._colors3 = {};
  70404. _this._colors4 = {};
  70405. _this._vectors2 = {};
  70406. _this._vectors3 = {};
  70407. _this._matrices = {};
  70408. _this._fallbackTextureUsed = false;
  70409. scene.proceduralTextures.push(_this);
  70410. _this._engine = scene.getEngine();
  70411. _this.name = name;
  70412. _this.isRenderTarget = true;
  70413. _this._size = size;
  70414. _this._generateMipMaps = generateMipMaps;
  70415. _this.setFragment(fragment);
  70416. _this._fallbackTexture = fallbackTexture;
  70417. if (isCube) {
  70418. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70419. _this.setFloat("face", 0);
  70420. }
  70421. else {
  70422. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70423. }
  70424. // VBO
  70425. var vertices = [];
  70426. vertices.push(1, 1);
  70427. vertices.push(-1, 1);
  70428. vertices.push(-1, -1);
  70429. vertices.push(1, -1);
  70430. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70431. _this._createIndexBuffer();
  70432. return _this;
  70433. }
  70434. ProceduralTexture.prototype._createIndexBuffer = function () {
  70435. var engine = this._engine;
  70436. // Indices
  70437. var indices = [];
  70438. indices.push(0);
  70439. indices.push(1);
  70440. indices.push(2);
  70441. indices.push(0);
  70442. indices.push(2);
  70443. indices.push(3);
  70444. this._indexBuffer = engine.createIndexBuffer(indices);
  70445. };
  70446. ProceduralTexture.prototype._rebuild = function () {
  70447. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70448. if (vb) {
  70449. vb._rebuild();
  70450. }
  70451. this._createIndexBuffer();
  70452. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70453. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70454. }
  70455. };
  70456. ProceduralTexture.prototype.reset = function () {
  70457. if (this._effect === undefined) {
  70458. return;
  70459. }
  70460. var engine = this._engine;
  70461. engine._releaseEffect(this._effect);
  70462. };
  70463. ProceduralTexture.prototype.isReady = function () {
  70464. var _this = this;
  70465. var engine = this._engine;
  70466. var shaders;
  70467. if (!this._fragment) {
  70468. return false;
  70469. }
  70470. if (this._fallbackTextureUsed) {
  70471. return true;
  70472. }
  70473. if (this._fragment.fragmentElement !== undefined) {
  70474. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70475. }
  70476. else {
  70477. shaders = { vertex: "procedural", fragment: this._fragment };
  70478. }
  70479. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70480. _this.releaseInternalTexture();
  70481. if (_this._fallbackTexture) {
  70482. _this._texture = _this._fallbackTexture._texture;
  70483. if (_this._texture) {
  70484. _this._texture.incrementReferences();
  70485. }
  70486. }
  70487. _this._fallbackTextureUsed = true;
  70488. });
  70489. return this._effect.isReady();
  70490. };
  70491. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70492. this._currentRefreshId = -1;
  70493. };
  70494. ProceduralTexture.prototype.setFragment = function (fragment) {
  70495. this._fragment = fragment;
  70496. };
  70497. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70498. get: function () {
  70499. return this._refreshRate;
  70500. },
  70501. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70502. set: function (value) {
  70503. this._refreshRate = value;
  70504. this.resetRefreshCounter();
  70505. },
  70506. enumerable: true,
  70507. configurable: true
  70508. });
  70509. ProceduralTexture.prototype._shouldRender = function () {
  70510. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70511. return false;
  70512. }
  70513. if (this._fallbackTextureUsed) {
  70514. return false;
  70515. }
  70516. if (this._currentRefreshId === -1) { // At least render once
  70517. this._currentRefreshId = 1;
  70518. return true;
  70519. }
  70520. if (this.refreshRate === this._currentRefreshId) {
  70521. this._currentRefreshId = 1;
  70522. return true;
  70523. }
  70524. this._currentRefreshId++;
  70525. return false;
  70526. };
  70527. ProceduralTexture.prototype.getRenderSize = function () {
  70528. return this._size;
  70529. };
  70530. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70531. if (this._fallbackTextureUsed) {
  70532. return;
  70533. }
  70534. this.releaseInternalTexture();
  70535. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70536. // Update properties
  70537. this._size = size;
  70538. this._generateMipMaps = generateMipMaps;
  70539. };
  70540. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70541. if (this._uniforms.indexOf(uniformName) === -1) {
  70542. this._uniforms.push(uniformName);
  70543. }
  70544. };
  70545. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70546. if (this._samplers.indexOf(name) === -1) {
  70547. this._samplers.push(name);
  70548. }
  70549. this._textures[name] = texture;
  70550. return this;
  70551. };
  70552. ProceduralTexture.prototype.setFloat = function (name, value) {
  70553. this._checkUniform(name);
  70554. this._floats[name] = value;
  70555. return this;
  70556. };
  70557. ProceduralTexture.prototype.setFloats = function (name, value) {
  70558. this._checkUniform(name);
  70559. this._floatsArrays[name] = value;
  70560. return this;
  70561. };
  70562. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70563. this._checkUniform(name);
  70564. this._colors3[name] = value;
  70565. return this;
  70566. };
  70567. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70568. this._checkUniform(name);
  70569. this._colors4[name] = value;
  70570. return this;
  70571. };
  70572. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70573. this._checkUniform(name);
  70574. this._vectors2[name] = value;
  70575. return this;
  70576. };
  70577. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70578. this._checkUniform(name);
  70579. this._vectors3[name] = value;
  70580. return this;
  70581. };
  70582. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70583. this._checkUniform(name);
  70584. this._matrices[name] = value;
  70585. return this;
  70586. };
  70587. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70588. var scene = this.getScene();
  70589. if (!scene) {
  70590. return;
  70591. }
  70592. var engine = this._engine;
  70593. // Render
  70594. engine.enableEffect(this._effect);
  70595. engine.setState(false);
  70596. // Texture
  70597. for (var name in this._textures) {
  70598. this._effect.setTexture(name, this._textures[name]);
  70599. }
  70600. // Float
  70601. for (name in this._floats) {
  70602. this._effect.setFloat(name, this._floats[name]);
  70603. }
  70604. // Floats
  70605. for (name in this._floatsArrays) {
  70606. this._effect.setArray(name, this._floatsArrays[name]);
  70607. }
  70608. // Color3
  70609. for (name in this._colors3) {
  70610. this._effect.setColor3(name, this._colors3[name]);
  70611. }
  70612. // Color4
  70613. for (name in this._colors4) {
  70614. var color = this._colors4[name];
  70615. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70616. }
  70617. // Vector2
  70618. for (name in this._vectors2) {
  70619. this._effect.setVector2(name, this._vectors2[name]);
  70620. }
  70621. // Vector3
  70622. for (name in this._vectors3) {
  70623. this._effect.setVector3(name, this._vectors3[name]);
  70624. }
  70625. // Matrix
  70626. for (name in this._matrices) {
  70627. this._effect.setMatrix(name, this._matrices[name]);
  70628. }
  70629. if (!this._texture) {
  70630. return;
  70631. }
  70632. if (this.isCube) {
  70633. for (var face = 0; face < 6; face++) {
  70634. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70635. // VBOs
  70636. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70637. this._effect.setFloat("face", face);
  70638. // Clear
  70639. engine.clear(scene.clearColor, true, true, true);
  70640. // Draw order
  70641. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70642. // Mipmaps
  70643. if (face === 5) {
  70644. engine.generateMipMapsForCubemap(this._texture);
  70645. }
  70646. }
  70647. }
  70648. else {
  70649. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70650. // VBOs
  70651. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70652. // Clear
  70653. engine.clear(scene.clearColor, true, true, true);
  70654. // Draw order
  70655. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70656. }
  70657. // Unbind
  70658. engine.unBindFramebuffer(this._texture, this.isCube);
  70659. if (this.onGenerated) {
  70660. this.onGenerated();
  70661. }
  70662. };
  70663. ProceduralTexture.prototype.clone = function () {
  70664. var textureSize = this.getSize();
  70665. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70666. // Base texture
  70667. newTexture.hasAlpha = this.hasAlpha;
  70668. newTexture.level = this.level;
  70669. // RenderTarget Texture
  70670. newTexture.coordinatesMode = this.coordinatesMode;
  70671. return newTexture;
  70672. };
  70673. ProceduralTexture.prototype.dispose = function () {
  70674. var scene = this.getScene();
  70675. if (!scene) {
  70676. return;
  70677. }
  70678. var index = scene.proceduralTextures.indexOf(this);
  70679. if (index >= 0) {
  70680. scene.proceduralTextures.splice(index, 1);
  70681. }
  70682. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70683. if (vertexBuffer) {
  70684. vertexBuffer.dispose();
  70685. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70686. }
  70687. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70688. this._indexBuffer = null;
  70689. }
  70690. _super.prototype.dispose.call(this);
  70691. };
  70692. __decorate([
  70693. BABYLON.serialize()
  70694. ], ProceduralTexture.prototype, "_size", void 0);
  70695. __decorate([
  70696. BABYLON.serialize()
  70697. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70698. __decorate([
  70699. BABYLON.serialize()
  70700. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70701. __decorate([
  70702. BABYLON.serialize()
  70703. ], ProceduralTexture.prototype, "refreshRate", null);
  70704. return ProceduralTexture;
  70705. }(BABYLON.Texture));
  70706. BABYLON.ProceduralTexture = ProceduralTexture;
  70707. })(BABYLON || (BABYLON = {}));
  70708. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70709. var BABYLON;
  70710. (function (BABYLON) {
  70711. var CustomProceduralTexture = /** @class */ (function (_super) {
  70712. __extends(CustomProceduralTexture, _super);
  70713. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70714. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70715. _this._animate = true;
  70716. _this._time = 0;
  70717. _this._texturePath = texturePath;
  70718. //Try to load json
  70719. _this.loadJson(texturePath);
  70720. _this.refreshRate = 1;
  70721. return _this;
  70722. }
  70723. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70724. var _this = this;
  70725. var noConfigFile = function () {
  70726. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70727. try {
  70728. _this.setFragment(_this._texturePath);
  70729. }
  70730. catch (ex) {
  70731. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70732. }
  70733. };
  70734. var configFileUrl = jsonUrl + "/config.json";
  70735. var xhr = new XMLHttpRequest();
  70736. xhr.open("GET", configFileUrl, true);
  70737. xhr.addEventListener("load", function () {
  70738. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70739. try {
  70740. _this._config = JSON.parse(xhr.response);
  70741. _this.updateShaderUniforms();
  70742. _this.updateTextures();
  70743. _this.setFragment(_this._texturePath + "/custom");
  70744. _this._animate = _this._config.animate;
  70745. _this.refreshRate = _this._config.refreshrate;
  70746. }
  70747. catch (ex) {
  70748. noConfigFile();
  70749. }
  70750. }
  70751. else {
  70752. noConfigFile();
  70753. }
  70754. }, false);
  70755. xhr.addEventListener("error", function () {
  70756. noConfigFile();
  70757. }, false);
  70758. try {
  70759. xhr.send();
  70760. }
  70761. catch (ex) {
  70762. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70763. }
  70764. };
  70765. CustomProceduralTexture.prototype.isReady = function () {
  70766. if (!_super.prototype.isReady.call(this)) {
  70767. return false;
  70768. }
  70769. for (var name in this._textures) {
  70770. var texture = this._textures[name];
  70771. if (!texture.isReady()) {
  70772. return false;
  70773. }
  70774. }
  70775. return true;
  70776. };
  70777. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70778. var scene = this.getScene();
  70779. if (this._animate && scene) {
  70780. this._time += scene.getAnimationRatio() * 0.03;
  70781. this.updateShaderUniforms();
  70782. }
  70783. _super.prototype.render.call(this, useCameraPostProcess);
  70784. };
  70785. CustomProceduralTexture.prototype.updateTextures = function () {
  70786. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70787. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70788. }
  70789. };
  70790. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70791. if (this._config) {
  70792. for (var j = 0; j < this._config.uniforms.length; j++) {
  70793. var uniform = this._config.uniforms[j];
  70794. switch (uniform.type) {
  70795. case "float":
  70796. this.setFloat(uniform.name, uniform.value);
  70797. break;
  70798. case "color3":
  70799. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70800. break;
  70801. case "color4":
  70802. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70803. break;
  70804. case "vector2":
  70805. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70806. break;
  70807. case "vector3":
  70808. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70809. break;
  70810. }
  70811. }
  70812. }
  70813. this.setFloat("time", this._time);
  70814. };
  70815. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70816. get: function () {
  70817. return this._animate;
  70818. },
  70819. set: function (value) {
  70820. this._animate = value;
  70821. },
  70822. enumerable: true,
  70823. configurable: true
  70824. });
  70825. return CustomProceduralTexture;
  70826. }(BABYLON.ProceduralTexture));
  70827. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70828. })(BABYLON || (BABYLON = {}));
  70829. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70830. var BABYLON;
  70831. (function (BABYLON) {
  70832. var FreeCameraGamepadInput = /** @class */ (function () {
  70833. function FreeCameraGamepadInput() {
  70834. this.gamepadAngularSensibility = 200;
  70835. this.gamepadMoveSensibility = 40;
  70836. // private members
  70837. this._cameraTransform = BABYLON.Matrix.Identity();
  70838. this._deltaTransform = BABYLON.Vector3.Zero();
  70839. this._vector3 = BABYLON.Vector3.Zero();
  70840. this._vector2 = BABYLON.Vector2.Zero();
  70841. }
  70842. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70843. var _this = this;
  70844. var manager = this.camera.getScene().gamepadManager;
  70845. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70846. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70847. // prioritize XBOX gamepads.
  70848. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70849. _this.gamepad = gamepad;
  70850. }
  70851. }
  70852. });
  70853. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70854. if (_this.gamepad === gamepad) {
  70855. _this.gamepad = null;
  70856. }
  70857. });
  70858. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70859. };
  70860. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70861. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70862. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70863. this.gamepad = null;
  70864. };
  70865. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70866. if (this.gamepad && this.gamepad.leftStick) {
  70867. var camera = this.camera;
  70868. var LSValues = this.gamepad.leftStick;
  70869. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70870. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70871. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70872. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70873. var RSValues = this.gamepad.rightStick;
  70874. if (RSValues) {
  70875. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70876. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70877. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70878. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70879. }
  70880. else {
  70881. RSValues = { x: 0, y: 0 };
  70882. }
  70883. if (!camera.rotationQuaternion) {
  70884. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70885. }
  70886. else {
  70887. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70888. }
  70889. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70890. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70891. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70892. camera.cameraDirection.addInPlace(this._deltaTransform);
  70893. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70894. camera.cameraRotation.addInPlace(this._vector2);
  70895. }
  70896. };
  70897. FreeCameraGamepadInput.prototype.getClassName = function () {
  70898. return "FreeCameraGamepadInput";
  70899. };
  70900. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70901. return "gamepad";
  70902. };
  70903. __decorate([
  70904. BABYLON.serialize()
  70905. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70906. __decorate([
  70907. BABYLON.serialize()
  70908. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70909. return FreeCameraGamepadInput;
  70910. }());
  70911. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70912. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70913. })(BABYLON || (BABYLON = {}));
  70914. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70915. var BABYLON;
  70916. (function (BABYLON) {
  70917. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70918. function ArcRotateCameraGamepadInput() {
  70919. this.gamepadRotationSensibility = 80;
  70920. this.gamepadMoveSensibility = 40;
  70921. }
  70922. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70923. var _this = this;
  70924. var manager = this.camera.getScene().gamepadManager;
  70925. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70926. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70927. // prioritize XBOX gamepads.
  70928. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70929. _this.gamepad = gamepad;
  70930. }
  70931. }
  70932. });
  70933. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70934. if (_this.gamepad === gamepad) {
  70935. _this.gamepad = null;
  70936. }
  70937. });
  70938. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70939. };
  70940. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70941. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70942. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70943. this.gamepad = null;
  70944. };
  70945. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70946. if (this.gamepad) {
  70947. var camera = this.camera;
  70948. var RSValues = this.gamepad.rightStick;
  70949. if (RSValues) {
  70950. if (RSValues.x != 0) {
  70951. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70952. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70953. camera.inertialAlphaOffset += normalizedRX;
  70954. }
  70955. }
  70956. if (RSValues.y != 0) {
  70957. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70958. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70959. camera.inertialBetaOffset += normalizedRY;
  70960. }
  70961. }
  70962. }
  70963. var LSValues = this.gamepad.leftStick;
  70964. if (LSValues && LSValues.y != 0) {
  70965. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70966. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70967. this.camera.inertialRadiusOffset -= normalizedLY;
  70968. }
  70969. }
  70970. }
  70971. };
  70972. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70973. return "ArcRotateCameraGamepadInput";
  70974. };
  70975. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70976. return "gamepad";
  70977. };
  70978. __decorate([
  70979. BABYLON.serialize()
  70980. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70981. __decorate([
  70982. BABYLON.serialize()
  70983. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70984. return ArcRotateCameraGamepadInput;
  70985. }());
  70986. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70987. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70988. })(BABYLON || (BABYLON = {}));
  70989. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70990. var BABYLON;
  70991. (function (BABYLON) {
  70992. var GamepadManager = /** @class */ (function () {
  70993. function GamepadManager(_scene) {
  70994. var _this = this;
  70995. this._scene = _scene;
  70996. this._babylonGamepads = [];
  70997. this._oneGamepadConnected = false;
  70998. this._isMonitoring = false;
  70999. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  71000. if (!BABYLON.Tools.IsWindowObjectExist()) {
  71001. this._gamepadEventSupported = false;
  71002. }
  71003. else {
  71004. this._gamepadEventSupported = 'GamepadEvent' in window;
  71005. this._gamepadSupport = (navigator.getGamepads ||
  71006. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  71007. }
  71008. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  71009. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  71010. for (var i in _this._babylonGamepads) {
  71011. var gamepad = _this._babylonGamepads[i];
  71012. if (gamepad && gamepad._isConnected) {
  71013. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  71014. }
  71015. }
  71016. });
  71017. this._onGamepadConnectedEvent = function (evt) {
  71018. var gamepad = evt.gamepad;
  71019. if (gamepad.index in _this._babylonGamepads) {
  71020. if (_this._babylonGamepads[gamepad.index].isConnected) {
  71021. return;
  71022. }
  71023. }
  71024. var newGamepad;
  71025. if (_this._babylonGamepads[gamepad.index]) {
  71026. newGamepad = _this._babylonGamepads[gamepad.index];
  71027. newGamepad.browserGamepad = gamepad;
  71028. newGamepad._isConnected = true;
  71029. }
  71030. else {
  71031. newGamepad = _this._addNewGamepad(gamepad);
  71032. }
  71033. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71034. _this._startMonitoringGamepads();
  71035. };
  71036. this._onGamepadDisconnectedEvent = function (evt) {
  71037. var gamepad = evt.gamepad;
  71038. // Remove the gamepad from the list of gamepads to monitor.
  71039. for (var i in _this._babylonGamepads) {
  71040. if (_this._babylonGamepads[i].index === gamepad.index) {
  71041. var disconnectedGamepad = _this._babylonGamepads[i];
  71042. disconnectedGamepad._isConnected = false;
  71043. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  71044. break;
  71045. }
  71046. }
  71047. };
  71048. if (this._gamepadSupport) {
  71049. //first add already-connected gamepads
  71050. this._updateGamepadObjects();
  71051. if (this._babylonGamepads.length) {
  71052. this._startMonitoringGamepads();
  71053. }
  71054. // Checking if the gamepad connected event is supported (like in Firefox)
  71055. if (this._gamepadEventSupported) {
  71056. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  71057. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  71058. }
  71059. else {
  71060. this._startMonitoringGamepads();
  71061. }
  71062. }
  71063. }
  71064. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  71065. get: function () {
  71066. return this._babylonGamepads;
  71067. },
  71068. enumerable: true,
  71069. configurable: true
  71070. });
  71071. GamepadManager.prototype.getGamepadByType = function (type) {
  71072. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  71073. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  71074. var gamepad = _a[_i];
  71075. if (gamepad && gamepad.type === type) {
  71076. return gamepad;
  71077. }
  71078. }
  71079. return null;
  71080. };
  71081. GamepadManager.prototype.dispose = function () {
  71082. if (this._gamepadEventSupported) {
  71083. if (this._onGamepadConnectedEvent) {
  71084. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71085. }
  71086. if (this._onGamepadDisconnectedEvent) {
  71087. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71088. }
  71089. this._onGamepadConnectedEvent = null;
  71090. this._onGamepadDisconnectedEvent = null;
  71091. }
  71092. this._babylonGamepads.forEach(function (gamepad) {
  71093. gamepad.dispose();
  71094. });
  71095. this.onGamepadConnectedObservable.clear();
  71096. this.onGamepadDisconnectedObservable.clear();
  71097. this._oneGamepadConnected = false;
  71098. this._stopMonitoringGamepads();
  71099. this._babylonGamepads = [];
  71100. };
  71101. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71102. if (!this._oneGamepadConnected) {
  71103. this._oneGamepadConnected = true;
  71104. }
  71105. var newGamepad;
  71106. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71107. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71108. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71109. }
  71110. // if pose is supported, use the (WebVR) pose enabled controller
  71111. else if (gamepad.pose) {
  71112. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71113. }
  71114. else {
  71115. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71116. }
  71117. this._babylonGamepads[newGamepad.index] = newGamepad;
  71118. return newGamepad;
  71119. };
  71120. GamepadManager.prototype._startMonitoringGamepads = function () {
  71121. if (!this._isMonitoring) {
  71122. this._isMonitoring = true;
  71123. //back-comp
  71124. if (!this._scene) {
  71125. this._checkGamepadsStatus();
  71126. }
  71127. }
  71128. };
  71129. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71130. this._isMonitoring = false;
  71131. };
  71132. GamepadManager.prototype._checkGamepadsStatus = function () {
  71133. var _this = this;
  71134. // Hack to be compatible Chrome
  71135. this._updateGamepadObjects();
  71136. for (var i in this._babylonGamepads) {
  71137. var gamepad = this._babylonGamepads[i];
  71138. if (!gamepad || !gamepad.isConnected) {
  71139. continue;
  71140. }
  71141. gamepad.update();
  71142. }
  71143. if (this._isMonitoring && !this._scene) {
  71144. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71145. }
  71146. };
  71147. // This function is called only on Chrome, which does not properly support
  71148. // connection/disconnection events and forces you to recopy again the gamepad object
  71149. GamepadManager.prototype._updateGamepadObjects = function () {
  71150. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71151. for (var i = 0; i < gamepads.length; i++) {
  71152. var gamepad = gamepads[i];
  71153. if (gamepad) {
  71154. if (!this._babylonGamepads[gamepad.index]) {
  71155. var newGamepad = this._addNewGamepad(gamepad);
  71156. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71157. }
  71158. else {
  71159. // Forced to copy again this object for Chrome for unknown reason
  71160. this._babylonGamepads[i].browserGamepad = gamepad;
  71161. if (!this._babylonGamepads[i].isConnected) {
  71162. this._babylonGamepads[i]._isConnected = true;
  71163. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71164. }
  71165. }
  71166. }
  71167. }
  71168. };
  71169. return GamepadManager;
  71170. }());
  71171. BABYLON.GamepadManager = GamepadManager;
  71172. })(BABYLON || (BABYLON = {}));
  71173. //# sourceMappingURL=babylon.gamepadManager.js.map
  71174. var BABYLON;
  71175. (function (BABYLON) {
  71176. var StickValues = /** @class */ (function () {
  71177. function StickValues(x, y) {
  71178. this.x = x;
  71179. this.y = y;
  71180. }
  71181. return StickValues;
  71182. }());
  71183. BABYLON.StickValues = StickValues;
  71184. var Gamepad = /** @class */ (function () {
  71185. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71186. if (leftStickX === void 0) { leftStickX = 0; }
  71187. if (leftStickY === void 0) { leftStickY = 1; }
  71188. if (rightStickX === void 0) { rightStickX = 2; }
  71189. if (rightStickY === void 0) { rightStickY = 3; }
  71190. this.id = id;
  71191. this.index = index;
  71192. this.browserGamepad = browserGamepad;
  71193. this._isConnected = true;
  71194. this._invertLeftStickY = false;
  71195. this.type = Gamepad.GAMEPAD;
  71196. this._leftStickAxisX = leftStickX;
  71197. this._leftStickAxisY = leftStickY;
  71198. this._rightStickAxisX = rightStickX;
  71199. this._rightStickAxisY = rightStickY;
  71200. if (this.browserGamepad.axes.length >= 2) {
  71201. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71202. }
  71203. if (this.browserGamepad.axes.length >= 4) {
  71204. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71205. }
  71206. }
  71207. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71208. get: function () {
  71209. return this._isConnected;
  71210. },
  71211. enumerable: true,
  71212. configurable: true
  71213. });
  71214. Gamepad.prototype.onleftstickchanged = function (callback) {
  71215. this._onleftstickchanged = callback;
  71216. };
  71217. Gamepad.prototype.onrightstickchanged = function (callback) {
  71218. this._onrightstickchanged = callback;
  71219. };
  71220. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71221. get: function () {
  71222. return this._leftStick;
  71223. },
  71224. set: function (newValues) {
  71225. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71226. this._onleftstickchanged(newValues);
  71227. }
  71228. this._leftStick = newValues;
  71229. },
  71230. enumerable: true,
  71231. configurable: true
  71232. });
  71233. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71234. get: function () {
  71235. return this._rightStick;
  71236. },
  71237. set: function (newValues) {
  71238. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71239. this._onrightstickchanged(newValues);
  71240. }
  71241. this._rightStick = newValues;
  71242. },
  71243. enumerable: true,
  71244. configurable: true
  71245. });
  71246. Gamepad.prototype.update = function () {
  71247. if (this._leftStick) {
  71248. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71249. if (this._invertLeftStickY) {
  71250. this.leftStick.y *= -1;
  71251. }
  71252. }
  71253. if (this._rightStick) {
  71254. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71255. }
  71256. };
  71257. Gamepad.prototype.dispose = function () {
  71258. };
  71259. Gamepad.GAMEPAD = 0;
  71260. Gamepad.GENERIC = 1;
  71261. Gamepad.XBOX = 2;
  71262. Gamepad.POSE_ENABLED = 3;
  71263. return Gamepad;
  71264. }());
  71265. BABYLON.Gamepad = Gamepad;
  71266. var GenericPad = /** @class */ (function (_super) {
  71267. __extends(GenericPad, _super);
  71268. function GenericPad(id, index, browserGamepad) {
  71269. var _this = _super.call(this, id, index, browserGamepad) || this;
  71270. _this.onButtonDownObservable = new BABYLON.Observable();
  71271. _this.onButtonUpObservable = new BABYLON.Observable();
  71272. _this.type = Gamepad.GENERIC;
  71273. _this._buttons = new Array(browserGamepad.buttons.length);
  71274. return _this;
  71275. }
  71276. GenericPad.prototype.onbuttondown = function (callback) {
  71277. this._onbuttondown = callback;
  71278. };
  71279. GenericPad.prototype.onbuttonup = function (callback) {
  71280. this._onbuttonup = callback;
  71281. };
  71282. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71283. if (newValue !== currentValue) {
  71284. if (newValue === 1) {
  71285. if (this._onbuttondown) {
  71286. this._onbuttondown(buttonIndex);
  71287. }
  71288. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71289. }
  71290. if (newValue === 0) {
  71291. if (this._onbuttonup) {
  71292. this._onbuttonup(buttonIndex);
  71293. }
  71294. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71295. }
  71296. }
  71297. return newValue;
  71298. };
  71299. GenericPad.prototype.update = function () {
  71300. _super.prototype.update.call(this);
  71301. for (var index = 0; index < this._buttons.length; index++) {
  71302. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71303. }
  71304. };
  71305. GenericPad.prototype.dispose = function () {
  71306. _super.prototype.dispose.call(this);
  71307. this.onButtonDownObservable.clear();
  71308. this.onButtonUpObservable.clear();
  71309. };
  71310. return GenericPad;
  71311. }(Gamepad));
  71312. BABYLON.GenericPad = GenericPad;
  71313. })(BABYLON || (BABYLON = {}));
  71314. //# sourceMappingURL=babylon.gamepad.js.map
  71315. var BABYLON;
  71316. (function (BABYLON) {
  71317. /**
  71318. * Defines supported buttons for XBox360 compatible gamepads
  71319. */
  71320. var Xbox360Button;
  71321. (function (Xbox360Button) {
  71322. /** A */
  71323. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71324. /** B */
  71325. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71326. /** X */
  71327. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71328. /** Y */
  71329. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71330. /** Start */
  71331. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71332. /** Back */
  71333. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71334. /** Left button */
  71335. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71336. /** Right button */
  71337. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71338. /** Left stick */
  71339. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71340. /** Right stick */
  71341. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71342. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71343. /** Defines values for XBox360 DPad */
  71344. var Xbox360Dpad;
  71345. (function (Xbox360Dpad) {
  71346. /** Up */
  71347. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71348. /** Down */
  71349. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71350. /** Left */
  71351. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71352. /** Right */
  71353. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71354. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71355. /**
  71356. * Defines a XBox360 gamepad
  71357. */
  71358. var Xbox360Pad = /** @class */ (function (_super) {
  71359. __extends(Xbox360Pad, _super);
  71360. /**
  71361. * Creates a new XBox360 gamepad object
  71362. * @param id defines the id of this gamepad
  71363. * @param index defines its index
  71364. * @param gamepad defines the internal HTML gamepad object
  71365. * @param xboxOne defines if it is a XBox One gamepad
  71366. */
  71367. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71368. if (xboxOne === void 0) { xboxOne = false; }
  71369. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71370. _this._leftTrigger = 0;
  71371. _this._rightTrigger = 0;
  71372. /** Observable raised when a button is pressed */
  71373. _this.onButtonDownObservable = new BABYLON.Observable();
  71374. /** Observable raised when a button is released */
  71375. _this.onButtonUpObservable = new BABYLON.Observable();
  71376. /** Observable raised when a pad is pressed */
  71377. _this.onPadDownObservable = new BABYLON.Observable();
  71378. /** Observable raised when a pad is released */
  71379. _this.onPadUpObservable = new BABYLON.Observable();
  71380. _this._buttonA = 0;
  71381. _this._buttonB = 0;
  71382. _this._buttonX = 0;
  71383. _this._buttonY = 0;
  71384. _this._buttonBack = 0;
  71385. _this._buttonStart = 0;
  71386. _this._buttonLB = 0;
  71387. _this._buttonRB = 0;
  71388. _this._buttonLeftStick = 0;
  71389. _this._buttonRightStick = 0;
  71390. _this._dPadUp = 0;
  71391. _this._dPadDown = 0;
  71392. _this._dPadLeft = 0;
  71393. _this._dPadRight = 0;
  71394. _this._isXboxOnePad = false;
  71395. _this.type = BABYLON.Gamepad.XBOX;
  71396. _this._isXboxOnePad = xboxOne;
  71397. return _this;
  71398. }
  71399. /**
  71400. * Defines the callback to call when left trigger is pressed
  71401. * @param callback defines the callback to use
  71402. */
  71403. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71404. this._onlefttriggerchanged = callback;
  71405. };
  71406. /**
  71407. * Defines the callback to call when right trigger is pressed
  71408. * @param callback defines the callback to use
  71409. */
  71410. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71411. this._onrighttriggerchanged = callback;
  71412. };
  71413. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71414. /**
  71415. * Gets or sets left trigger value
  71416. */
  71417. get: function () {
  71418. return this._leftTrigger;
  71419. },
  71420. set: function (newValue) {
  71421. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71422. this._onlefttriggerchanged(newValue);
  71423. }
  71424. this._leftTrigger = newValue;
  71425. },
  71426. enumerable: true,
  71427. configurable: true
  71428. });
  71429. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71430. /**
  71431. * Gets or sets right trigger value
  71432. */
  71433. get: function () {
  71434. return this._rightTrigger;
  71435. },
  71436. set: function (newValue) {
  71437. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71438. this._onrighttriggerchanged(newValue);
  71439. }
  71440. this._rightTrigger = newValue;
  71441. },
  71442. enumerable: true,
  71443. configurable: true
  71444. });
  71445. /**
  71446. * Defines the callback to call when a button is pressed
  71447. * @param callback defines the callback to use
  71448. */
  71449. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71450. this._onbuttondown = callback;
  71451. };
  71452. /**
  71453. * Defines the callback to call when a button is released
  71454. * @param callback defines the callback to use
  71455. */
  71456. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71457. this._onbuttonup = callback;
  71458. };
  71459. /**
  71460. * Defines the callback to call when a pad is pressed
  71461. * @param callback defines the callback to use
  71462. */
  71463. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71464. this._ondpaddown = callback;
  71465. };
  71466. /**
  71467. * Defines the callback to call when a pad is released
  71468. * @param callback defines the callback to use
  71469. */
  71470. Xbox360Pad.prototype.ondpadup = function (callback) {
  71471. this._ondpadup = callback;
  71472. };
  71473. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71474. if (newValue !== currentValue) {
  71475. if (newValue === 1) {
  71476. if (this._onbuttondown) {
  71477. this._onbuttondown(buttonType);
  71478. }
  71479. this.onButtonDownObservable.notifyObservers(buttonType);
  71480. }
  71481. if (newValue === 0) {
  71482. if (this._onbuttonup) {
  71483. this._onbuttonup(buttonType);
  71484. }
  71485. this.onButtonUpObservable.notifyObservers(buttonType);
  71486. }
  71487. }
  71488. return newValue;
  71489. };
  71490. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71491. if (newValue !== currentValue) {
  71492. if (newValue === 1) {
  71493. if (this._ondpaddown) {
  71494. this._ondpaddown(buttonType);
  71495. }
  71496. this.onPadDownObservable.notifyObservers(buttonType);
  71497. }
  71498. if (newValue === 0) {
  71499. if (this._ondpadup) {
  71500. this._ondpadup(buttonType);
  71501. }
  71502. this.onPadUpObservable.notifyObservers(buttonType);
  71503. }
  71504. }
  71505. return newValue;
  71506. };
  71507. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71508. /** Gets or sets value of A button */
  71509. get: function () {
  71510. return this._buttonA;
  71511. },
  71512. set: function (value) {
  71513. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71514. },
  71515. enumerable: true,
  71516. configurable: true
  71517. });
  71518. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71519. /** Gets or sets value of B button */
  71520. get: function () {
  71521. return this._buttonB;
  71522. },
  71523. set: function (value) {
  71524. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71525. },
  71526. enumerable: true,
  71527. configurable: true
  71528. });
  71529. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71530. /** Gets or sets value of X button */
  71531. get: function () {
  71532. return this._buttonX;
  71533. },
  71534. set: function (value) {
  71535. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71536. },
  71537. enumerable: true,
  71538. configurable: true
  71539. });
  71540. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71541. /** Gets or sets value of Y button */
  71542. get: function () {
  71543. return this._buttonY;
  71544. },
  71545. set: function (value) {
  71546. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71547. },
  71548. enumerable: true,
  71549. configurable: true
  71550. });
  71551. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71552. /** Gets or sets value of Start button */
  71553. get: function () {
  71554. return this._buttonStart;
  71555. },
  71556. set: function (value) {
  71557. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71558. },
  71559. enumerable: true,
  71560. configurable: true
  71561. });
  71562. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71563. /** Gets or sets value of Back button */
  71564. get: function () {
  71565. return this._buttonBack;
  71566. },
  71567. set: function (value) {
  71568. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71569. },
  71570. enumerable: true,
  71571. configurable: true
  71572. });
  71573. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71574. /** Gets or sets value of Left button */
  71575. get: function () {
  71576. return this._buttonLB;
  71577. },
  71578. set: function (value) {
  71579. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71580. },
  71581. enumerable: true,
  71582. configurable: true
  71583. });
  71584. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71585. /** Gets or sets value of Right button */
  71586. get: function () {
  71587. return this._buttonRB;
  71588. },
  71589. set: function (value) {
  71590. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71591. },
  71592. enumerable: true,
  71593. configurable: true
  71594. });
  71595. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71596. /** Gets or sets value of left stick */
  71597. get: function () {
  71598. return this._buttonLeftStick;
  71599. },
  71600. set: function (value) {
  71601. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71602. },
  71603. enumerable: true,
  71604. configurable: true
  71605. });
  71606. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71607. /** Gets or sets value of right stick */
  71608. get: function () {
  71609. return this._buttonRightStick;
  71610. },
  71611. set: function (value) {
  71612. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71613. },
  71614. enumerable: true,
  71615. configurable: true
  71616. });
  71617. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71618. /** Gets or sets value of DPad up */
  71619. get: function () {
  71620. return this._dPadUp;
  71621. },
  71622. set: function (value) {
  71623. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71624. },
  71625. enumerable: true,
  71626. configurable: true
  71627. });
  71628. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71629. /** Gets or sets value of DPad down */
  71630. get: function () {
  71631. return this._dPadDown;
  71632. },
  71633. set: function (value) {
  71634. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71635. },
  71636. enumerable: true,
  71637. configurable: true
  71638. });
  71639. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71640. /** Gets or sets value of DPad left */
  71641. get: function () {
  71642. return this._dPadLeft;
  71643. },
  71644. set: function (value) {
  71645. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71646. },
  71647. enumerable: true,
  71648. configurable: true
  71649. });
  71650. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71651. /** Gets or sets value of DPad right */
  71652. get: function () {
  71653. return this._dPadRight;
  71654. },
  71655. set: function (value) {
  71656. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71657. },
  71658. enumerable: true,
  71659. configurable: true
  71660. });
  71661. /**
  71662. * Force the gamepad to synchronize with device values
  71663. */
  71664. Xbox360Pad.prototype.update = function () {
  71665. _super.prototype.update.call(this);
  71666. if (this._isXboxOnePad) {
  71667. this.buttonA = this.browserGamepad.buttons[0].value;
  71668. this.buttonB = this.browserGamepad.buttons[1].value;
  71669. this.buttonX = this.browserGamepad.buttons[2].value;
  71670. this.buttonY = this.browserGamepad.buttons[3].value;
  71671. this.buttonLB = this.browserGamepad.buttons[4].value;
  71672. this.buttonRB = this.browserGamepad.buttons[5].value;
  71673. this.leftTrigger = this.browserGamepad.axes[2];
  71674. this.rightTrigger = this.browserGamepad.axes[5];
  71675. this.buttonBack = this.browserGamepad.buttons[9].value;
  71676. this.buttonStart = this.browserGamepad.buttons[8].value;
  71677. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71678. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71679. this.dPadUp = this.browserGamepad.buttons[11].value;
  71680. this.dPadDown = this.browserGamepad.buttons[12].value;
  71681. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71682. this.dPadRight = this.browserGamepad.buttons[14].value;
  71683. }
  71684. else {
  71685. this.buttonA = this.browserGamepad.buttons[0].value;
  71686. this.buttonB = this.browserGamepad.buttons[1].value;
  71687. this.buttonX = this.browserGamepad.buttons[2].value;
  71688. this.buttonY = this.browserGamepad.buttons[3].value;
  71689. this.buttonLB = this.browserGamepad.buttons[4].value;
  71690. this.buttonRB = this.browserGamepad.buttons[5].value;
  71691. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71692. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71693. this.buttonBack = this.browserGamepad.buttons[8].value;
  71694. this.buttonStart = this.browserGamepad.buttons[9].value;
  71695. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71696. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71697. this.dPadUp = this.browserGamepad.buttons[12].value;
  71698. this.dPadDown = this.browserGamepad.buttons[13].value;
  71699. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71700. this.dPadRight = this.browserGamepad.buttons[15].value;
  71701. }
  71702. };
  71703. Xbox360Pad.prototype.dispose = function () {
  71704. _super.prototype.dispose.call(this);
  71705. this.onButtonDownObservable.clear();
  71706. this.onButtonUpObservable.clear();
  71707. this.onPadDownObservable.clear();
  71708. this.onPadUpObservable.clear();
  71709. };
  71710. return Xbox360Pad;
  71711. }(BABYLON.Gamepad));
  71712. BABYLON.Xbox360Pad = Xbox360Pad;
  71713. })(BABYLON || (BABYLON = {}));
  71714. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71715. var BABYLON;
  71716. (function (BABYLON) {
  71717. /**
  71718. * Defines the types of pose enabled controllers that are supported
  71719. */
  71720. var PoseEnabledControllerType;
  71721. (function (PoseEnabledControllerType) {
  71722. /**
  71723. * HTC Vive
  71724. */
  71725. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71726. /**
  71727. * Oculus Rift
  71728. */
  71729. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71730. /**
  71731. * Windows mixed reality
  71732. */
  71733. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71734. /**
  71735. * Samsung gear VR
  71736. */
  71737. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71738. /**
  71739. * Google Daydream
  71740. */
  71741. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71742. /**
  71743. * Generic
  71744. */
  71745. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71746. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71747. /**
  71748. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71749. */
  71750. var PoseEnabledControllerHelper = /** @class */ (function () {
  71751. function PoseEnabledControllerHelper() {
  71752. }
  71753. /**
  71754. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71755. * @param vrGamepad the gamepad to initialized
  71756. * @returns a vr controller of the type the gamepad identified as
  71757. */
  71758. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71759. // Oculus Touch
  71760. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71761. return new BABYLON.OculusTouchController(vrGamepad);
  71762. }
  71763. // Windows Mixed Reality controllers
  71764. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71765. return new BABYLON.WindowsMotionController(vrGamepad);
  71766. }
  71767. // HTC Vive
  71768. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71769. return new BABYLON.ViveController(vrGamepad);
  71770. }
  71771. // Samsung/Oculus Gear VR or Oculus Go
  71772. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71773. return new BABYLON.GearVRController(vrGamepad);
  71774. }
  71775. // Google Daydream
  71776. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71777. return new BABYLON.DaydreamController(vrGamepad);
  71778. }
  71779. // Generic
  71780. else {
  71781. return new BABYLON.GenericController(vrGamepad);
  71782. }
  71783. };
  71784. return PoseEnabledControllerHelper;
  71785. }());
  71786. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71787. /**
  71788. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71789. */
  71790. var PoseEnabledController = /** @class */ (function (_super) {
  71791. __extends(PoseEnabledController, _super);
  71792. /**
  71793. * Creates a new PoseEnabledController from a gamepad
  71794. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71795. */
  71796. function PoseEnabledController(browserGamepad) {
  71797. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71798. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71799. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71800. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71801. /**
  71802. * The device position in babylon space
  71803. */
  71804. _this.devicePosition = BABYLON.Vector3.Zero();
  71805. /**
  71806. * The device rotation in babylon space
  71807. */
  71808. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71809. /**
  71810. * The scale factor of the device in babylon space
  71811. */
  71812. _this.deviceScaleFactor = 1;
  71813. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71814. /**
  71815. * Internal, matrix used to convert room space to babylon space
  71816. */
  71817. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71818. /**
  71819. * Node to be used when casting a ray from the controller
  71820. */
  71821. _this._pointingPoseNode = null;
  71822. _this._workingMatrix = BABYLON.Matrix.Identity();
  71823. /**
  71824. * @hidden
  71825. */
  71826. _this._meshAttachedObservable = new BABYLON.Observable();
  71827. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71828. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71829. _this.position = BABYLON.Vector3.Zero();
  71830. _this.rotationQuaternion = new BABYLON.Quaternion();
  71831. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71832. _this._calculatedRotation = new BABYLON.Quaternion();
  71833. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71834. return _this;
  71835. }
  71836. /**
  71837. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71838. */
  71839. PoseEnabledController.prototype.update = function () {
  71840. _super.prototype.update.call(this);
  71841. this._updatePoseAndMesh();
  71842. };
  71843. /**
  71844. * Updates only the pose device and mesh without doing any button event checking
  71845. */
  71846. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  71847. var pose = this.browserGamepad.pose;
  71848. this.updateFromDevice(pose);
  71849. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71850. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71851. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71852. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71853. if (this._mesh) {
  71854. this._mesh.position.copyFrom(this.devicePosition);
  71855. if (this._mesh.rotationQuaternion) {
  71856. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71857. }
  71858. }
  71859. };
  71860. /**
  71861. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71862. * @param poseData raw pose fromthe device
  71863. */
  71864. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71865. if (poseData) {
  71866. this.rawPose = poseData;
  71867. if (poseData.position) {
  71868. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71869. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71870. this._deviceRoomPosition.z *= -1;
  71871. }
  71872. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71873. this._calculatedPosition.addInPlace(this.position);
  71874. }
  71875. var pose = this.rawPose;
  71876. if (poseData.orientation && pose.orientation) {
  71877. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71878. if (this._mesh) {
  71879. if (this._mesh.getScene().useRightHandedSystem) {
  71880. this._deviceRoomRotationQuaternion.z *= -1;
  71881. this._deviceRoomRotationQuaternion.w *= -1;
  71882. }
  71883. else {
  71884. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71885. }
  71886. }
  71887. // if the camera is set, rotate to the camera's rotation
  71888. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71889. }
  71890. }
  71891. };
  71892. /**
  71893. * Attaches a mesh to the controller
  71894. * @param mesh the mesh to be attached
  71895. */
  71896. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71897. if (this._mesh) {
  71898. this._mesh.parent = null;
  71899. }
  71900. this._mesh = mesh;
  71901. if (this._poseControlledCamera) {
  71902. this._mesh.parent = this._poseControlledCamera;
  71903. }
  71904. if (!this._mesh.rotationQuaternion) {
  71905. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71906. }
  71907. // 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
  71908. this._updatePoseAndMesh();
  71909. if (this._pointingPoseNode) {
  71910. var parents = [];
  71911. var obj = this._pointingPoseNode;
  71912. while (obj.parent) {
  71913. parents.push(obj.parent);
  71914. obj = obj.parent;
  71915. }
  71916. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71917. }
  71918. this._meshAttachedObservable.notifyObservers(mesh);
  71919. };
  71920. /**
  71921. * Attaches the controllers mesh to a camera
  71922. * @param camera the camera the mesh should be attached to
  71923. */
  71924. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71925. this._poseControlledCamera = camera;
  71926. if (this._mesh) {
  71927. this._mesh.parent = this._poseControlledCamera;
  71928. }
  71929. };
  71930. /**
  71931. * Disposes of the controller
  71932. */
  71933. PoseEnabledController.prototype.dispose = function () {
  71934. if (this._mesh) {
  71935. this._mesh.dispose();
  71936. }
  71937. this._mesh = null;
  71938. _super.prototype.dispose.call(this);
  71939. };
  71940. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71941. /**
  71942. * The mesh that is attached to the controller
  71943. */
  71944. get: function () {
  71945. return this._mesh;
  71946. },
  71947. enumerable: true,
  71948. configurable: true
  71949. });
  71950. /**
  71951. * Gets the ray of the controller in the direction the controller is pointing
  71952. * @param length the length the resulting ray should be
  71953. * @returns a ray in the direction the controller is pointing
  71954. */
  71955. PoseEnabledController.prototype.getForwardRay = function (length) {
  71956. if (length === void 0) { length = 100; }
  71957. if (!this.mesh) {
  71958. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71959. }
  71960. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71961. var origin = m.getTranslation();
  71962. var forward = new BABYLON.Vector3(0, 0, -1);
  71963. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71964. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71965. return new BABYLON.Ray(origin, direction, length);
  71966. };
  71967. /**
  71968. * Name of the child mesh that can be used to cast a ray from the controller
  71969. */
  71970. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71971. return PoseEnabledController;
  71972. }(BABYLON.Gamepad));
  71973. BABYLON.PoseEnabledController = PoseEnabledController;
  71974. })(BABYLON || (BABYLON = {}));
  71975. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71976. var BABYLON;
  71977. (function (BABYLON) {
  71978. /**
  71979. * Defines the WebVRController object that represents controllers tracked in 3D space
  71980. */
  71981. var WebVRController = /** @class */ (function (_super) {
  71982. __extends(WebVRController, _super);
  71983. /**
  71984. * Creates a new WebVRController from a gamepad
  71985. * @param vrGamepad the gamepad that the WebVRController should be created from
  71986. */
  71987. function WebVRController(vrGamepad) {
  71988. var _this = _super.call(this, vrGamepad) || this;
  71989. // Observables
  71990. /**
  71991. * Fired when the trigger state has changed
  71992. */
  71993. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71994. /**
  71995. * Fired when the main button state has changed
  71996. */
  71997. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71998. /**
  71999. * Fired when the secondary button state has changed
  72000. */
  72001. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  72002. /**
  72003. * Fired when the pad state has changed
  72004. */
  72005. _this.onPadStateChangedObservable = new BABYLON.Observable();
  72006. /**
  72007. * Fired when controllers stick values have changed
  72008. */
  72009. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  72010. /**
  72011. * X and Y axis corrisponding to the controllers joystick
  72012. */
  72013. _this.pad = { x: 0, y: 0 };
  72014. // avoid GC, store state in a tmp object
  72015. _this._changes = {
  72016. pressChanged: false,
  72017. touchChanged: false,
  72018. valueChanged: false,
  72019. changed: false
  72020. };
  72021. _this._buttons = new Array(vrGamepad.buttons.length);
  72022. _this.hand = vrGamepad.hand;
  72023. return _this;
  72024. }
  72025. /**
  72026. * Fired when a controller button's state has changed
  72027. * @param callback the callback containing the button that was modified
  72028. */
  72029. WebVRController.prototype.onButtonStateChange = function (callback) {
  72030. this._onButtonStateChange = callback;
  72031. };
  72032. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  72033. /**
  72034. * The default controller model for the controller
  72035. */
  72036. get: function () {
  72037. return this._defaultModel;
  72038. },
  72039. enumerable: true,
  72040. configurable: true
  72041. });
  72042. /**
  72043. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  72044. */
  72045. WebVRController.prototype.update = function () {
  72046. _super.prototype.update.call(this);
  72047. for (var index = 0; index < this._buttons.length; index++) {
  72048. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  72049. }
  72050. ;
  72051. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  72052. this.pad.x = this.leftStick.x;
  72053. this.pad.y = this.leftStick.y;
  72054. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  72055. }
  72056. };
  72057. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  72058. if (!newState) {
  72059. newState = {
  72060. pressed: false,
  72061. touched: false,
  72062. value: 0
  72063. };
  72064. }
  72065. if (!currentState) {
  72066. this._buttons[buttonIndex] = {
  72067. pressed: newState.pressed,
  72068. touched: newState.touched,
  72069. value: newState.value
  72070. };
  72071. return;
  72072. }
  72073. this._checkChanges(newState, currentState);
  72074. if (this._changes.changed) {
  72075. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  72076. this._handleButtonChange(buttonIndex, newState, this._changes);
  72077. }
  72078. this._buttons[buttonIndex].pressed = newState.pressed;
  72079. this._buttons[buttonIndex].touched = newState.touched;
  72080. // oculus triggers are never 0, thou not touched.
  72081. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  72082. };
  72083. WebVRController.prototype._checkChanges = function (newState, currentState) {
  72084. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  72085. this._changes.touchChanged = newState.touched !== currentState.touched;
  72086. this._changes.valueChanged = newState.value !== currentState.value;
  72087. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  72088. return this._changes;
  72089. };
  72090. /**
  72091. * Disposes of th webVRCOntroller
  72092. */
  72093. WebVRController.prototype.dispose = function () {
  72094. _super.prototype.dispose.call(this);
  72095. this.onTriggerStateChangedObservable.clear();
  72096. this.onMainButtonStateChangedObservable.clear();
  72097. this.onSecondaryButtonStateChangedObservable.clear();
  72098. this.onPadStateChangedObservable.clear();
  72099. this.onPadValuesChangedObservable.clear();
  72100. };
  72101. return WebVRController;
  72102. }(BABYLON.PoseEnabledController));
  72103. BABYLON.WebVRController = WebVRController;
  72104. })(BABYLON || (BABYLON = {}));
  72105. //# sourceMappingURL=babylon.webVRController.js.map
  72106. var BABYLON;
  72107. (function (BABYLON) {
  72108. /**
  72109. * Oculus Touch Controller
  72110. */
  72111. var OculusTouchController = /** @class */ (function (_super) {
  72112. __extends(OculusTouchController, _super);
  72113. /**
  72114. * Creates a new OculusTouchController from a gamepad
  72115. * @param vrGamepad the gamepad that the controller should be created from
  72116. */
  72117. function OculusTouchController(vrGamepad) {
  72118. var _this = _super.call(this, vrGamepad) || this;
  72119. /**
  72120. * Fired when the secondary trigger on this controller is modified
  72121. */
  72122. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72123. /**
  72124. * Fired when the thumb rest on this controller is modified
  72125. */
  72126. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72127. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72128. return _this;
  72129. }
  72130. /**
  72131. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72132. * @param scene scene in which to add meshes
  72133. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72134. */
  72135. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72136. var _this = this;
  72137. var meshName;
  72138. // Hand
  72139. if (this.hand === 'left') {
  72140. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72141. }
  72142. else { // Right is the default if no hand is specified
  72143. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72144. }
  72145. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72146. /*
  72147. Parent Mesh name: oculus_touch_left
  72148. - body
  72149. - trigger
  72150. - thumbstick
  72151. - grip
  72152. - button_y
  72153. - button_x
  72154. - button_enter
  72155. */
  72156. _this._defaultModel = newMeshes[1];
  72157. _this.attachToMesh(_this._defaultModel);
  72158. if (meshLoaded) {
  72159. meshLoaded(_this._defaultModel);
  72160. }
  72161. });
  72162. };
  72163. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72164. /**
  72165. * Fired when the A button on this controller is modified
  72166. */
  72167. get: function () {
  72168. if (this.hand === 'right') {
  72169. return this.onMainButtonStateChangedObservable;
  72170. }
  72171. else {
  72172. throw new Error('No A button on left hand');
  72173. }
  72174. },
  72175. enumerable: true,
  72176. configurable: true
  72177. });
  72178. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72179. /**
  72180. * Fired when the B button on this controller is modified
  72181. */
  72182. get: function () {
  72183. if (this.hand === 'right') {
  72184. return this.onSecondaryButtonStateChangedObservable;
  72185. }
  72186. else {
  72187. throw new Error('No B button on left hand');
  72188. }
  72189. },
  72190. enumerable: true,
  72191. configurable: true
  72192. });
  72193. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72194. /**
  72195. * Fired when the X button on this controller is modified
  72196. */
  72197. get: function () {
  72198. if (this.hand === 'left') {
  72199. return this.onMainButtonStateChangedObservable;
  72200. }
  72201. else {
  72202. throw new Error('No X button on right hand');
  72203. }
  72204. },
  72205. enumerable: true,
  72206. configurable: true
  72207. });
  72208. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72209. /**
  72210. * Fired when the Y button on this controller is modified
  72211. */
  72212. get: function () {
  72213. if (this.hand === 'left') {
  72214. return this.onSecondaryButtonStateChangedObservable;
  72215. }
  72216. else {
  72217. throw new Error('No Y button on right hand');
  72218. }
  72219. },
  72220. enumerable: true,
  72221. configurable: true
  72222. });
  72223. /**
  72224. * Called once for each button that changed state since the last frame
  72225. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72226. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72227. * 2) secondary trigger (same)
  72228. * 3) A (right) X (left), touch, pressed = value
  72229. * 4) B / Y
  72230. * 5) thumb rest
  72231. * @param buttonIdx Which button index changed
  72232. * @param state New state of the button
  72233. * @param changes Which properties on the state changed since last frame
  72234. */
  72235. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72236. var notifyObject = state; //{ state: state, changes: changes };
  72237. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72238. switch (buttonIdx) {
  72239. case 0:
  72240. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72241. return;
  72242. case 1: // index trigger
  72243. if (this._defaultModel) {
  72244. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72245. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72246. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72247. }
  72248. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72249. return;
  72250. case 2: // secondary trigger
  72251. if (this._defaultModel) {
  72252. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72253. }
  72254. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72255. return;
  72256. case 3:
  72257. if (this._defaultModel) {
  72258. if (notifyObject.pressed) {
  72259. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72260. }
  72261. else {
  72262. (this._defaultModel.getChildren()[1]).position.y = 0;
  72263. }
  72264. }
  72265. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72266. return;
  72267. case 4:
  72268. if (this._defaultModel) {
  72269. if (notifyObject.pressed) {
  72270. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72271. }
  72272. else {
  72273. (this._defaultModel.getChildren()[2]).position.y = 0;
  72274. }
  72275. }
  72276. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72277. return;
  72278. case 5:
  72279. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72280. return;
  72281. }
  72282. };
  72283. /**
  72284. * Base Url for the controller model.
  72285. */
  72286. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72287. /**
  72288. * File name for the left controller model.
  72289. */
  72290. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72291. /**
  72292. * File name for the right controller model.
  72293. */
  72294. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72295. return OculusTouchController;
  72296. }(BABYLON.WebVRController));
  72297. BABYLON.OculusTouchController = OculusTouchController;
  72298. })(BABYLON || (BABYLON = {}));
  72299. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72300. var BABYLON;
  72301. (function (BABYLON) {
  72302. /**
  72303. * Vive Controller
  72304. */
  72305. var ViveController = /** @class */ (function (_super) {
  72306. __extends(ViveController, _super);
  72307. /**
  72308. * Creates a new ViveController from a gamepad
  72309. * @param vrGamepad the gamepad that the controller should be created from
  72310. */
  72311. function ViveController(vrGamepad) {
  72312. var _this = _super.call(this, vrGamepad) || this;
  72313. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72314. _this._invertLeftStickY = true;
  72315. return _this;
  72316. }
  72317. /**
  72318. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72319. * @param scene scene in which to add meshes
  72320. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72321. */
  72322. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72323. var _this = this;
  72324. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72325. /*
  72326. Parent Mesh name: ViveWand
  72327. - body
  72328. - r_gripper
  72329. - l_gripper
  72330. - menu_button
  72331. - system_button
  72332. - trackpad
  72333. - trigger
  72334. - LED
  72335. */
  72336. _this._defaultModel = newMeshes[1];
  72337. _this.attachToMesh(_this._defaultModel);
  72338. if (meshLoaded) {
  72339. meshLoaded(_this._defaultModel);
  72340. }
  72341. });
  72342. };
  72343. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72344. /**
  72345. * Fired when the left button on this controller is modified
  72346. */
  72347. get: function () {
  72348. return this.onMainButtonStateChangedObservable;
  72349. },
  72350. enumerable: true,
  72351. configurable: true
  72352. });
  72353. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72354. /**
  72355. * Fired when the right button on this controller is modified
  72356. */
  72357. get: function () {
  72358. return this.onMainButtonStateChangedObservable;
  72359. },
  72360. enumerable: true,
  72361. configurable: true
  72362. });
  72363. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72364. /**
  72365. * Fired when the menu button on this controller is modified
  72366. */
  72367. get: function () {
  72368. return this.onSecondaryButtonStateChangedObservable;
  72369. },
  72370. enumerable: true,
  72371. configurable: true
  72372. });
  72373. /**
  72374. * Called once for each button that changed state since the last frame
  72375. * Vive mapping:
  72376. * 0: touchpad
  72377. * 1: trigger
  72378. * 2: left AND right buttons
  72379. * 3: menu button
  72380. * @param buttonIdx Which button index changed
  72381. * @param state New state of the button
  72382. * @param changes Which properties on the state changed since last frame
  72383. */
  72384. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72385. var notifyObject = state; //{ state: state, changes: changes };
  72386. switch (buttonIdx) {
  72387. case 0:
  72388. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72389. return;
  72390. case 1: // index trigger
  72391. if (this._defaultModel) {
  72392. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72393. }
  72394. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72395. return;
  72396. case 2: // left AND right button
  72397. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72398. return;
  72399. case 3:
  72400. if (this._defaultModel) {
  72401. if (notifyObject.pressed) {
  72402. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72403. }
  72404. else {
  72405. (this._defaultModel.getChildren()[2]).position.y = 0;
  72406. }
  72407. }
  72408. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72409. return;
  72410. }
  72411. };
  72412. /**
  72413. * Base Url for the controller model.
  72414. */
  72415. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72416. /**
  72417. * File name for the controller model.
  72418. */
  72419. ViveController.MODEL_FILENAME = 'wand.babylon';
  72420. return ViveController;
  72421. }(BABYLON.WebVRController));
  72422. BABYLON.ViveController = ViveController;
  72423. })(BABYLON || (BABYLON = {}));
  72424. //# sourceMappingURL=babylon.viveController.js.map
  72425. var BABYLON;
  72426. (function (BABYLON) {
  72427. /**
  72428. * Generic Controller
  72429. */
  72430. var GenericController = /** @class */ (function (_super) {
  72431. __extends(GenericController, _super);
  72432. /**
  72433. * Creates a new GenericController from a gamepad
  72434. * @param vrGamepad the gamepad that the controller should be created from
  72435. */
  72436. function GenericController(vrGamepad) {
  72437. return _super.call(this, vrGamepad) || this;
  72438. }
  72439. /**
  72440. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72441. * @param scene scene in which to add meshes
  72442. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72443. */
  72444. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72445. var _this = this;
  72446. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72447. _this._defaultModel = newMeshes[1];
  72448. _this.attachToMesh(_this._defaultModel);
  72449. if (meshLoaded) {
  72450. meshLoaded(_this._defaultModel);
  72451. }
  72452. });
  72453. };
  72454. /**
  72455. * Called once for each button that changed state since the last frame
  72456. * @param buttonIdx Which button index changed
  72457. * @param state New state of the button
  72458. * @param changes Which properties on the state changed since last frame
  72459. */
  72460. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72461. console.log("Button id: " + buttonIdx + "state: ");
  72462. console.dir(state);
  72463. };
  72464. /**
  72465. * Base Url for the controller model.
  72466. */
  72467. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72468. /**
  72469. * File name for the controller model.
  72470. */
  72471. GenericController.MODEL_FILENAME = 'generic.babylon';
  72472. return GenericController;
  72473. }(BABYLON.WebVRController));
  72474. BABYLON.GenericController = GenericController;
  72475. })(BABYLON || (BABYLON = {}));
  72476. //# sourceMappingURL=babylon.genericController.js.map
  72477. var BABYLON;
  72478. (function (BABYLON) {
  72479. /**
  72480. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72481. */
  72482. var LoadedMeshInfo = /** @class */ (function () {
  72483. function LoadedMeshInfo() {
  72484. /**
  72485. * Map of the button meshes contained in the controller
  72486. */
  72487. this.buttonMeshes = {};
  72488. /**
  72489. * Map of the axis meshes contained in the controller
  72490. */
  72491. this.axisMeshes = {};
  72492. }
  72493. return LoadedMeshInfo;
  72494. }());
  72495. /**
  72496. * Defines the WindowsMotionController object that the state of the windows motion controller
  72497. */
  72498. var WindowsMotionController = /** @class */ (function (_super) {
  72499. __extends(WindowsMotionController, _super);
  72500. /**
  72501. * Creates a new WindowsMotionController from a gamepad
  72502. * @param vrGamepad the gamepad that the controller should be created from
  72503. */
  72504. function WindowsMotionController(vrGamepad) {
  72505. var _this = _super.call(this, vrGamepad) || this;
  72506. _this._mapping = {
  72507. // Semantic button names
  72508. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72509. // A mapping of the button name to glTF model node name
  72510. // that should be transformed by button value.
  72511. buttonMeshNames: {
  72512. 'trigger': 'SELECT',
  72513. 'menu': 'MENU',
  72514. 'grip': 'GRASP',
  72515. 'thumbstick': 'THUMBSTICK_PRESS',
  72516. 'trackpad': 'TOUCHPAD_PRESS'
  72517. },
  72518. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72519. buttonObservableNames: {
  72520. 'trigger': 'onTriggerStateChangedObservable',
  72521. 'menu': 'onSecondaryButtonStateChangedObservable',
  72522. 'grip': 'onMainButtonStateChangedObservable',
  72523. 'thumbstick': 'onPadStateChangedObservable',
  72524. 'trackpad': 'onTrackpadChangedObservable'
  72525. },
  72526. // A mapping of the axis name to glTF model node name
  72527. // that should be transformed by axis value.
  72528. // This array mirrors the browserGamepad.axes array, such that
  72529. // the mesh corresponding to axis 0 is in this array index 0.
  72530. axisMeshNames: [
  72531. 'THUMBSTICK_X',
  72532. 'THUMBSTICK_Y',
  72533. 'TOUCHPAD_TOUCH_X',
  72534. 'TOUCHPAD_TOUCH_Y'
  72535. ],
  72536. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72537. };
  72538. /**
  72539. * Fired when the trackpad on this controller is clicked
  72540. */
  72541. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72542. /**
  72543. * Fired when the trackpad on this controller is modified
  72544. */
  72545. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72546. /**
  72547. * The current x and y values of this controller's trackpad
  72548. */
  72549. _this.trackpad = { x: 0, y: 0 };
  72550. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72551. _this._loadedMeshInfo = null;
  72552. return _this;
  72553. }
  72554. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72555. /**
  72556. * Fired when the trigger on this controller is modified
  72557. */
  72558. get: function () {
  72559. return this.onTriggerStateChangedObservable;
  72560. },
  72561. enumerable: true,
  72562. configurable: true
  72563. });
  72564. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72565. /**
  72566. * Fired when the menu button on this controller is modified
  72567. */
  72568. get: function () {
  72569. return this.onSecondaryButtonStateChangedObservable;
  72570. },
  72571. enumerable: true,
  72572. configurable: true
  72573. });
  72574. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72575. /**
  72576. * Fired when the grip button on this controller is modified
  72577. */
  72578. get: function () {
  72579. return this.onMainButtonStateChangedObservable;
  72580. },
  72581. enumerable: true,
  72582. configurable: true
  72583. });
  72584. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72585. /**
  72586. * Fired when the thumbstick button on this controller is modified
  72587. */
  72588. get: function () {
  72589. return this.onPadStateChangedObservable;
  72590. },
  72591. enumerable: true,
  72592. configurable: true
  72593. });
  72594. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72595. /**
  72596. * Fired when the touchpad button on this controller is modified
  72597. */
  72598. get: function () {
  72599. return this.onTrackpadChangedObservable;
  72600. },
  72601. enumerable: true,
  72602. configurable: true
  72603. });
  72604. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72605. /**
  72606. * Fired when the touchpad values on this controller are modified
  72607. */
  72608. get: function () {
  72609. return this.onTrackpadValuesChangedObservable;
  72610. },
  72611. enumerable: true,
  72612. configurable: true
  72613. });
  72614. WindowsMotionController.prototype._updateTrackpad = function () {
  72615. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72616. this.trackpad.x = this.browserGamepad["axes"][2];
  72617. this.trackpad.y = this.browserGamepad["axes"][3];
  72618. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72619. }
  72620. };
  72621. /**
  72622. * Called once per frame by the engine.
  72623. */
  72624. WindowsMotionController.prototype.update = function () {
  72625. _super.prototype.update.call(this);
  72626. if (this.browserGamepad.axes) {
  72627. this._updateTrackpad();
  72628. // Only need to animate axes if there is a loaded mesh
  72629. if (this._loadedMeshInfo) {
  72630. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72631. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72632. }
  72633. }
  72634. }
  72635. };
  72636. /**
  72637. * Called once for each button that changed state since the last frame
  72638. * @param buttonIdx Which button index changed
  72639. * @param state New state of the button
  72640. * @param changes Which properties on the state changed since last frame
  72641. */
  72642. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72643. var buttonName = this._mapping.buttons[buttonIdx];
  72644. if (!buttonName) {
  72645. return;
  72646. }
  72647. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72648. this._updateTrackpad();
  72649. // Only emit events for buttons that we know how to map from index to name
  72650. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72651. if (observable) {
  72652. observable.notifyObservers(state);
  72653. }
  72654. this._lerpButtonTransform(buttonName, state.value);
  72655. };
  72656. /**
  72657. * Moves the buttons on the controller mesh based on their current state
  72658. * @param buttonName the name of the button to move
  72659. * @param buttonValue the value of the button which determines the buttons new position
  72660. */
  72661. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72662. // If there is no loaded mesh, there is nothing to transform.
  72663. if (!this._loadedMeshInfo) {
  72664. return;
  72665. }
  72666. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72667. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72668. return;
  72669. }
  72670. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72671. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72672. };
  72673. /**
  72674. * Moves the axis on the controller mesh based on its current state
  72675. * @param axis the index of the axis
  72676. * @param axisValue the value of the axis which determines the meshes new position
  72677. * @hidden
  72678. */
  72679. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72680. if (!this._loadedMeshInfo) {
  72681. return;
  72682. }
  72683. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72684. if (!meshInfo) {
  72685. return;
  72686. }
  72687. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72688. return;
  72689. }
  72690. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72691. var lerpValue = axisValue * 0.5 + 0.5;
  72692. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72693. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72694. };
  72695. /**
  72696. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72697. * @param scene scene in which to add meshes
  72698. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72699. */
  72700. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72701. var _this = this;
  72702. if (forceDefault === void 0) { forceDefault = false; }
  72703. var path;
  72704. var filename;
  72705. // Checking if GLB loader is present
  72706. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72707. // Determine the device specific folder based on the ID suffix
  72708. var device = 'default';
  72709. if (this.id && !forceDefault) {
  72710. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72711. device = ((match && match[0]) || device);
  72712. }
  72713. // Hand
  72714. if (this.hand === 'left') {
  72715. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72716. }
  72717. else { // Right is the default if no hand is specified
  72718. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72719. }
  72720. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72721. }
  72722. else {
  72723. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72724. path = BABYLON.GenericController.MODEL_BASE_URL;
  72725. filename = BABYLON.GenericController.MODEL_FILENAME;
  72726. }
  72727. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72728. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72729. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72730. if (!_this._loadedMeshInfo) {
  72731. return;
  72732. }
  72733. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72734. _this.attachToMesh(_this._defaultModel);
  72735. if (meshLoaded) {
  72736. meshLoaded(_this._defaultModel);
  72737. }
  72738. }, null, function (scene, message) {
  72739. BABYLON.Tools.Log(message);
  72740. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72741. if (!forceDefault) {
  72742. _this.initControllerMesh(scene, meshLoaded, true);
  72743. }
  72744. });
  72745. };
  72746. /**
  72747. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72748. * can be transformed by button presses and axes values, based on this._mapping.
  72749. *
  72750. * @param scene scene in which the meshes exist
  72751. * @param meshes list of meshes that make up the controller model to process
  72752. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72753. */
  72754. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72755. var loadedMeshInfo = null;
  72756. // Create a new mesh to contain the glTF hierarchy
  72757. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72758. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72759. var childMesh = null;
  72760. for (var i = 0; i < meshes.length; i++) {
  72761. var mesh = meshes[i];
  72762. if (!mesh.parent) {
  72763. // Exclude controller meshes from picking results
  72764. mesh.isPickable = false;
  72765. // Handle root node, attach to the new parentMesh
  72766. childMesh = mesh;
  72767. break;
  72768. }
  72769. }
  72770. if (childMesh) {
  72771. childMesh.setParent(parentMesh);
  72772. // Create our mesh info. Note that this method will always return non-null.
  72773. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72774. }
  72775. else {
  72776. BABYLON.Tools.Warn('Could not find root node in model file.');
  72777. }
  72778. return loadedMeshInfo;
  72779. };
  72780. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72781. var loadedMeshInfo = new LoadedMeshInfo();
  72782. var i;
  72783. loadedMeshInfo.rootNode = rootNode;
  72784. // Reset the caches
  72785. loadedMeshInfo.buttonMeshes = {};
  72786. loadedMeshInfo.axisMeshes = {};
  72787. // Button Meshes
  72788. for (i = 0; i < this._mapping.buttons.length; i++) {
  72789. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72790. if (!buttonMeshName) {
  72791. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72792. continue;
  72793. }
  72794. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72795. if (!buttonMesh) {
  72796. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72797. continue;
  72798. }
  72799. var buttonMeshInfo = {
  72800. index: i,
  72801. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72802. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72803. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72804. };
  72805. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72806. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72807. }
  72808. else {
  72809. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72810. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72811. '(VALUE: ' + !!buttonMeshInfo.value +
  72812. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72813. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72814. ')');
  72815. }
  72816. }
  72817. // Axis Meshes
  72818. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72819. var axisMeshName = this._mapping.axisMeshNames[i];
  72820. if (!axisMeshName) {
  72821. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72822. continue;
  72823. }
  72824. var axisMesh = getChildByName(rootNode, axisMeshName);
  72825. if (!axisMesh) {
  72826. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72827. continue;
  72828. }
  72829. var axisMeshInfo = {
  72830. index: i,
  72831. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72832. min: getImmediateChildByName(axisMesh, 'MIN'),
  72833. max: getImmediateChildByName(axisMesh, 'MAX')
  72834. };
  72835. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72836. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72837. }
  72838. else {
  72839. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72840. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72841. '(VALUE: ' + !!axisMeshInfo.value +
  72842. ', MIN: ' + !!axisMeshInfo.min +
  72843. ', MAX:' + !!axisMeshInfo.max +
  72844. ')');
  72845. }
  72846. }
  72847. // Pointing Ray
  72848. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72849. if (!loadedMeshInfo.pointingPoseNode) {
  72850. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72851. }
  72852. else {
  72853. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72854. }
  72855. return loadedMeshInfo;
  72856. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72857. function getChildByName(node, name) {
  72858. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72859. }
  72860. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72861. function getImmediateChildByName(node, name) {
  72862. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72863. }
  72864. };
  72865. /**
  72866. * Gets the ray of the controller in the direction the controller is pointing
  72867. * @param length the length the resulting ray should be
  72868. * @returns a ray in the direction the controller is pointing
  72869. */
  72870. WindowsMotionController.prototype.getForwardRay = function (length) {
  72871. if (length === void 0) { length = 100; }
  72872. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72873. return _super.prototype.getForwardRay.call(this, length);
  72874. }
  72875. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72876. var origin = m.getTranslation();
  72877. var forward = new BABYLON.Vector3(0, 0, -1);
  72878. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72879. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72880. return new BABYLON.Ray(origin, direction, length);
  72881. };
  72882. /**
  72883. * Disposes of the controller
  72884. */
  72885. WindowsMotionController.prototype.dispose = function () {
  72886. _super.prototype.dispose.call(this);
  72887. this.onTrackpadChangedObservable.clear();
  72888. };
  72889. /**
  72890. * The base url used to load the left and right controller models
  72891. */
  72892. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72893. /**
  72894. * The name of the left controller model file
  72895. */
  72896. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72897. /**
  72898. * The name of the right controller model file
  72899. */
  72900. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72901. /**
  72902. * The controller name prefix for this controller type
  72903. */
  72904. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72905. /**
  72906. * The controller id pattern for this controller type
  72907. */
  72908. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72909. return WindowsMotionController;
  72910. }(BABYLON.WebVRController));
  72911. BABYLON.WindowsMotionController = WindowsMotionController;
  72912. })(BABYLON || (BABYLON = {}));
  72913. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72914. var BABYLON;
  72915. (function (BABYLON) {
  72916. /**
  72917. * Gear VR Controller
  72918. */
  72919. var GearVRController = /** @class */ (function (_super) {
  72920. __extends(GearVRController, _super);
  72921. /**
  72922. * Creates a new GearVRController from a gamepad
  72923. * @param vrGamepad the gamepad that the controller should be created from
  72924. */
  72925. function GearVRController(vrGamepad) {
  72926. var _this = _super.call(this, vrGamepad) || this;
  72927. _this._buttonIndexToObservableNameMap = [
  72928. 'onTrackpadChangedObservable',
  72929. 'onTriggerStateChangedObservable' // Trigger
  72930. ];
  72931. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72932. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72933. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72934. return _this;
  72935. }
  72936. /**
  72937. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72938. * @param scene scene in which to add meshes
  72939. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72940. */
  72941. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72942. var _this = this;
  72943. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72944. _this._defaultModel = newMeshes[1];
  72945. _this.attachToMesh(_this._defaultModel);
  72946. if (meshLoaded) {
  72947. meshLoaded(_this._defaultModel);
  72948. }
  72949. });
  72950. };
  72951. /**
  72952. * Called once for each button that changed state since the last frame
  72953. * @param buttonIdx Which button index changed
  72954. * @param state New state of the button
  72955. * @param changes Which properties on the state changed since last frame
  72956. */
  72957. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72958. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72959. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72960. // Only emit events for buttons that we know how to map from index to observable
  72961. var observable = this[observableName];
  72962. if (observable) {
  72963. observable.notifyObservers(state);
  72964. }
  72965. }
  72966. };
  72967. /**
  72968. * Base Url for the controller model.
  72969. */
  72970. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72971. /**
  72972. * File name for the controller model.
  72973. */
  72974. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72975. /**
  72976. * Gamepad Id prefix used to identify this controller.
  72977. */
  72978. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72979. return GearVRController;
  72980. }(BABYLON.WebVRController));
  72981. BABYLON.GearVRController = GearVRController;
  72982. })(BABYLON || (BABYLON = {}));
  72983. //# sourceMappingURL=babylon.gearVRController.js.map
  72984. var BABYLON;
  72985. (function (BABYLON) {
  72986. /**
  72987. * Google Daydream controller
  72988. */
  72989. var DaydreamController = /** @class */ (function (_super) {
  72990. __extends(DaydreamController, _super);
  72991. /**
  72992. * Creates a new DaydreamController from a gamepad
  72993. * @param vrGamepad the gamepad that the controller should be created from
  72994. */
  72995. function DaydreamController(vrGamepad) {
  72996. var _this = _super.call(this, vrGamepad) || this;
  72997. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72998. return _this;
  72999. }
  73000. /**
  73001. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73002. * @param scene scene in which to add meshes
  73003. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73004. */
  73005. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73006. var _this = this;
  73007. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  73008. _this._defaultModel = newMeshes[1];
  73009. _this.attachToMesh(_this._defaultModel);
  73010. if (meshLoaded) {
  73011. meshLoaded(_this._defaultModel);
  73012. }
  73013. });
  73014. };
  73015. /**
  73016. * Called once for each button that changed state since the last frame
  73017. * @param buttonIdx Which button index changed
  73018. * @param state New state of the button
  73019. * @param changes Which properties on the state changed since last frame
  73020. */
  73021. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73022. // Daydream controller only has 1 GamepadButton (on the trackpad).
  73023. if (buttonIdx === 0) {
  73024. var observable = this.onTriggerStateChangedObservable;
  73025. if (observable) {
  73026. observable.notifyObservers(state);
  73027. }
  73028. }
  73029. else {
  73030. // If the app or home buttons are ever made available
  73031. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  73032. }
  73033. };
  73034. /**
  73035. * Base Url for the controller model.
  73036. */
  73037. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73038. /**
  73039. * File name for the controller model.
  73040. */
  73041. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  73042. /**
  73043. * Gamepad Id prefix used to identify Daydream Controller.
  73044. */
  73045. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  73046. return DaydreamController;
  73047. }(BABYLON.WebVRController));
  73048. BABYLON.DaydreamController = DaydreamController;
  73049. })(BABYLON || (BABYLON = {}));
  73050. //# sourceMappingURL=babylon.daydreamController.js.map
  73051. var BABYLON;
  73052. (function (BABYLON) {
  73053. var FollowCamera = /** @class */ (function (_super) {
  73054. __extends(FollowCamera, _super);
  73055. function FollowCamera(name, position, scene, lockedTarget) {
  73056. if (lockedTarget === void 0) { lockedTarget = null; }
  73057. var _this = _super.call(this, name, position, scene) || this;
  73058. _this.radius = 12;
  73059. _this.rotationOffset = 0;
  73060. _this.heightOffset = 4;
  73061. _this.cameraAcceleration = 0.05;
  73062. _this.maxCameraSpeed = 20;
  73063. _this.lockedTarget = lockedTarget;
  73064. return _this;
  73065. }
  73066. FollowCamera.prototype.getRadians = function (degrees) {
  73067. return degrees * Math.PI / 180;
  73068. };
  73069. FollowCamera.prototype.follow = function (cameraTarget) {
  73070. if (!cameraTarget)
  73071. return;
  73072. var yRotation;
  73073. if (cameraTarget.rotationQuaternion) {
  73074. var rotMatrix = new BABYLON.Matrix();
  73075. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  73076. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  73077. }
  73078. else {
  73079. yRotation = cameraTarget.rotation.y;
  73080. }
  73081. var radians = this.getRadians(this.rotationOffset) + yRotation;
  73082. var targetPosition = cameraTarget.getAbsolutePosition();
  73083. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  73084. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  73085. var dx = targetX - this.position.x;
  73086. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  73087. var dz = (targetZ) - this.position.z;
  73088. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  73089. var vy = dy * this.cameraAcceleration;
  73090. var vz = dz * this.cameraAcceleration * 2;
  73091. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  73092. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73093. }
  73094. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73095. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73096. }
  73097. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73098. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73099. }
  73100. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73101. this.setTarget(targetPosition);
  73102. };
  73103. FollowCamera.prototype._checkInputs = function () {
  73104. _super.prototype._checkInputs.call(this);
  73105. if (this.lockedTarget) {
  73106. this.follow(this.lockedTarget);
  73107. }
  73108. };
  73109. FollowCamera.prototype.getClassName = function () {
  73110. return "FollowCamera";
  73111. };
  73112. __decorate([
  73113. BABYLON.serialize()
  73114. ], FollowCamera.prototype, "radius", void 0);
  73115. __decorate([
  73116. BABYLON.serialize()
  73117. ], FollowCamera.prototype, "rotationOffset", void 0);
  73118. __decorate([
  73119. BABYLON.serialize()
  73120. ], FollowCamera.prototype, "heightOffset", void 0);
  73121. __decorate([
  73122. BABYLON.serialize()
  73123. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73124. __decorate([
  73125. BABYLON.serialize()
  73126. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73127. __decorate([
  73128. BABYLON.serializeAsMeshReference("lockedTargetId")
  73129. ], FollowCamera.prototype, "lockedTarget", void 0);
  73130. return FollowCamera;
  73131. }(BABYLON.TargetCamera));
  73132. BABYLON.FollowCamera = FollowCamera;
  73133. var ArcFollowCamera = /** @class */ (function (_super) {
  73134. __extends(ArcFollowCamera, _super);
  73135. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73136. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73137. _this.alpha = alpha;
  73138. _this.beta = beta;
  73139. _this.radius = radius;
  73140. _this.target = target;
  73141. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73142. _this.follow();
  73143. return _this;
  73144. }
  73145. ArcFollowCamera.prototype.follow = function () {
  73146. if (!this.target) {
  73147. return;
  73148. }
  73149. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73150. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73151. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73152. var targetPosition = this.target.getAbsolutePosition();
  73153. this.position = targetPosition.add(this._cartesianCoordinates);
  73154. this.setTarget(targetPosition);
  73155. };
  73156. ArcFollowCamera.prototype._checkInputs = function () {
  73157. _super.prototype._checkInputs.call(this);
  73158. this.follow();
  73159. };
  73160. ArcFollowCamera.prototype.getClassName = function () {
  73161. return "ArcFollowCamera";
  73162. };
  73163. return ArcFollowCamera;
  73164. }(BABYLON.TargetCamera));
  73165. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73166. })(BABYLON || (BABYLON = {}));
  73167. //# sourceMappingURL=babylon.followCamera.js.map
  73168. var BABYLON;
  73169. (function (BABYLON) {
  73170. // We're mainly based on the logic defined into the FreeCamera code
  73171. var UniversalCamera = /** @class */ (function (_super) {
  73172. __extends(UniversalCamera, _super);
  73173. //-- end properties for backward compatibility for inputs
  73174. function UniversalCamera(name, position, scene) {
  73175. var _this = _super.call(this, name, position, scene) || this;
  73176. _this.inputs.addGamepad();
  73177. return _this;
  73178. }
  73179. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73180. //-- Begin properties for backward compatibility for inputs
  73181. get: function () {
  73182. var gamepad = this.inputs.attached["gamepad"];
  73183. if (gamepad)
  73184. return gamepad.gamepadAngularSensibility;
  73185. return 0;
  73186. },
  73187. set: function (value) {
  73188. var gamepad = this.inputs.attached["gamepad"];
  73189. if (gamepad)
  73190. gamepad.gamepadAngularSensibility = value;
  73191. },
  73192. enumerable: true,
  73193. configurable: true
  73194. });
  73195. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73196. get: function () {
  73197. var gamepad = this.inputs.attached["gamepad"];
  73198. if (gamepad)
  73199. return gamepad.gamepadMoveSensibility;
  73200. return 0;
  73201. },
  73202. set: function (value) {
  73203. var gamepad = this.inputs.attached["gamepad"];
  73204. if (gamepad)
  73205. gamepad.gamepadMoveSensibility = value;
  73206. },
  73207. enumerable: true,
  73208. configurable: true
  73209. });
  73210. UniversalCamera.prototype.getClassName = function () {
  73211. return "UniversalCamera";
  73212. };
  73213. return UniversalCamera;
  73214. }(BABYLON.TouchCamera));
  73215. BABYLON.UniversalCamera = UniversalCamera;
  73216. })(BABYLON || (BABYLON = {}));
  73217. //# sourceMappingURL=babylon.universalCamera.js.map
  73218. var BABYLON;
  73219. (function (BABYLON) {
  73220. // We're mainly based on the logic defined into the FreeCamera code
  73221. var GamepadCamera = /** @class */ (function (_super) {
  73222. __extends(GamepadCamera, _super);
  73223. //-- end properties for backward compatibility for inputs
  73224. function GamepadCamera(name, position, scene) {
  73225. return _super.call(this, name, position, scene) || this;
  73226. }
  73227. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73228. //-- Begin properties for backward compatibility for inputs
  73229. get: function () {
  73230. var gamepad = this.inputs.attached["gamepad"];
  73231. if (gamepad)
  73232. return gamepad.gamepadAngularSensibility;
  73233. return 0;
  73234. },
  73235. set: function (value) {
  73236. var gamepad = this.inputs.attached["gamepad"];
  73237. if (gamepad)
  73238. gamepad.gamepadAngularSensibility = value;
  73239. },
  73240. enumerable: true,
  73241. configurable: true
  73242. });
  73243. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73244. get: function () {
  73245. var gamepad = this.inputs.attached["gamepad"];
  73246. if (gamepad)
  73247. return gamepad.gamepadMoveSensibility;
  73248. return 0;
  73249. },
  73250. set: function (value) {
  73251. var gamepad = this.inputs.attached["gamepad"];
  73252. if (gamepad)
  73253. gamepad.gamepadMoveSensibility = value;
  73254. },
  73255. enumerable: true,
  73256. configurable: true
  73257. });
  73258. GamepadCamera.prototype.getClassName = function () {
  73259. return "GamepadCamera";
  73260. };
  73261. return GamepadCamera;
  73262. }(BABYLON.UniversalCamera));
  73263. BABYLON.GamepadCamera = GamepadCamera;
  73264. })(BABYLON || (BABYLON = {}));
  73265. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73266. var BABYLON;
  73267. (function (BABYLON) {
  73268. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73269. function PostProcessRenderPipelineManager() {
  73270. this._renderPipelines = {};
  73271. }
  73272. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73273. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73274. };
  73275. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73276. if (unique === void 0) { unique = false; }
  73277. var renderPipeline = this._renderPipelines[renderPipelineName];
  73278. if (!renderPipeline) {
  73279. return;
  73280. }
  73281. renderPipeline._attachCameras(cameras, unique);
  73282. };
  73283. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73284. var renderPipeline = this._renderPipelines[renderPipelineName];
  73285. if (!renderPipeline) {
  73286. return;
  73287. }
  73288. renderPipeline._detachCameras(cameras);
  73289. };
  73290. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73291. var renderPipeline = this._renderPipelines[renderPipelineName];
  73292. if (!renderPipeline) {
  73293. return;
  73294. }
  73295. renderPipeline._enableEffect(renderEffectName, cameras);
  73296. };
  73297. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73298. var renderPipeline = this._renderPipelines[renderPipelineName];
  73299. if (!renderPipeline) {
  73300. return;
  73301. }
  73302. renderPipeline._disableEffect(renderEffectName, cameras);
  73303. };
  73304. PostProcessRenderPipelineManager.prototype.update = function () {
  73305. for (var renderPipelineName in this._renderPipelines) {
  73306. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73307. var pipeline = this._renderPipelines[renderPipelineName];
  73308. if (!pipeline.isSupported) {
  73309. pipeline.dispose();
  73310. delete this._renderPipelines[renderPipelineName];
  73311. }
  73312. else {
  73313. pipeline._update();
  73314. }
  73315. }
  73316. }
  73317. };
  73318. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73319. for (var renderPipelineName in this._renderPipelines) {
  73320. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73321. var pipeline = this._renderPipelines[renderPipelineName];
  73322. pipeline._rebuild();
  73323. }
  73324. }
  73325. };
  73326. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73327. for (var renderPipelineName in this._renderPipelines) {
  73328. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73329. var pipeline = this._renderPipelines[renderPipelineName];
  73330. pipeline.dispose();
  73331. }
  73332. }
  73333. };
  73334. return PostProcessRenderPipelineManager;
  73335. }());
  73336. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73337. })(BABYLON || (BABYLON = {}));
  73338. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73339. var BABYLON;
  73340. (function (BABYLON) {
  73341. /**
  73342. * This represents a set of one or more post processes in Babylon.
  73343. * A post process can be used to apply a shader to a texture after it is rendered.
  73344. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73345. */
  73346. var PostProcessRenderEffect = /** @class */ (function () {
  73347. /**
  73348. * Instantiates a post process render effect.
  73349. * A post process can be used to apply a shader to a texture after it is rendered.
  73350. * @param engine The engine the effect is tied to
  73351. * @param name The name of the effect
  73352. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73353. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73354. */
  73355. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73356. this._name = name;
  73357. this._singleInstance = singleInstance || true;
  73358. this._getPostProcesses = getPostProcesses;
  73359. this._cameras = {};
  73360. this._indicesForCamera = {};
  73361. this._postProcesses = {};
  73362. }
  73363. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73364. /**
  73365. * Checks if all the post processes in the effect are supported.
  73366. */
  73367. get: function () {
  73368. for (var index in this._postProcesses) {
  73369. if (this._postProcesses.hasOwnProperty(index)) {
  73370. var pps = this._postProcesses[index];
  73371. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73372. if (!pps[ppIndex].isSupported) {
  73373. return false;
  73374. }
  73375. }
  73376. }
  73377. }
  73378. return true;
  73379. },
  73380. enumerable: true,
  73381. configurable: true
  73382. });
  73383. /**
  73384. * Updates the current state of the effect
  73385. */
  73386. PostProcessRenderEffect.prototype._update = function () {
  73387. };
  73388. /**
  73389. * Attaches the effect on cameras
  73390. * @param cameras The camera to attach to.
  73391. */
  73392. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73393. var _this = this;
  73394. var cameraKey;
  73395. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73396. if (!cams) {
  73397. return;
  73398. }
  73399. for (var i = 0; i < cams.length; i++) {
  73400. var camera = cams[i];
  73401. var cameraName = camera.name;
  73402. if (this._singleInstance) {
  73403. cameraKey = 0;
  73404. }
  73405. else {
  73406. cameraKey = cameraName;
  73407. }
  73408. if (!this._postProcesses[cameraKey]) {
  73409. var postProcess = this._getPostProcesses();
  73410. if (postProcess) {
  73411. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73412. }
  73413. }
  73414. if (!this._indicesForCamera[cameraName]) {
  73415. this._indicesForCamera[cameraName] = [];
  73416. }
  73417. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73418. var index = camera.attachPostProcess(postProcess);
  73419. _this._indicesForCamera[cameraName].push(index);
  73420. });
  73421. if (!this._cameras[cameraName]) {
  73422. this._cameras[cameraName] = camera;
  73423. }
  73424. }
  73425. };
  73426. /**
  73427. * Detatches the effect on cameras
  73428. * @param cameras The camera to detatch from.
  73429. */
  73430. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73431. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73432. if (!cams) {
  73433. return;
  73434. }
  73435. for (var i = 0; i < cams.length; i++) {
  73436. var camera = cams[i];
  73437. var cameraName = camera.name;
  73438. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73439. camera.detachPostProcess(postProcess);
  73440. });
  73441. if (this._cameras[cameraName]) {
  73442. //this._indicesForCamera.splice(index, 1);
  73443. this._cameras[cameraName] = null;
  73444. }
  73445. }
  73446. };
  73447. /**
  73448. * Enables the effect on given cameras
  73449. * @param cameras The camera to enable.
  73450. */
  73451. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73452. var _this = this;
  73453. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73454. if (!cams) {
  73455. return;
  73456. }
  73457. for (var i = 0; i < cams.length; i++) {
  73458. var camera = cams[i];
  73459. var cameraName = camera.name;
  73460. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73461. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73462. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73463. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73464. });
  73465. }
  73466. }
  73467. }
  73468. };
  73469. /**
  73470. * Disables the effect on the given cameras
  73471. * @param cameras The camera to disable.
  73472. */
  73473. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73474. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73475. if (!cams) {
  73476. return;
  73477. }
  73478. for (var i = 0; i < cams.length; i++) {
  73479. var camera = cams[i];
  73480. var cameraName = camera.name;
  73481. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73482. camera.detachPostProcess(postProcess);
  73483. });
  73484. }
  73485. };
  73486. /**
  73487. * Gets a list of the post processes contained in the effect.
  73488. * @param camera The camera to get the post processes on.
  73489. * @returns The list of the post processes in the effect.
  73490. */
  73491. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73492. if (this._singleInstance) {
  73493. return this._postProcesses[0];
  73494. }
  73495. else {
  73496. if (!camera) {
  73497. return null;
  73498. }
  73499. return this._postProcesses[camera.name];
  73500. }
  73501. };
  73502. return PostProcessRenderEffect;
  73503. }());
  73504. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73505. })(BABYLON || (BABYLON = {}));
  73506. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73507. var BABYLON;
  73508. (function (BABYLON) {
  73509. var PostProcessRenderPipeline = /** @class */ (function () {
  73510. function PostProcessRenderPipeline(engine, name) {
  73511. this.engine = engine;
  73512. this._name = name;
  73513. this._renderEffects = {};
  73514. this._renderEffectsForIsolatedPass = new Array();
  73515. this._cameras = [];
  73516. }
  73517. PostProcessRenderPipeline.prototype.getClassName = function () {
  73518. return "PostProcessRenderPipeline";
  73519. };
  73520. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73521. get: function () {
  73522. for (var renderEffectName in this._renderEffects) {
  73523. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73524. if (!this._renderEffects[renderEffectName].isSupported) {
  73525. return false;
  73526. }
  73527. }
  73528. }
  73529. return true;
  73530. },
  73531. enumerable: true,
  73532. configurable: true
  73533. });
  73534. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73535. this._renderEffects[renderEffect._name] = renderEffect;
  73536. };
  73537. // private
  73538. PostProcessRenderPipeline.prototype._rebuild = function () {
  73539. };
  73540. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73541. var renderEffects = this._renderEffects[renderEffectName];
  73542. if (!renderEffects) {
  73543. return;
  73544. }
  73545. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73546. };
  73547. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73548. var renderEffects = this._renderEffects[renderEffectName];
  73549. if (!renderEffects) {
  73550. return;
  73551. }
  73552. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73553. };
  73554. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73555. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73556. if (!cams) {
  73557. return;
  73558. }
  73559. var indicesToDelete = [];
  73560. var i;
  73561. for (i = 0; i < cams.length; i++) {
  73562. var camera = cams[i];
  73563. var cameraName = camera.name;
  73564. if (this._cameras.indexOf(camera) === -1) {
  73565. this._cameras[cameraName] = camera;
  73566. }
  73567. else if (unique) {
  73568. indicesToDelete.push(i);
  73569. }
  73570. }
  73571. for (i = 0; i < indicesToDelete.length; i++) {
  73572. cameras.splice(indicesToDelete[i], 1);
  73573. }
  73574. for (var renderEffectName in this._renderEffects) {
  73575. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73576. this._renderEffects[renderEffectName]._attachCameras(cams);
  73577. }
  73578. }
  73579. };
  73580. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73581. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73582. if (!cams) {
  73583. return;
  73584. }
  73585. for (var renderEffectName in this._renderEffects) {
  73586. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73587. this._renderEffects[renderEffectName]._detachCameras(cams);
  73588. }
  73589. }
  73590. for (var i = 0; i < cams.length; i++) {
  73591. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73592. }
  73593. };
  73594. PostProcessRenderPipeline.prototype._update = function () {
  73595. for (var renderEffectName in this._renderEffects) {
  73596. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73597. this._renderEffects[renderEffectName]._update();
  73598. }
  73599. }
  73600. for (var i = 0; i < this._cameras.length; i++) {
  73601. var cameraName = this._cameras[i].name;
  73602. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73603. this._renderEffectsForIsolatedPass[cameraName]._update();
  73604. }
  73605. }
  73606. };
  73607. PostProcessRenderPipeline.prototype._reset = function () {
  73608. this._renderEffects = {};
  73609. this._renderEffectsForIsolatedPass = new Array();
  73610. };
  73611. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73612. // 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)
  73613. var effectKeys = Object.keys(this._renderEffects);
  73614. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73615. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73616. if (postProcesses) {
  73617. postProcesses[0].samples = sampleCount;
  73618. return true;
  73619. }
  73620. }
  73621. return false;
  73622. };
  73623. PostProcessRenderPipeline.prototype.dispose = function () {
  73624. // Must be implemented by children
  73625. };
  73626. __decorate([
  73627. BABYLON.serialize()
  73628. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73629. return PostProcessRenderPipeline;
  73630. }());
  73631. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73632. })(BABYLON || (BABYLON = {}));
  73633. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73634. var BABYLON;
  73635. (function (BABYLON) {
  73636. /**
  73637. * This represents a depth renderer in Babylon.
  73638. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73639. */
  73640. var DepthRenderer = /** @class */ (function () {
  73641. /**
  73642. * Instantiates a depth renderer
  73643. * @param scene The scene the renderer belongs to
  73644. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73645. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73646. */
  73647. function DepthRenderer(scene, type, camera) {
  73648. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73649. if (camera === void 0) { camera = null; }
  73650. var _this = this;
  73651. this._scene = scene;
  73652. this._camera = camera;
  73653. var engine = scene.getEngine();
  73654. // Render target
  73655. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73656. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73657. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73658. this._depthMap.refreshRate = 1;
  73659. this._depthMap.renderParticles = false;
  73660. this._depthMap.renderList = null;
  73661. // Camera to get depth map from to support multiple concurrent cameras
  73662. this._depthMap.activeCamera = this._camera;
  73663. this._depthMap.ignoreCameraViewport = true;
  73664. this._depthMap.useCameraPostProcesses = false;
  73665. // set default depth value to 1.0 (far away)
  73666. this._depthMap.onClearObservable.add(function (engine) {
  73667. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73668. });
  73669. // Custom render function
  73670. var renderSubMesh = function (subMesh) {
  73671. var mesh = subMesh.getRenderingMesh();
  73672. var scene = _this._scene;
  73673. var engine = scene.getEngine();
  73674. var material = subMesh.getMaterial();
  73675. if (!material) {
  73676. return;
  73677. }
  73678. // Culling and reverse (right handed system)
  73679. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73680. // Managing instances
  73681. var batch = mesh._getInstancesRenderList(subMesh._id);
  73682. if (batch.mustReturn) {
  73683. return;
  73684. }
  73685. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73686. var camera = _this._camera || scene.activeCamera;
  73687. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73688. engine.enableEffect(_this._effect);
  73689. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73690. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73691. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73692. // Alpha test
  73693. if (material && material.needAlphaTesting()) {
  73694. var alphaTexture = material.getAlphaTestTexture();
  73695. if (alphaTexture) {
  73696. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73697. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73698. }
  73699. }
  73700. // Bones
  73701. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73702. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73703. }
  73704. // Draw
  73705. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73706. }
  73707. };
  73708. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73709. var index;
  73710. if (depthOnlySubMeshes.length) {
  73711. engine.setColorWrite(false);
  73712. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73713. renderSubMesh(depthOnlySubMeshes.data[index]);
  73714. }
  73715. engine.setColorWrite(true);
  73716. }
  73717. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73718. renderSubMesh(opaqueSubMeshes.data[index]);
  73719. }
  73720. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73721. renderSubMesh(alphaTestSubMeshes.data[index]);
  73722. }
  73723. };
  73724. }
  73725. /**
  73726. * Creates the depth rendering effect and checks if the effect is ready.
  73727. * @param subMesh The submesh to be used to render the depth map of
  73728. * @param useInstances If multiple world instances should be used
  73729. * @returns if the depth renderer is ready to render the depth map
  73730. */
  73731. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73732. var material = subMesh.getMaterial();
  73733. if (material.disableDepthWrite) {
  73734. return false;
  73735. }
  73736. var defines = [];
  73737. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73738. var mesh = subMesh.getMesh();
  73739. // Alpha test
  73740. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73741. defines.push("#define ALPHATEST");
  73742. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73743. attribs.push(BABYLON.VertexBuffer.UVKind);
  73744. defines.push("#define UV1");
  73745. }
  73746. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73747. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73748. defines.push("#define UV2");
  73749. }
  73750. }
  73751. // Bones
  73752. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73753. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73754. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73755. if (mesh.numBoneInfluencers > 4) {
  73756. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73757. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73758. }
  73759. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73760. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73761. }
  73762. else {
  73763. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73764. }
  73765. // Instances
  73766. if (useInstances) {
  73767. defines.push("#define INSTANCES");
  73768. attribs.push("world0");
  73769. attribs.push("world1");
  73770. attribs.push("world2");
  73771. attribs.push("world3");
  73772. }
  73773. // Get correct effect
  73774. var join = defines.join("\n");
  73775. if (this._cachedDefines !== join) {
  73776. this._cachedDefines = join;
  73777. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73778. }
  73779. return this._effect.isReady();
  73780. };
  73781. /**
  73782. * Gets the texture which the depth map will be written to.
  73783. * @returns The depth map texture
  73784. */
  73785. DepthRenderer.prototype.getDepthMap = function () {
  73786. return this._depthMap;
  73787. };
  73788. /**
  73789. * Disposes of the depth renderer.
  73790. */
  73791. DepthRenderer.prototype.dispose = function () {
  73792. this._depthMap.dispose();
  73793. };
  73794. return DepthRenderer;
  73795. }());
  73796. BABYLON.DepthRenderer = DepthRenderer;
  73797. })(BABYLON || (BABYLON = {}));
  73798. //# sourceMappingURL=babylon.depthRenderer.js.map
  73799. var BABYLON;
  73800. (function (BABYLON) {
  73801. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73802. __extends(SSAORenderingPipeline, _super);
  73803. /**
  73804. * @constructor
  73805. * @param {string} name - The rendering pipeline name
  73806. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73807. * @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 }
  73808. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73809. */
  73810. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73811. var _this = _super.call(this, scene.getEngine(), name) || this;
  73812. // Members
  73813. /**
  73814. * The PassPostProcess id in the pipeline that contains the original scene color
  73815. */
  73816. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73817. /**
  73818. * The SSAO PostProcess id in the pipeline
  73819. */
  73820. _this.SSAORenderEffect = "SSAORenderEffect";
  73821. /**
  73822. * The horizontal blur PostProcess id in the pipeline
  73823. */
  73824. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73825. /**
  73826. * The vertical blur PostProcess id in the pipeline
  73827. */
  73828. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73829. /**
  73830. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73831. */
  73832. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73833. /**
  73834. * The output strength of the SSAO post-process. Default value is 1.0.
  73835. */
  73836. _this.totalStrength = 1.0;
  73837. /**
  73838. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73839. */
  73840. _this.radius = 0.0001;
  73841. /**
  73842. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73843. * Must not be equal to fallOff and superior to fallOff.
  73844. * Default value is 0.975
  73845. */
  73846. _this.area = 0.0075;
  73847. /**
  73848. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73849. * Must not be equal to area and inferior to area.
  73850. * Default value is 0.0
  73851. */
  73852. _this.fallOff = 0.000001;
  73853. /**
  73854. * The base color of the SSAO post-process
  73855. * The final result is "base + ssao" between [0, 1]
  73856. */
  73857. _this.base = 0.5;
  73858. _this._firstUpdate = true;
  73859. _this._scene = scene;
  73860. // Set up assets
  73861. _this._createRandomTexture();
  73862. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73863. var ssaoRatio = ratio.ssaoRatio || ratio;
  73864. var combineRatio = ratio.combineRatio || ratio;
  73865. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73866. _this._createSSAOPostProcess(ssaoRatio);
  73867. _this._createBlurPostProcess(ssaoRatio);
  73868. _this._createSSAOCombinePostProcess(combineRatio);
  73869. // Set up pipeline
  73870. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73871. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73872. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73873. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73874. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73875. // Finish
  73876. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73877. if (cameras)
  73878. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73879. return _this;
  73880. }
  73881. // Public Methods
  73882. /**
  73883. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73884. */
  73885. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73886. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73887. for (var i = 0; i < this._scene.cameras.length; i++) {
  73888. var camera = this._scene.cameras[i];
  73889. this._originalColorPostProcess.dispose(camera);
  73890. this._ssaoPostProcess.dispose(camera);
  73891. this._blurHPostProcess.dispose(camera);
  73892. this._blurVPostProcess.dispose(camera);
  73893. this._ssaoCombinePostProcess.dispose(camera);
  73894. }
  73895. this._randomTexture.dispose();
  73896. if (disableDepthRender)
  73897. this._scene.disableDepthRenderer();
  73898. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73899. _super.prototype.dispose.call(this);
  73900. };
  73901. // Private Methods
  73902. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73903. var _this = this;
  73904. var size = 16;
  73905. 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);
  73906. 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);
  73907. this._blurHPostProcess.onActivateObservable.add(function () {
  73908. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73909. _this._blurHPostProcess.kernel = size * dw;
  73910. });
  73911. this._blurVPostProcess.onActivateObservable.add(function () {
  73912. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73913. _this._blurVPostProcess.kernel = size * dw;
  73914. });
  73915. };
  73916. SSAORenderingPipeline.prototype._rebuild = function () {
  73917. this._firstUpdate = true;
  73918. _super.prototype._rebuild.call(this);
  73919. };
  73920. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73921. var _this = this;
  73922. var numSamples = 16;
  73923. var sampleSphere = [
  73924. 0.5381, 0.1856, -0.4319,
  73925. 0.1379, 0.2486, 0.4430,
  73926. 0.3371, 0.5679, -0.0057,
  73927. -0.6999, -0.0451, -0.0019,
  73928. 0.0689, -0.1598, -0.8547,
  73929. 0.0560, 0.0069, -0.1843,
  73930. -0.0146, 0.1402, 0.0762,
  73931. 0.0100, -0.1924, -0.0344,
  73932. -0.3577, -0.5301, -0.4358,
  73933. -0.3169, 0.1063, 0.0158,
  73934. 0.0103, -0.5869, 0.0046,
  73935. -0.0897, -0.4940, 0.3287,
  73936. 0.7119, -0.0154, -0.0918,
  73937. -0.0533, 0.0596, -0.5411,
  73938. 0.0352, -0.0631, 0.5460,
  73939. -0.4776, 0.2847, -0.0271
  73940. ];
  73941. var samplesFactor = 1.0 / numSamples;
  73942. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73943. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73944. "area", "fallOff", "base", "range", "viewport"
  73945. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73946. this._ssaoPostProcess.onApply = function (effect) {
  73947. if (_this._firstUpdate) {
  73948. effect.setArray3("sampleSphere", sampleSphere);
  73949. effect.setFloat("samplesFactor", samplesFactor);
  73950. effect.setFloat("randTextureTiles", 4.0);
  73951. }
  73952. effect.setFloat("totalStrength", _this.totalStrength);
  73953. effect.setFloat("radius", _this.radius);
  73954. effect.setFloat("area", _this.area);
  73955. effect.setFloat("fallOff", _this.fallOff);
  73956. effect.setFloat("base", _this.base);
  73957. effect.setTexture("textureSampler", _this._depthTexture);
  73958. effect.setTexture("randomSampler", _this._randomTexture);
  73959. };
  73960. };
  73961. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73962. var _this = this;
  73963. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73964. this._ssaoCombinePostProcess.onApply = function (effect) {
  73965. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73966. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73967. };
  73968. };
  73969. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73970. var size = 512;
  73971. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73972. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73973. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73974. var context = this._randomTexture.getContext();
  73975. var rand = function (min, max) {
  73976. return Math.random() * (max - min) + min;
  73977. };
  73978. var randVector = BABYLON.Vector3.Zero();
  73979. for (var x = 0; x < size; x++) {
  73980. for (var y = 0; y < size; y++) {
  73981. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73982. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73983. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73984. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73985. context.fillRect(x, y, 1, 1);
  73986. }
  73987. }
  73988. this._randomTexture.update(false);
  73989. };
  73990. __decorate([
  73991. BABYLON.serialize()
  73992. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73993. __decorate([
  73994. BABYLON.serialize()
  73995. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73996. __decorate([
  73997. BABYLON.serialize()
  73998. ], SSAORenderingPipeline.prototype, "area", void 0);
  73999. __decorate([
  74000. BABYLON.serialize()
  74001. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  74002. __decorate([
  74003. BABYLON.serialize()
  74004. ], SSAORenderingPipeline.prototype, "base", void 0);
  74005. return SSAORenderingPipeline;
  74006. }(BABYLON.PostProcessRenderPipeline));
  74007. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  74008. })(BABYLON || (BABYLON = {}));
  74009. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  74010. var BABYLON;
  74011. (function (BABYLON) {
  74012. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  74013. __extends(SSAO2RenderingPipeline, _super);
  74014. /**
  74015. * @constructor
  74016. * @param {string} name - The rendering pipeline name
  74017. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74018. * @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 }
  74019. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74020. */
  74021. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  74022. var _this = _super.call(this, scene.getEngine(), name) || this;
  74023. // Members
  74024. /**
  74025. * The PassPostProcess id in the pipeline that contains the original scene color
  74026. */
  74027. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74028. /**
  74029. * The SSAO PostProcess id in the pipeline
  74030. */
  74031. _this.SSAORenderEffect = "SSAORenderEffect";
  74032. /**
  74033. * The horizontal blur PostProcess id in the pipeline
  74034. */
  74035. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74036. /**
  74037. * The vertical blur PostProcess id in the pipeline
  74038. */
  74039. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74040. /**
  74041. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74042. */
  74043. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74044. /**
  74045. * The output strength of the SSAO post-process. Default value is 1.0.
  74046. */
  74047. _this.totalStrength = 1.0;
  74048. /**
  74049. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  74050. */
  74051. _this.maxZ = 100.0;
  74052. /**
  74053. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  74054. */
  74055. _this.minZAspect = 0.2;
  74056. /**
  74057. * Number of samples used for the SSAO calculations. Default value is 8
  74058. */
  74059. _this._samples = 8;
  74060. /**
  74061. * Are we using bilateral blur ?
  74062. */
  74063. _this._expensiveBlur = true;
  74064. /**
  74065. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  74066. */
  74067. _this.radius = 2.0;
  74068. /**
  74069. * The base color of the SSAO post-process
  74070. * The final result is "base + ssao" between [0, 1]
  74071. */
  74072. _this.base = 0.1;
  74073. _this._firstUpdate = true;
  74074. _this._scene = scene;
  74075. _this._ratio = ratio;
  74076. if (!_this.isSupported) {
  74077. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  74078. return _this;
  74079. }
  74080. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  74081. var blurRatio = _this._ratio.blurRatio || ratio;
  74082. // Set up assets
  74083. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  74084. _this._createRandomTexture();
  74085. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  74086. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  74087. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74088. _this._createSSAOPostProcess(1.0);
  74089. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  74090. _this._createSSAOCombinePostProcess(blurRatio);
  74091. // Set up pipeline
  74092. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74093. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74094. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74095. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74096. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74097. // Finish
  74098. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74099. if (cameras)
  74100. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74101. return _this;
  74102. }
  74103. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74104. get: function () {
  74105. return this._samples;
  74106. },
  74107. set: function (n) {
  74108. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74109. this._samples = n;
  74110. this._sampleSphere = this._generateHemisphere();
  74111. this._firstUpdate = true;
  74112. },
  74113. enumerable: true,
  74114. configurable: true
  74115. });
  74116. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74117. get: function () {
  74118. return this._expensiveBlur;
  74119. },
  74120. set: function (b) {
  74121. 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"]);
  74122. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74123. this._expensiveBlur = b;
  74124. this._firstUpdate = true;
  74125. },
  74126. enumerable: true,
  74127. configurable: true
  74128. });
  74129. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74130. /**
  74131. * Support test.
  74132. */
  74133. get: function () {
  74134. var engine = BABYLON.Engine.LastCreatedEngine;
  74135. if (!engine) {
  74136. return false;
  74137. }
  74138. return engine.getCaps().drawBuffersExtension;
  74139. },
  74140. enumerable: true,
  74141. configurable: true
  74142. });
  74143. // Public Methods
  74144. /**
  74145. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74146. */
  74147. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74148. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74149. for (var i = 0; i < this._scene.cameras.length; i++) {
  74150. var camera = this._scene.cameras[i];
  74151. this._originalColorPostProcess.dispose(camera);
  74152. this._ssaoPostProcess.dispose(camera);
  74153. this._blurHPostProcess.dispose(camera);
  74154. this._blurVPostProcess.dispose(camera);
  74155. this._ssaoCombinePostProcess.dispose(camera);
  74156. }
  74157. this._randomTexture.dispose();
  74158. if (disableGeometryBufferRenderer)
  74159. this._scene.disableGeometryBufferRenderer();
  74160. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74161. _super.prototype.dispose.call(this);
  74162. };
  74163. // Private Methods
  74164. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74165. var _this = this;
  74166. this._samplerOffsets = [];
  74167. var expensive = this.expensiveBlur;
  74168. for (var i = -8; i < 8; i++) {
  74169. this._samplerOffsets.push(i * 2 + 0.5);
  74170. }
  74171. 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");
  74172. this._blurHPostProcess.onApply = function (effect) {
  74173. if (!_this._scene.activeCamera) {
  74174. return;
  74175. }
  74176. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74177. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74178. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74179. effect.setFloat("radius", _this.radius);
  74180. effect.setTexture("depthSampler", _this._depthTexture);
  74181. if (_this._firstUpdate) {
  74182. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74183. }
  74184. };
  74185. 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");
  74186. this._blurVPostProcess.onApply = function (effect) {
  74187. if (!_this._scene.activeCamera) {
  74188. return;
  74189. }
  74190. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74191. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74192. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74193. effect.setFloat("radius", _this.radius);
  74194. effect.setTexture("depthSampler", _this._depthTexture);
  74195. if (_this._firstUpdate) {
  74196. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74197. _this._firstUpdate = false;
  74198. }
  74199. };
  74200. };
  74201. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74202. this._firstUpdate = true;
  74203. _super.prototype._rebuild.call(this);
  74204. };
  74205. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74206. var numSamples = this.samples;
  74207. var result = [];
  74208. var vector, scale;
  74209. var rand = function (min, max) {
  74210. return Math.random() * (max - min) + min;
  74211. };
  74212. var i = 0;
  74213. while (i < numSamples) {
  74214. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74215. vector.normalize();
  74216. scale = i / numSamples;
  74217. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74218. vector.scaleInPlace(scale);
  74219. result.push(vector.x, vector.y, vector.z);
  74220. i++;
  74221. }
  74222. return result;
  74223. };
  74224. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74225. var _this = this;
  74226. var numSamples = this.samples;
  74227. this._sampleSphere = this._generateHemisphere();
  74228. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74229. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74230. "base", "range", "projection", "near", "far", "texelSize",
  74231. "xViewport", "yViewport", "maxZ", "minZAspect"
  74232. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74233. this._ssaoPostProcess.onApply = function (effect) {
  74234. if (_this._firstUpdate) {
  74235. effect.setArray3("sampleSphere", _this._sampleSphere);
  74236. effect.setFloat("randTextureTiles", 4.0);
  74237. }
  74238. if (!_this._scene.activeCamera) {
  74239. return;
  74240. }
  74241. effect.setFloat("samplesFactor", 1 / _this.samples);
  74242. effect.setFloat("totalStrength", _this.totalStrength);
  74243. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74244. effect.setFloat("radius", _this.radius);
  74245. effect.setFloat("maxZ", _this.maxZ);
  74246. effect.setFloat("minZAspect", _this.minZAspect);
  74247. effect.setFloat("base", _this.base);
  74248. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74249. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74250. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74251. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74252. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74253. effect.setTexture("textureSampler", _this._depthTexture);
  74254. effect.setTexture("normalSampler", _this._normalTexture);
  74255. effect.setTexture("randomSampler", _this._randomTexture);
  74256. };
  74257. };
  74258. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74259. var _this = this;
  74260. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74261. this._ssaoCombinePostProcess.onApply = function (effect) {
  74262. var viewport = _this._scene.activeCamera.viewport;
  74263. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74264. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74265. };
  74266. };
  74267. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74268. var size = 512;
  74269. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74270. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74271. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74272. var context = this._randomTexture.getContext();
  74273. var rand = function (min, max) {
  74274. return Math.random() * (max - min) + min;
  74275. };
  74276. var randVector = BABYLON.Vector3.Zero();
  74277. for (var x = 0; x < size; x++) {
  74278. for (var y = 0; y < size; y++) {
  74279. randVector.x = rand(0.0, 1.0);
  74280. randVector.y = rand(0.0, 1.0);
  74281. randVector.z = 0.0;
  74282. randVector.normalize();
  74283. randVector.scaleInPlace(255);
  74284. randVector.x = Math.floor(randVector.x);
  74285. randVector.y = Math.floor(randVector.y);
  74286. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74287. context.fillRect(x, y, 1, 1);
  74288. }
  74289. }
  74290. this._randomTexture.update(false);
  74291. };
  74292. /**
  74293. * Serialize the rendering pipeline (Used when exporting)
  74294. * @returns the serialized object
  74295. */
  74296. SSAO2RenderingPipeline.prototype.serialize = function () {
  74297. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74298. serializationObject.customType = "SSAO2RenderingPipeline";
  74299. return serializationObject;
  74300. };
  74301. /**
  74302. * Parse the serialized pipeline
  74303. * @param source Source pipeline.
  74304. * @param scene The scene to load the pipeline to.
  74305. * @param rootUrl The URL of the serialized pipeline.
  74306. * @returns An instantiated pipeline from the serialized object.
  74307. */
  74308. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74309. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74310. };
  74311. __decorate([
  74312. BABYLON.serialize()
  74313. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74314. __decorate([
  74315. BABYLON.serialize()
  74316. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74317. __decorate([
  74318. BABYLON.serialize()
  74319. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74320. __decorate([
  74321. BABYLON.serialize("samples")
  74322. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74323. __decorate([
  74324. BABYLON.serialize()
  74325. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74326. __decorate([
  74327. BABYLON.serialize("expensiveBlur")
  74328. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74329. __decorate([
  74330. BABYLON.serialize()
  74331. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74332. __decorate([
  74333. BABYLON.serialize()
  74334. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74335. return SSAO2RenderingPipeline;
  74336. }(BABYLON.PostProcessRenderPipeline));
  74337. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74338. })(BABYLON || (BABYLON = {}));
  74339. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74340. // BABYLON.JS Chromatic Aberration GLSL Shader
  74341. // Author: Olivier Guyot
  74342. // Separates very slightly R, G and B colors on the edges of the screen
  74343. // Inspired by Francois Tarlier & Martins Upitis
  74344. var BABYLON;
  74345. (function (BABYLON) {
  74346. var LensRenderingPipeline = /** @class */ (function (_super) {
  74347. __extends(LensRenderingPipeline, _super);
  74348. /**
  74349. * @constructor
  74350. *
  74351. * Effect parameters are as follow:
  74352. * {
  74353. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74354. * edge_blur: number; // from 0 to x (1 for realism)
  74355. * distortion: number; // from 0 to x (1 for realism)
  74356. * grain_amount: number; // from 0 to 1
  74357. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74358. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74359. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74360. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74361. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74362. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74363. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74364. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74365. * }
  74366. * Note: if an effect parameter is unset, effect is disabled
  74367. *
  74368. * @param {string} name - The rendering pipeline name
  74369. * @param {object} parameters - An object containing all parameters (see above)
  74370. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74371. * @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)
  74372. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74373. */
  74374. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74375. if (ratio === void 0) { ratio = 1.0; }
  74376. var _this = _super.call(this, scene.getEngine(), name) || this;
  74377. // Lens effects can be of the following:
  74378. // - chromatic aberration (slight shift of RGB colors)
  74379. // - blur on the edge of the lens
  74380. // - lens distortion
  74381. // - depth-of-field blur & highlights enhancing
  74382. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74383. // - grain effect (noise or custom texture)
  74384. // Two additional texture samplers are needed:
  74385. // - depth map (for depth-of-field)
  74386. // - grain texture
  74387. /**
  74388. * The chromatic aberration PostProcess id in the pipeline
  74389. */
  74390. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74391. /**
  74392. * The highlights enhancing PostProcess id in the pipeline
  74393. */
  74394. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74395. /**
  74396. * The depth-of-field PostProcess id in the pipeline
  74397. */
  74398. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74399. _this._scene = scene;
  74400. // Fetch texture samplers
  74401. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74402. if (parameters.grain_texture) {
  74403. _this._grainTexture = parameters.grain_texture;
  74404. }
  74405. else {
  74406. _this._createGrainTexture();
  74407. }
  74408. // save parameters
  74409. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74410. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74411. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74412. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74413. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74414. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74415. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74416. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74417. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74418. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74419. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74420. // Create effects
  74421. _this._createChromaticAberrationPostProcess(ratio);
  74422. _this._createHighlightsPostProcess(ratio);
  74423. _this._createDepthOfFieldPostProcess(ratio / 4);
  74424. // Set up pipeline
  74425. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74426. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74427. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74428. if (_this._highlightsGain === -1) {
  74429. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74430. }
  74431. // Finish
  74432. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74433. if (cameras) {
  74434. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74435. }
  74436. return _this;
  74437. }
  74438. // public methods (self explanatory)
  74439. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74440. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74441. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74442. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74443. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74444. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74445. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74446. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74447. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74448. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74449. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74450. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74451. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74452. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74453. };
  74454. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74455. this._highlightsPostProcess.updateEffect();
  74456. };
  74457. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74458. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74459. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74460. this._highlightsGain = amount;
  74461. };
  74462. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74463. if (this._highlightsGain === -1) {
  74464. this._highlightsGain = 1.0;
  74465. }
  74466. this._highlightsThreshold = amount;
  74467. };
  74468. LensRenderingPipeline.prototype.disableHighlights = function () {
  74469. this._highlightsGain = -1;
  74470. };
  74471. /**
  74472. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74473. */
  74474. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74475. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74476. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74477. this._chromaticAberrationPostProcess = null;
  74478. this._highlightsPostProcess = null;
  74479. this._depthOfFieldPostProcess = null;
  74480. this._grainTexture.dispose();
  74481. if (disableDepthRender)
  74482. this._scene.disableDepthRenderer();
  74483. };
  74484. // colors shifting and distortion
  74485. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74486. var _this = this;
  74487. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74488. [], // samplers
  74489. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74490. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74491. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74492. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74493. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74494. effect.setFloat('radialIntensity', 1);
  74495. effect.setFloat2('direction', 17, 17);
  74496. effect.setFloat2('centerPosition', 0.5, 0.5);
  74497. };
  74498. };
  74499. // highlights enhancing
  74500. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74501. var _this = this;
  74502. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74503. [], // samplers
  74504. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74505. this._highlightsPostProcess.onApply = function (effect) {
  74506. effect.setFloat('gain', _this._highlightsGain);
  74507. effect.setFloat('threshold', _this._highlightsThreshold);
  74508. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74509. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74510. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74511. };
  74512. };
  74513. // colors shifting and distortion
  74514. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74515. var _this = this;
  74516. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74517. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74518. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74519. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74520. this._depthOfFieldPostProcess.onApply = function (effect) {
  74521. effect.setTexture("depthSampler", _this._depthTexture);
  74522. effect.setTexture("grainSampler", _this._grainTexture);
  74523. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74524. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74525. effect.setFloat('grain_amount', _this._grainAmount);
  74526. effect.setBool('blur_noise', _this._blurNoise);
  74527. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74528. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74529. effect.setFloat('distortion', _this._distortion);
  74530. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74531. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74532. effect.setFloat('aperture', _this._dofAperture);
  74533. effect.setFloat('darken', _this._dofDarken);
  74534. effect.setFloat('edge_blur', _this._edgeBlur);
  74535. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74536. if (_this._scene.activeCamera) {
  74537. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74538. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74539. }
  74540. };
  74541. };
  74542. // creates a black and white random noise texture, 512x512
  74543. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74544. var size = 512;
  74545. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74546. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74547. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74548. var context = this._grainTexture.getContext();
  74549. var rand = function (min, max) {
  74550. return Math.random() * (max - min) + min;
  74551. };
  74552. var value;
  74553. for (var x = 0; x < size; x++) {
  74554. for (var y = 0; y < size; y++) {
  74555. value = Math.floor(rand(0.42, 0.58) * 255);
  74556. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74557. context.fillRect(x, y, 1, 1);
  74558. }
  74559. }
  74560. this._grainTexture.update(false);
  74561. };
  74562. return LensRenderingPipeline;
  74563. }(BABYLON.PostProcessRenderPipeline));
  74564. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74565. })(BABYLON || (BABYLON = {}));
  74566. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74567. var BABYLON;
  74568. (function (BABYLON) {
  74569. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74570. __extends(StandardRenderingPipeline, _super);
  74571. /**
  74572. * @constructor
  74573. * @param {string} name - The rendering pipeline name
  74574. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74575. * @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)
  74576. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74577. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74578. */
  74579. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74580. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74581. var _this = _super.call(this, scene.getEngine(), name) || this;
  74582. _this.downSampleX4PostProcess = null;
  74583. _this.brightPassPostProcess = null;
  74584. _this.blurHPostProcesses = [];
  74585. _this.blurVPostProcesses = [];
  74586. _this.textureAdderPostProcess = null;
  74587. _this.volumetricLightPostProcess = null;
  74588. _this.volumetricLightSmoothXPostProcess = null;
  74589. _this.volumetricLightSmoothYPostProcess = null;
  74590. _this.volumetricLightMergePostProces = null;
  74591. _this.volumetricLightFinalPostProcess = null;
  74592. _this.luminancePostProcess = null;
  74593. _this.luminanceDownSamplePostProcesses = [];
  74594. _this.hdrPostProcess = null;
  74595. _this.textureAdderFinalPostProcess = null;
  74596. _this.lensFlareFinalPostProcess = null;
  74597. _this.hdrFinalPostProcess = null;
  74598. _this.lensFlarePostProcess = null;
  74599. _this.lensFlareComposePostProcess = null;
  74600. _this.motionBlurPostProcess = null;
  74601. _this.depthOfFieldPostProcess = null;
  74602. // Values
  74603. _this.brightThreshold = 1.0;
  74604. _this.blurWidth = 512.0;
  74605. _this.horizontalBlur = false;
  74606. _this.exposure = 1.0;
  74607. _this.lensTexture = null;
  74608. _this.volumetricLightCoefficient = 0.2;
  74609. _this.volumetricLightPower = 4.0;
  74610. _this.volumetricLightBlurScale = 64.0;
  74611. _this.sourceLight = null;
  74612. _this.hdrMinimumLuminance = 1.0;
  74613. _this.hdrDecreaseRate = 0.5;
  74614. _this.hdrIncreaseRate = 0.5;
  74615. _this.lensColorTexture = null;
  74616. _this.lensFlareStrength = 20.0;
  74617. _this.lensFlareGhostDispersal = 1.4;
  74618. _this.lensFlareHaloWidth = 0.7;
  74619. _this.lensFlareDistortionStrength = 16.0;
  74620. _this.lensStarTexture = null;
  74621. _this.lensFlareDirtTexture = null;
  74622. _this.depthOfFieldDistance = 10.0;
  74623. _this.depthOfFieldBlurWidth = 64.0;
  74624. _this.motionStrength = 1.0;
  74625. // IAnimatable
  74626. _this.animations = [];
  74627. _this._currentDepthOfFieldSource = null;
  74628. _this._hdrCurrentLuminance = 1.0;
  74629. // Getters and setters
  74630. _this._bloomEnabled = true;
  74631. _this._depthOfFieldEnabled = false;
  74632. _this._vlsEnabled = false;
  74633. _this._lensFlareEnabled = false;
  74634. _this._hdrEnabled = false;
  74635. _this._motionBlurEnabled = false;
  74636. _this._motionBlurSamples = 64.0;
  74637. _this._volumetricLightStepsCount = 50.0;
  74638. _this._cameras = cameras || [];
  74639. // Initialize
  74640. _this._scene = scene;
  74641. _this._basePostProcess = originalPostProcess;
  74642. _this._ratio = ratio;
  74643. // Misc
  74644. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74645. // Finish
  74646. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74647. _this._buildPipeline();
  74648. return _this;
  74649. }
  74650. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74651. get: function () {
  74652. return this._bloomEnabled;
  74653. },
  74654. set: function (enabled) {
  74655. if (this._bloomEnabled === enabled) {
  74656. return;
  74657. }
  74658. this._bloomEnabled = enabled;
  74659. this._buildPipeline();
  74660. },
  74661. enumerable: true,
  74662. configurable: true
  74663. });
  74664. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74665. get: function () {
  74666. return this._depthOfFieldEnabled;
  74667. },
  74668. set: function (enabled) {
  74669. if (this._depthOfFieldEnabled === enabled) {
  74670. return;
  74671. }
  74672. this._depthOfFieldEnabled = enabled;
  74673. this._buildPipeline();
  74674. },
  74675. enumerable: true,
  74676. configurable: true
  74677. });
  74678. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74679. get: function () {
  74680. return this._lensFlareEnabled;
  74681. },
  74682. set: function (enabled) {
  74683. if (this._lensFlareEnabled === enabled) {
  74684. return;
  74685. }
  74686. this._lensFlareEnabled = enabled;
  74687. this._buildPipeline();
  74688. },
  74689. enumerable: true,
  74690. configurable: true
  74691. });
  74692. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74693. get: function () {
  74694. return this._hdrEnabled;
  74695. },
  74696. set: function (enabled) {
  74697. if (this._hdrEnabled === enabled) {
  74698. return;
  74699. }
  74700. this._hdrEnabled = enabled;
  74701. this._buildPipeline();
  74702. },
  74703. enumerable: true,
  74704. configurable: true
  74705. });
  74706. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74707. get: function () {
  74708. return this._vlsEnabled;
  74709. },
  74710. set: function (enabled) {
  74711. if (this._vlsEnabled === enabled) {
  74712. return;
  74713. }
  74714. if (enabled) {
  74715. var geometry = this._scene.enableGeometryBufferRenderer();
  74716. if (!geometry) {
  74717. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74718. return;
  74719. }
  74720. }
  74721. this._vlsEnabled = enabled;
  74722. this._buildPipeline();
  74723. },
  74724. enumerable: true,
  74725. configurable: true
  74726. });
  74727. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74728. get: function () {
  74729. return this._motionBlurEnabled;
  74730. },
  74731. set: function (enabled) {
  74732. if (this._motionBlurEnabled === enabled) {
  74733. return;
  74734. }
  74735. this._motionBlurEnabled = enabled;
  74736. this._buildPipeline();
  74737. },
  74738. enumerable: true,
  74739. configurable: true
  74740. });
  74741. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74742. get: function () {
  74743. return this._volumetricLightStepsCount;
  74744. },
  74745. set: function (count) {
  74746. if (this.volumetricLightPostProcess) {
  74747. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74748. }
  74749. this._volumetricLightStepsCount = count;
  74750. },
  74751. enumerable: true,
  74752. configurable: true
  74753. });
  74754. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74755. get: function () {
  74756. return this._motionBlurSamples;
  74757. },
  74758. set: function (samples) {
  74759. if (this.motionBlurPostProcess) {
  74760. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74761. }
  74762. this._motionBlurSamples = samples;
  74763. },
  74764. enumerable: true,
  74765. configurable: true
  74766. });
  74767. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74768. var _this = this;
  74769. var ratio = this._ratio;
  74770. var scene = this._scene;
  74771. this._disposePostProcesses();
  74772. this._reset();
  74773. // Create pass post-process
  74774. if (!this._basePostProcess) {
  74775. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74776. this.originalPostProcess.onApply = function (effect) {
  74777. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74778. };
  74779. }
  74780. else {
  74781. this.originalPostProcess = this._basePostProcess;
  74782. }
  74783. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74784. this._currentDepthOfFieldSource = this.originalPostProcess;
  74785. if (this._bloomEnabled) {
  74786. // Create down sample X4 post-process
  74787. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74788. // Create bright pass post-process
  74789. this._createBrightPassPostProcess(scene, ratio / 2);
  74790. // Create gaussian blur post-processes (down sampling blurs)
  74791. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74792. // Create texture adder post-process
  74793. this._createTextureAdderPostProcess(scene, ratio);
  74794. // Create depth-of-field source post-process
  74795. 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);
  74796. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74797. }
  74798. if (this._vlsEnabled) {
  74799. // Create volumetric light
  74800. this._createVolumetricLightPostProcess(scene, ratio);
  74801. // Create volumetric light final post-process
  74802. 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);
  74803. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74804. }
  74805. if (this._lensFlareEnabled) {
  74806. // Create lens flare post-process
  74807. this._createLensFlarePostProcess(scene, ratio);
  74808. // Create depth-of-field source post-process post lens-flare and disable it now
  74809. 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);
  74810. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74811. }
  74812. if (this._hdrEnabled) {
  74813. // Create luminance
  74814. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74815. // Create HDR
  74816. this._createHdrPostProcess(scene, ratio);
  74817. // Create depth-of-field source post-process post hdr and disable it now
  74818. 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);
  74819. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74820. }
  74821. if (this._depthOfFieldEnabled) {
  74822. // Create gaussian blur used by depth-of-field
  74823. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74824. // Create depth-of-field post-process
  74825. this._createDepthOfFieldPostProcess(scene, ratio);
  74826. }
  74827. if (this._motionBlurEnabled) {
  74828. // Create motion blur post-process
  74829. this._createMotionBlurPostProcess(scene, ratio);
  74830. }
  74831. if (this._cameras !== null) {
  74832. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74833. }
  74834. };
  74835. // Down Sample X4 Post-Processs
  74836. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74837. var _this = this;
  74838. var downSampleX4Offsets = new Array(32);
  74839. 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);
  74840. this.downSampleX4PostProcess.onApply = function (effect) {
  74841. var id = 0;
  74842. var width = _this.downSampleX4PostProcess.width;
  74843. var height = _this.downSampleX4PostProcess.height;
  74844. for (var i = -2; i < 2; i++) {
  74845. for (var j = -2; j < 2; j++) {
  74846. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74847. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74848. id += 2;
  74849. }
  74850. }
  74851. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74852. };
  74853. // Add to pipeline
  74854. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74855. };
  74856. // Brightpass Post-Process
  74857. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74858. var _this = this;
  74859. var brightOffsets = new Array(8);
  74860. 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);
  74861. this.brightPassPostProcess.onApply = function (effect) {
  74862. var sU = (1.0 / _this.brightPassPostProcess.width);
  74863. var sV = (1.0 / _this.brightPassPostProcess.height);
  74864. brightOffsets[0] = -0.5 * sU;
  74865. brightOffsets[1] = 0.5 * sV;
  74866. brightOffsets[2] = 0.5 * sU;
  74867. brightOffsets[3] = 0.5 * sV;
  74868. brightOffsets[4] = -0.5 * sU;
  74869. brightOffsets[5] = -0.5 * sV;
  74870. brightOffsets[6] = 0.5 * sU;
  74871. brightOffsets[7] = -0.5 * sV;
  74872. effect.setArray2("dsOffsets", brightOffsets);
  74873. effect.setFloat("brightThreshold", _this.brightThreshold);
  74874. };
  74875. // Add to pipeline
  74876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74877. };
  74878. // Create blur H&V post-processes
  74879. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74880. var _this = this;
  74881. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74882. var engine = scene.getEngine();
  74883. 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);
  74884. 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);
  74885. blurX.onActivateObservable.add(function () {
  74886. var dw = blurX.width / engine.getRenderWidth();
  74887. blurX.kernel = _this[blurWidthKey] * dw;
  74888. });
  74889. blurY.onActivateObservable.add(function () {
  74890. var dw = blurY.height / engine.getRenderHeight();
  74891. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74892. });
  74893. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74894. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74895. this.blurHPostProcesses.push(blurX);
  74896. this.blurVPostProcesses.push(blurY);
  74897. };
  74898. // Create texture adder post-process
  74899. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74900. var _this = this;
  74901. 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);
  74902. this.textureAdderPostProcess.onApply = function (effect) {
  74903. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74904. effect.setTexture("lensSampler", _this.lensTexture);
  74905. effect.setFloat("exposure", _this.exposure);
  74906. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74907. };
  74908. // Add to pipeline
  74909. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74910. };
  74911. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74912. var _this = this;
  74913. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74914. geometryRenderer.enablePosition = true;
  74915. var geometry = geometryRenderer.getGBuffer();
  74916. // Base post-process
  74917. 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));
  74918. var depthValues = BABYLON.Vector2.Zero();
  74919. this.volumetricLightPostProcess.onApply = function (effect) {
  74920. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74921. var generator = _this.sourceLight.getShadowGenerator();
  74922. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74923. effect.setTexture("positionSampler", geometry.textures[2]);
  74924. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74925. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74926. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74927. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74928. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74929. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74930. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74931. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74932. effect.setVector2("depthValues", depthValues);
  74933. }
  74934. };
  74935. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74936. // Smooth
  74937. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74938. // Merge
  74939. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74940. this.volumetricLightMergePostProces.onApply = function (effect) {
  74941. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74942. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74943. };
  74944. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74945. };
  74946. // Create luminance
  74947. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74948. var _this = this;
  74949. // Create luminance
  74950. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74951. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74952. var offsets = [];
  74953. this.luminancePostProcess.onApply = function (effect) {
  74954. var sU = (1.0 / _this.luminancePostProcess.width);
  74955. var sV = (1.0 / _this.luminancePostProcess.height);
  74956. offsets[0] = -0.5 * sU;
  74957. offsets[1] = 0.5 * sV;
  74958. offsets[2] = 0.5 * sU;
  74959. offsets[3] = 0.5 * sV;
  74960. offsets[4] = -0.5 * sU;
  74961. offsets[5] = -0.5 * sV;
  74962. offsets[6] = 0.5 * sU;
  74963. offsets[7] = -0.5 * sV;
  74964. effect.setArray2("lumOffsets", offsets);
  74965. };
  74966. // Add to pipeline
  74967. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74968. // Create down sample luminance
  74969. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74970. var size = Math.pow(3, i);
  74971. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74972. if (i === 0) {
  74973. defines += "#define FINAL_DOWN_SAMPLER";
  74974. }
  74975. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74976. this.luminanceDownSamplePostProcesses.push(postProcess);
  74977. }
  74978. // Create callbacks and add effects
  74979. var lastLuminance = this.luminancePostProcess;
  74980. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74981. var downSampleOffsets = new Array(18);
  74982. pp.onApply = function (effect) {
  74983. if (!lastLuminance) {
  74984. return;
  74985. }
  74986. var id = 0;
  74987. for (var x = -1; x < 2; x++) {
  74988. for (var y = -1; y < 2; y++) {
  74989. downSampleOffsets[id] = x / lastLuminance.width;
  74990. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74991. id += 2;
  74992. }
  74993. }
  74994. effect.setArray2("dsOffsets", downSampleOffsets);
  74995. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74996. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74997. lastLuminance = _this.luminancePostProcess;
  74998. }
  74999. else {
  75000. lastLuminance = pp;
  75001. }
  75002. };
  75003. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75004. pp.onAfterRender = function (effect) {
  75005. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  75006. 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);
  75007. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  75008. };
  75009. }
  75010. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  75011. });
  75012. };
  75013. // Create HDR post-process
  75014. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  75015. var _this = this;
  75016. 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);
  75017. var outputLiminance = 1;
  75018. var time = 0;
  75019. var lastTime = 0;
  75020. this.hdrPostProcess.onApply = function (effect) {
  75021. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  75022. time += scene.getEngine().getDeltaTime();
  75023. if (outputLiminance < 0) {
  75024. outputLiminance = _this._hdrCurrentLuminance;
  75025. }
  75026. else {
  75027. var dt = (lastTime - time) / 1000.0;
  75028. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  75029. outputLiminance += _this.hdrDecreaseRate * dt;
  75030. }
  75031. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  75032. outputLiminance -= _this.hdrIncreaseRate * dt;
  75033. }
  75034. else {
  75035. outputLiminance = _this._hdrCurrentLuminance;
  75036. }
  75037. }
  75038. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  75039. effect.setFloat("averageLuminance", outputLiminance);
  75040. lastTime = time;
  75041. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  75042. };
  75043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  75044. };
  75045. // Create lens flare post-process
  75046. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  75047. var _this = this;
  75048. 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);
  75049. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  75050. this._createBlurPostProcesses(scene, ratio / 4, 2);
  75051. 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);
  75052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  75053. var resolution = new BABYLON.Vector2(0, 0);
  75054. // Lens flare
  75055. this.lensFlarePostProcess.onApply = function (effect) {
  75056. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  75057. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  75058. effect.setFloat("strength", _this.lensFlareStrength);
  75059. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  75060. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  75061. // Shift
  75062. resolution.x = _this.lensFlarePostProcess.width;
  75063. resolution.y = _this.lensFlarePostProcess.height;
  75064. effect.setVector2("resolution", resolution);
  75065. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  75066. };
  75067. // Compose
  75068. 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);
  75069. 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);
  75070. this.lensFlareComposePostProcess.onApply = function (effect) {
  75071. if (!_this._scene.activeCamera) {
  75072. return;
  75073. }
  75074. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75075. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  75076. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  75077. // Lens start rotation matrix
  75078. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  75079. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  75080. 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));
  75081. camRot *= 4.0;
  75082. 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);
  75083. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  75084. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  75085. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  75086. };
  75087. };
  75088. // Create depth-of-field post-process
  75089. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  75090. var _this = this;
  75091. 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);
  75092. this.depthOfFieldPostProcess.onApply = function (effect) {
  75093. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75094. effect.setTexture("depthSampler", _this._getDepthTexture());
  75095. effect.setFloat("distance", _this.depthOfFieldDistance);
  75096. };
  75097. // Add to pipeline
  75098. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75099. };
  75100. // Create motion blur post-process
  75101. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75102. var _this = this;
  75103. 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);
  75104. var motionScale = 0;
  75105. var prevViewProjection = BABYLON.Matrix.Identity();
  75106. var invViewProjection = BABYLON.Matrix.Identity();
  75107. var viewProjection = BABYLON.Matrix.Identity();
  75108. var screenSize = BABYLON.Vector2.Zero();
  75109. this.motionBlurPostProcess.onApply = function (effect) {
  75110. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75111. viewProjection.invertToRef(invViewProjection);
  75112. effect.setMatrix("inverseViewProjection", invViewProjection);
  75113. effect.setMatrix("prevViewProjection", prevViewProjection);
  75114. prevViewProjection = viewProjection;
  75115. screenSize.x = _this.motionBlurPostProcess.width;
  75116. screenSize.y = _this.motionBlurPostProcess.height;
  75117. effect.setVector2("screenSize", screenSize);
  75118. motionScale = scene.getEngine().getFps() / 60.0;
  75119. effect.setFloat("motionScale", motionScale);
  75120. effect.setFloat("motionStrength", _this.motionStrength);
  75121. effect.setTexture("depthSampler", _this._getDepthTexture());
  75122. };
  75123. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75124. };
  75125. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75126. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75127. var renderer = this._scene.enableGeometryBufferRenderer();
  75128. return renderer.getGBuffer().textures[0];
  75129. }
  75130. return this._scene.enableDepthRenderer().getDepthMap();
  75131. };
  75132. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75133. for (var i = 0; i < this._cameras.length; i++) {
  75134. var camera = this._cameras[i];
  75135. if (this.originalPostProcess) {
  75136. this.originalPostProcess.dispose(camera);
  75137. }
  75138. if (this.downSampleX4PostProcess) {
  75139. this.downSampleX4PostProcess.dispose(camera);
  75140. }
  75141. if (this.brightPassPostProcess) {
  75142. this.brightPassPostProcess.dispose(camera);
  75143. }
  75144. if (this.textureAdderPostProcess) {
  75145. this.textureAdderPostProcess.dispose(camera);
  75146. }
  75147. if (this.textureAdderFinalPostProcess) {
  75148. this.textureAdderFinalPostProcess.dispose(camera);
  75149. }
  75150. if (this.volumetricLightPostProcess) {
  75151. this.volumetricLightPostProcess.dispose(camera);
  75152. }
  75153. if (this.volumetricLightSmoothXPostProcess) {
  75154. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75155. }
  75156. if (this.volumetricLightSmoothYPostProcess) {
  75157. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75158. }
  75159. if (this.volumetricLightMergePostProces) {
  75160. this.volumetricLightMergePostProces.dispose(camera);
  75161. }
  75162. if (this.volumetricLightFinalPostProcess) {
  75163. this.volumetricLightFinalPostProcess.dispose(camera);
  75164. }
  75165. if (this.lensFlarePostProcess) {
  75166. this.lensFlarePostProcess.dispose(camera);
  75167. }
  75168. if (this.lensFlareComposePostProcess) {
  75169. this.lensFlareComposePostProcess.dispose(camera);
  75170. }
  75171. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75172. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75173. }
  75174. if (this.luminancePostProcess) {
  75175. this.luminancePostProcess.dispose(camera);
  75176. }
  75177. if (this.hdrPostProcess) {
  75178. this.hdrPostProcess.dispose(camera);
  75179. }
  75180. if (this.hdrFinalPostProcess) {
  75181. this.hdrFinalPostProcess.dispose(camera);
  75182. }
  75183. if (this.depthOfFieldPostProcess) {
  75184. this.depthOfFieldPostProcess.dispose(camera);
  75185. }
  75186. if (this.motionBlurPostProcess) {
  75187. this.motionBlurPostProcess.dispose(camera);
  75188. }
  75189. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75190. this.blurHPostProcesses[j].dispose(camera);
  75191. }
  75192. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75193. this.blurVPostProcesses[j].dispose(camera);
  75194. }
  75195. }
  75196. this.originalPostProcess = null;
  75197. this.downSampleX4PostProcess = null;
  75198. this.brightPassPostProcess = null;
  75199. this.textureAdderPostProcess = null;
  75200. this.textureAdderFinalPostProcess = null;
  75201. this.volumetricLightPostProcess = null;
  75202. this.volumetricLightSmoothXPostProcess = null;
  75203. this.volumetricLightSmoothYPostProcess = null;
  75204. this.volumetricLightMergePostProces = null;
  75205. this.volumetricLightFinalPostProcess = null;
  75206. this.lensFlarePostProcess = null;
  75207. this.lensFlareComposePostProcess = null;
  75208. this.luminancePostProcess = null;
  75209. this.hdrPostProcess = null;
  75210. this.hdrFinalPostProcess = null;
  75211. this.depthOfFieldPostProcess = null;
  75212. this.motionBlurPostProcess = null;
  75213. this.luminanceDownSamplePostProcesses = [];
  75214. this.blurHPostProcesses = [];
  75215. this.blurVPostProcesses = [];
  75216. };
  75217. /**
  75218. * Dispose of the pipeline and stop all post processes
  75219. */
  75220. StandardRenderingPipeline.prototype.dispose = function () {
  75221. this._disposePostProcesses();
  75222. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75223. _super.prototype.dispose.call(this);
  75224. };
  75225. /**
  75226. * Serialize the rendering pipeline (Used when exporting)
  75227. * @returns the serialized object
  75228. */
  75229. StandardRenderingPipeline.prototype.serialize = function () {
  75230. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75231. if (this.sourceLight) {
  75232. serializationObject.sourceLightId = this.sourceLight.id;
  75233. }
  75234. serializationObject.customType = "StandardRenderingPipeline";
  75235. return serializationObject;
  75236. };
  75237. /**
  75238. * Parse the serialized pipeline
  75239. * @param source Source pipeline.
  75240. * @param scene The scene to load the pipeline to.
  75241. * @param rootUrl The URL of the serialized pipeline.
  75242. * @returns An instantiated pipeline from the serialized object.
  75243. */
  75244. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75245. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75246. if (source.sourceLightId) {
  75247. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75248. }
  75249. return p;
  75250. };
  75251. // Luminance steps
  75252. StandardRenderingPipeline.LuminanceSteps = 6;
  75253. __decorate([
  75254. BABYLON.serialize()
  75255. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75256. __decorate([
  75257. BABYLON.serialize()
  75258. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75259. __decorate([
  75260. BABYLON.serialize()
  75261. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75262. __decorate([
  75263. BABYLON.serialize()
  75264. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75265. __decorate([
  75266. BABYLON.serializeAsTexture("lensTexture")
  75267. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75268. __decorate([
  75269. BABYLON.serialize()
  75270. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75271. __decorate([
  75272. BABYLON.serialize()
  75273. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75274. __decorate([
  75275. BABYLON.serialize()
  75276. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75277. __decorate([
  75278. BABYLON.serialize()
  75279. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75280. __decorate([
  75281. BABYLON.serialize()
  75282. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75283. __decorate([
  75284. BABYLON.serialize()
  75285. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75286. __decorate([
  75287. BABYLON.serializeAsTexture("lensColorTexture")
  75288. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75289. __decorate([
  75290. BABYLON.serialize()
  75291. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75292. __decorate([
  75293. BABYLON.serialize()
  75294. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75295. __decorate([
  75296. BABYLON.serialize()
  75297. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75298. __decorate([
  75299. BABYLON.serialize()
  75300. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75301. __decorate([
  75302. BABYLON.serializeAsTexture("lensStarTexture")
  75303. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75304. __decorate([
  75305. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75306. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75307. __decorate([
  75308. BABYLON.serialize()
  75309. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75310. __decorate([
  75311. BABYLON.serialize()
  75312. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75313. __decorate([
  75314. BABYLON.serialize()
  75315. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75316. __decorate([
  75317. BABYLON.serialize()
  75318. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75319. __decorate([
  75320. BABYLON.serialize()
  75321. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75322. __decorate([
  75323. BABYLON.serialize()
  75324. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75325. __decorate([
  75326. BABYLON.serialize()
  75327. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75328. __decorate([
  75329. BABYLON.serialize()
  75330. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75331. __decorate([
  75332. BABYLON.serialize()
  75333. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75334. __decorate([
  75335. BABYLON.serialize()
  75336. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75337. __decorate([
  75338. BABYLON.serialize()
  75339. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75340. __decorate([
  75341. BABYLON.serialize()
  75342. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75343. return StandardRenderingPipeline;
  75344. }(BABYLON.PostProcessRenderPipeline));
  75345. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75346. })(BABYLON || (BABYLON = {}));
  75347. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75348. var BABYLON;
  75349. (function (BABYLON) {
  75350. var FxaaPostProcess = /** @class */ (function (_super) {
  75351. __extends(FxaaPostProcess, _super);
  75352. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75353. if (camera === void 0) { camera = null; }
  75354. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75355. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75356. var defines = _this._getDefines();
  75357. _this.updateEffect(defines);
  75358. _this.onApplyObservable.add(function (effect) {
  75359. var texelSize = _this.texelSize;
  75360. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75361. });
  75362. return _this;
  75363. }
  75364. FxaaPostProcess.prototype._getDefines = function () {
  75365. var engine = this.getEngine();
  75366. if (!engine) {
  75367. return null;
  75368. }
  75369. var glInfo = engine.getGlInfo();
  75370. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75371. return "#define MALI 1\n";
  75372. }
  75373. return null;
  75374. };
  75375. return FxaaPostProcess;
  75376. }(BABYLON.PostProcess));
  75377. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75378. })(BABYLON || (BABYLON = {}));
  75379. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75380. var BABYLON;
  75381. (function (BABYLON) {
  75382. /**
  75383. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75384. */
  75385. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75386. __extends(ChromaticAberrationPostProcess, _super);
  75387. /**
  75388. * Creates a new instance ChromaticAberrationPostProcess
  75389. * @param name The name of the effect.
  75390. * @param screenWidth The width of the screen to apply the effect on.
  75391. * @param screenHeight The height of the screen to apply the effect on.
  75392. * @param options The required width/height ratio to downsize to before computing the render pass.
  75393. * @param camera The camera to apply the render pass to.
  75394. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75395. * @param engine The engine which the post process will be applied. (default: current engine)
  75396. * @param reusable If the post process can be reused on the same frame. (default: false)
  75397. * @param textureType Type of textures used when performing the post process. (default: 0)
  75398. * @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)
  75399. */
  75400. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75401. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75402. if (blockCompilation === void 0) { blockCompilation = false; }
  75403. 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;
  75404. /**
  75405. * The amount of seperation of rgb channels (default: 30)
  75406. */
  75407. _this.aberrationAmount = 30;
  75408. /**
  75409. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75410. */
  75411. _this.radialIntensity = 0;
  75412. /**
  75413. * 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))
  75414. */
  75415. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75416. /**
  75417. * 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))
  75418. */
  75419. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75420. _this.onApplyObservable.add(function (effect) {
  75421. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75422. effect.setFloat('screen_width', screenWidth);
  75423. effect.setFloat('screen_height', screenHeight);
  75424. effect.setFloat('radialIntensity', _this.radialIntensity);
  75425. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75426. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75427. });
  75428. return _this;
  75429. }
  75430. return ChromaticAberrationPostProcess;
  75431. }(BABYLON.PostProcess));
  75432. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75433. })(BABYLON || (BABYLON = {}));
  75434. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75435. var BABYLON;
  75436. (function (BABYLON) {
  75437. /**
  75438. * The GrainPostProcess adds noise to the image at mid luminance levels
  75439. */
  75440. var GrainPostProcess = /** @class */ (function (_super) {
  75441. __extends(GrainPostProcess, _super);
  75442. /**
  75443. * Creates a new instance of @see GrainPostProcess
  75444. * @param name The name of the effect.
  75445. * @param options The required width/height ratio to downsize to before computing the render pass.
  75446. * @param camera The camera to apply the render pass to.
  75447. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75448. * @param engine The engine which the post process will be applied. (default: current engine)
  75449. * @param reusable If the post process can be reused on the same frame. (default: false)
  75450. * @param textureType Type of textures used when performing the post process. (default: 0)
  75451. * @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)
  75452. */
  75453. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75454. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75455. if (blockCompilation === void 0) { blockCompilation = false; }
  75456. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75457. /**
  75458. * The intensity of the grain added (default: 30)
  75459. */
  75460. _this.intensity = 30;
  75461. /**
  75462. * If the grain should be randomized on every frame
  75463. */
  75464. _this.animated = false;
  75465. _this.onApplyObservable.add(function (effect) {
  75466. effect.setFloat('intensity', _this.intensity);
  75467. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75468. });
  75469. return _this;
  75470. }
  75471. return GrainPostProcess;
  75472. }(BABYLON.PostProcess));
  75473. BABYLON.GrainPostProcess = GrainPostProcess;
  75474. })(BABYLON || (BABYLON = {}));
  75475. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75476. var BABYLON;
  75477. (function (BABYLON) {
  75478. /**
  75479. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75480. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75481. */
  75482. var SharpenPostProcess = /** @class */ (function (_super) {
  75483. __extends(SharpenPostProcess, _super);
  75484. /**
  75485. * Creates a new instance ConvolutionPostProcess
  75486. * @param name The name of the effect.
  75487. * @param options The required width/height ratio to downsize to before computing the render pass.
  75488. * @param camera The camera to apply the render pass to.
  75489. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75490. * @param engine The engine which the post process will be applied. (default: current engine)
  75491. * @param reusable If the post process can be reused on the same frame. (default: false)
  75492. * @param textureType Type of textures used when performing the post process. (default: 0)
  75493. * @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)
  75494. */
  75495. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75496. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75497. if (blockCompilation === void 0) { blockCompilation = false; }
  75498. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75499. /**
  75500. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75501. */
  75502. _this.colorAmount = 1.0;
  75503. /**
  75504. * How much sharpness should be applied (default: 0.3)
  75505. */
  75506. _this.edgeAmount = 0.3;
  75507. _this.onApply = function (effect) {
  75508. effect.setFloat2("screenSize", _this.width, _this.height);
  75509. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75510. };
  75511. return _this;
  75512. }
  75513. return SharpenPostProcess;
  75514. }(BABYLON.PostProcess));
  75515. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75516. })(BABYLON || (BABYLON = {}));
  75517. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75518. var BABYLON;
  75519. (function (BABYLON) {
  75520. /**
  75521. * The Blur Post Process which blurs an image based on a kernel and direction.
  75522. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75523. */
  75524. var BlurPostProcess = /** @class */ (function (_super) {
  75525. __extends(BlurPostProcess, _super);
  75526. /**
  75527. * Creates a new instance BlurPostProcess
  75528. * @param name The name of the effect.
  75529. * @param direction The direction in which to blur the image.
  75530. * @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.
  75531. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75532. * @param camera The camera to apply the render pass to.
  75533. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75534. * @param engine The engine which the post process will be applied. (default: current engine)
  75535. * @param reusable If the post process can be reused on the same frame. (default: false)
  75536. * @param textureType Type of textures used when performing the post process. (default: 0)
  75537. * @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)
  75538. */
  75539. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75540. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75541. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75542. if (defines === void 0) { defines = ""; }
  75543. if (blockCompilation === void 0) { blockCompilation = false; }
  75544. 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;
  75545. _this.direction = direction;
  75546. _this.blockCompilation = blockCompilation;
  75547. _this._packedFloat = false;
  75548. _this._staticDefines = "";
  75549. _this._staticDefines = defines;
  75550. _this.onApplyObservable.add(function (effect) {
  75551. if (_this._outputTexture) {
  75552. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75553. }
  75554. else {
  75555. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75556. }
  75557. });
  75558. _this.kernel = kernel;
  75559. return _this;
  75560. }
  75561. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75562. /**
  75563. * Gets the length in pixels of the blur sample region
  75564. */
  75565. get: function () {
  75566. return this._idealKernel;
  75567. },
  75568. /**
  75569. * Sets the length in pixels of the blur sample region
  75570. */
  75571. set: function (v) {
  75572. if (this._idealKernel === v) {
  75573. return;
  75574. }
  75575. v = Math.max(v, 1);
  75576. this._idealKernel = v;
  75577. this._kernel = this._nearestBestKernel(v);
  75578. if (!this.blockCompilation) {
  75579. this._updateParameters();
  75580. }
  75581. },
  75582. enumerable: true,
  75583. configurable: true
  75584. });
  75585. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75586. /**
  75587. * Gets wether or not the blur is unpacking/repacking floats
  75588. */
  75589. get: function () {
  75590. return this._packedFloat;
  75591. },
  75592. /**
  75593. * Sets wether or not the blur needs to unpack/repack floats
  75594. */
  75595. set: function (v) {
  75596. if (this._packedFloat === v) {
  75597. return;
  75598. }
  75599. this._packedFloat = v;
  75600. if (!this.blockCompilation) {
  75601. this._updateParameters();
  75602. }
  75603. },
  75604. enumerable: true,
  75605. configurable: true
  75606. });
  75607. /**
  75608. * Updates the effect with the current post process compile time values and recompiles the shader.
  75609. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75610. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75611. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75612. * @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
  75613. * @param onCompiled Called when the shader has been compiled.
  75614. * @param onError Called if there is an error when compiling a shader.
  75615. */
  75616. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75617. if (defines === void 0) { defines = null; }
  75618. if (uniforms === void 0) { uniforms = null; }
  75619. if (samplers === void 0) { samplers = null; }
  75620. this._updateParameters(onCompiled, onError);
  75621. };
  75622. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75623. // Generate sampling offsets and weights
  75624. var N = this._kernel;
  75625. var centerIndex = (N - 1) / 2;
  75626. // Generate Gaussian sampling weights over kernel
  75627. var offsets = [];
  75628. var weights = [];
  75629. var totalWeight = 0;
  75630. for (var i = 0; i < N; i++) {
  75631. var u = i / (N - 1);
  75632. var w = this._gaussianWeight(u * 2.0 - 1);
  75633. offsets[i] = (i - centerIndex);
  75634. weights[i] = w;
  75635. totalWeight += w;
  75636. }
  75637. // Normalize weights
  75638. for (var i = 0; i < weights.length; i++) {
  75639. weights[i] /= totalWeight;
  75640. }
  75641. // Optimize: combine samples to take advantage of hardware linear sampling
  75642. // Walk from left to center, combining pairs (symmetrically)
  75643. var linearSamplingWeights = [];
  75644. var linearSamplingOffsets = [];
  75645. var linearSamplingMap = [];
  75646. for (var i = 0; i <= centerIndex; i += 2) {
  75647. var j = Math.min(i + 1, Math.floor(centerIndex));
  75648. var singleCenterSample = i === j;
  75649. if (singleCenterSample) {
  75650. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75651. }
  75652. else {
  75653. var sharedCell = j === centerIndex;
  75654. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75655. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75656. if (offsetLinear === 0) {
  75657. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75658. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75659. }
  75660. else {
  75661. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75662. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75663. }
  75664. }
  75665. }
  75666. for (var i = 0; i < linearSamplingMap.length; i++) {
  75667. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75668. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75669. }
  75670. // Replace with optimized
  75671. offsets = linearSamplingOffsets;
  75672. weights = linearSamplingWeights;
  75673. // Generate shaders
  75674. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75675. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75676. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75677. var defines = "";
  75678. defines += this._staticDefines;
  75679. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75680. if (this._staticDefines.indexOf("DOF") != -1) {
  75681. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75682. varyingCount--;
  75683. }
  75684. for (var i = 0; i < varyingCount; i++) {
  75685. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75686. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75687. }
  75688. var depCount = 0;
  75689. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75690. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75691. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75692. depCount++;
  75693. }
  75694. if (this.packedFloat) {
  75695. defines += "#define PACKEDFLOAT 1";
  75696. }
  75697. this.blockCompilation = false;
  75698. _super.prototype.updateEffect.call(this, defines, null, null, {
  75699. varyingCount: varyingCount,
  75700. depCount: depCount
  75701. }, onCompiled, onError);
  75702. };
  75703. /**
  75704. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75705. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75706. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75707. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75708. * The gaps between physical kernels are compensated for in the weighting of the samples
  75709. * @param idealKernel Ideal blur kernel.
  75710. * @return Nearest best kernel.
  75711. */
  75712. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75713. var v = Math.round(idealKernel);
  75714. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75715. var k = _a[_i];
  75716. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75717. return Math.max(k, 3);
  75718. }
  75719. }
  75720. return Math.max(v, 3);
  75721. };
  75722. /**
  75723. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75724. * @param x The point on the Gaussian distribution to sample.
  75725. * @return the value of the Gaussian function at x.
  75726. */
  75727. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75728. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75729. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75730. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75731. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75732. // truncated at around 1.3% of peak strength.
  75733. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75734. var sigma = (1 / 3);
  75735. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75736. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75737. var weight = (1.0 / denominator) * Math.exp(exponent);
  75738. return weight;
  75739. };
  75740. /**
  75741. * Generates a string that can be used as a floating point number in GLSL.
  75742. * @param x Value to print.
  75743. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75744. * @return GLSL float string.
  75745. */
  75746. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75747. if (decimalFigures === void 0) { decimalFigures = 8; }
  75748. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75749. };
  75750. return BlurPostProcess;
  75751. }(BABYLON.PostProcess));
  75752. BABYLON.BlurPostProcess = BlurPostProcess;
  75753. })(BABYLON || (BABYLON = {}));
  75754. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75755. var BABYLON;
  75756. (function (BABYLON) {
  75757. /**
  75758. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75759. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75760. * based on samples that have a large difference in distance than the center pixel.
  75761. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75762. */
  75763. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75764. __extends(DepthOfFieldBlurPostProcess, _super);
  75765. /**
  75766. * Creates a new instance CircleOfConfusionPostProcess
  75767. * @param name The name of the effect.
  75768. * @param scene The scene the effect belongs to.
  75769. * @param direction The direction the blur should be applied.
  75770. * @param kernel The size of the kernel used to blur.
  75771. * @param options The required width/height ratio to downsize to before computing the render pass.
  75772. * @param camera The camera to apply the render pass to.
  75773. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75774. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75775. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75776. * @param engine The engine which the post process will be applied. (default: current engine)
  75777. * @param reusable If the post process can be reused on the same frame. (default: false)
  75778. * @param textureType Type of textures used when performing the post process. (default: 0)
  75779. * @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)
  75780. */
  75781. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75782. if (imageToBlur === void 0) { imageToBlur = null; }
  75783. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75784. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75785. if (blockCompilation === void 0) { blockCompilation = false; }
  75786. 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;
  75787. _this.direction = direction;
  75788. _this.onApplyObservable.add(function (effect) {
  75789. if (imageToBlur != null) {
  75790. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75791. }
  75792. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75793. if (scene.activeCamera) {
  75794. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75795. }
  75796. });
  75797. return _this;
  75798. }
  75799. return DepthOfFieldBlurPostProcess;
  75800. }(BABYLON.BlurPostProcess));
  75801. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75802. })(BABYLON || (BABYLON = {}));
  75803. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75804. var BABYLON;
  75805. (function (BABYLON) {
  75806. /**
  75807. * Options to be set when merging outputs from the default pipeline.
  75808. */
  75809. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75810. function DepthOfFieldMergePostProcessOptions() {
  75811. }
  75812. return DepthOfFieldMergePostProcessOptions;
  75813. }());
  75814. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75815. /**
  75816. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75817. */
  75818. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75819. __extends(DepthOfFieldMergePostProcess, _super);
  75820. /**
  75821. * Creates a new instance of DepthOfFieldMergePostProcess
  75822. * @param name The name of the effect.
  75823. * @param originalFromInput Post process which's input will be used for the merge.
  75824. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75825. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75826. * @param options The required width/height ratio to downsize to before computing the render pass.
  75827. * @param camera The camera to apply the render pass to.
  75828. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75829. * @param engine The engine which the post process will be applied. (default: current engine)
  75830. * @param reusable If the post process can be reused on the same frame. (default: false)
  75831. * @param textureType Type of textures used when performing the post process. (default: 0)
  75832. * @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)
  75833. */
  75834. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75835. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75836. if (blockCompilation === void 0) { blockCompilation = false; }
  75837. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75838. _this.blurSteps = blurSteps;
  75839. _this.onApplyObservable.add(function (effect) {
  75840. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75841. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75842. blurSteps.forEach(function (step, index) {
  75843. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75844. });
  75845. });
  75846. if (!blockCompilation) {
  75847. _this.updateEffect();
  75848. }
  75849. return _this;
  75850. }
  75851. /**
  75852. * Updates the effect with the current post process compile time values and recompiles the shader.
  75853. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75854. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75855. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75856. * @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
  75857. * @param onCompiled Called when the shader has been compiled.
  75858. * @param onError Called if there is an error when compiling a shader.
  75859. */
  75860. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75861. if (defines === void 0) { defines = null; }
  75862. if (uniforms === void 0) { uniforms = null; }
  75863. if (samplers === void 0) { samplers = null; }
  75864. if (!defines) {
  75865. defines = "";
  75866. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75867. }
  75868. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75869. };
  75870. return DepthOfFieldMergePostProcess;
  75871. }(BABYLON.PostProcess));
  75872. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75873. })(BABYLON || (BABYLON = {}));
  75874. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75875. var BABYLON;
  75876. (function (BABYLON) {
  75877. /**
  75878. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75879. */
  75880. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75881. __extends(CircleOfConfusionPostProcess, _super);
  75882. /**
  75883. * Creates a new instance CircleOfConfusionPostProcess
  75884. * @param name The name of the effect.
  75885. * @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.
  75886. * @param options The required width/height ratio to downsize to before computing the render pass.
  75887. * @param camera The camera to apply the render pass to.
  75888. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75889. * @param engine The engine which the post process will be applied. (default: current engine)
  75890. * @param reusable If the post process can be reused on the same frame. (default: false)
  75891. * @param textureType Type of textures used when performing the post process. (default: 0)
  75892. * @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)
  75893. */
  75894. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75895. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75896. if (blockCompilation === void 0) { blockCompilation = false; }
  75897. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75898. /**
  75899. * 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.
  75900. */
  75901. _this.lensSize = 50;
  75902. /**
  75903. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75904. */
  75905. _this.fStop = 1.4;
  75906. /**
  75907. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75908. */
  75909. _this.focusDistance = 2000;
  75910. /**
  75911. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75912. */
  75913. _this.focalLength = 50;
  75914. _this._depthTexture = null;
  75915. _this._depthTexture = depthTexture;
  75916. _this.onApplyObservable.add(function (effect) {
  75917. if (!_this._depthTexture) {
  75918. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75919. return;
  75920. }
  75921. effect.setTexture("depthSampler", _this._depthTexture);
  75922. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75923. var aperture = _this.lensSize / _this.fStop;
  75924. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75925. effect.setFloat('focusDistance', _this.focusDistance);
  75926. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75927. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75928. });
  75929. return _this;
  75930. }
  75931. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75932. /**
  75933. * 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.
  75934. */
  75935. set: function (value) {
  75936. this._depthTexture = value;
  75937. },
  75938. enumerable: true,
  75939. configurable: true
  75940. });
  75941. return CircleOfConfusionPostProcess;
  75942. }(BABYLON.PostProcess));
  75943. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75944. })(BABYLON || (BABYLON = {}));
  75945. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75946. var BABYLON;
  75947. (function (BABYLON) {
  75948. /**
  75949. * Specifies the level of max blur that should be applied when using the depth of field effect
  75950. */
  75951. var DepthOfFieldEffectBlurLevel;
  75952. (function (DepthOfFieldEffectBlurLevel) {
  75953. /**
  75954. * Subtle blur
  75955. */
  75956. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75957. /**
  75958. * Medium blur
  75959. */
  75960. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75961. /**
  75962. * Large blur
  75963. */
  75964. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75965. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75966. ;
  75967. /**
  75968. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75969. */
  75970. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75971. __extends(DepthOfFieldEffect, _super);
  75972. /**
  75973. * Creates a new instance DepthOfFieldEffect
  75974. * @param scene The scene the effect belongs to.
  75975. * @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.
  75976. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75977. * @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)
  75978. */
  75979. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75980. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75981. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75982. if (blockCompilation === void 0) { blockCompilation = false; }
  75983. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75984. return _this._effects;
  75985. }, true) || this;
  75986. /**
  75987. * Internal post processes in depth of field effect
  75988. */
  75989. _this._effects = [];
  75990. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75991. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75992. // 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)
  75993. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75994. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75995. _this._depthOfFieldBlurY = [];
  75996. _this._depthOfFieldBlurX = [];
  75997. var blurCount = 1;
  75998. var kernelSize = 15;
  75999. switch (blurLevel) {
  76000. case DepthOfFieldEffectBlurLevel.High: {
  76001. blurCount = 3;
  76002. kernelSize = 51;
  76003. break;
  76004. }
  76005. case DepthOfFieldEffectBlurLevel.Medium: {
  76006. blurCount = 2;
  76007. kernelSize = 31;
  76008. break;
  76009. }
  76010. default: {
  76011. kernelSize = 15;
  76012. blurCount = 1;
  76013. break;
  76014. }
  76015. }
  76016. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  76017. var ratio = 1.0;
  76018. for (var i = 0; i < blurCount; i++) {
  76019. 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);
  76020. blurY.autoClear = false;
  76021. ratio = 0.75 / Math.pow(2, i);
  76022. 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);
  76023. blurX.autoClear = false;
  76024. _this._depthOfFieldBlurY.push(blurY);
  76025. _this._depthOfFieldBlurX.push(blurX);
  76026. }
  76027. // Set all post processes on the effect.
  76028. _this._effects = [_this._circleOfConfusion];
  76029. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  76030. _this._effects.push(_this._depthOfFieldBlurY[i]);
  76031. _this._effects.push(_this._depthOfFieldBlurX[i]);
  76032. }
  76033. // Merge blurred images with original image based on circleOfConfusion
  76034. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76035. _this._dofMerge.autoClear = false;
  76036. _this._effects.push(_this._dofMerge);
  76037. return _this;
  76038. }
  76039. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  76040. get: function () {
  76041. return this._circleOfConfusion.focalLength;
  76042. },
  76043. /**
  76044. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  76045. */
  76046. set: function (value) {
  76047. this._circleOfConfusion.focalLength = value;
  76048. },
  76049. enumerable: true,
  76050. configurable: true
  76051. });
  76052. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  76053. get: function () {
  76054. return this._circleOfConfusion.fStop;
  76055. },
  76056. /**
  76057. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76058. */
  76059. set: function (value) {
  76060. this._circleOfConfusion.fStop = value;
  76061. },
  76062. enumerable: true,
  76063. configurable: true
  76064. });
  76065. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  76066. get: function () {
  76067. return this._circleOfConfusion.focusDistance;
  76068. },
  76069. /**
  76070. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76071. */
  76072. set: function (value) {
  76073. this._circleOfConfusion.focusDistance = value;
  76074. },
  76075. enumerable: true,
  76076. configurable: true
  76077. });
  76078. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  76079. get: function () {
  76080. return this._circleOfConfusion.lensSize;
  76081. },
  76082. /**
  76083. * 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.
  76084. */
  76085. set: function (value) {
  76086. this._circleOfConfusion.lensSize = value;
  76087. },
  76088. enumerable: true,
  76089. configurable: true
  76090. });
  76091. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76092. /**
  76093. * 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.
  76094. */
  76095. set: function (value) {
  76096. this._circleOfConfusion.depthTexture = value;
  76097. },
  76098. enumerable: true,
  76099. configurable: true
  76100. });
  76101. /**
  76102. * Disposes each of the internal effects for a given camera.
  76103. * @param camera The camera to dispose the effect on.
  76104. */
  76105. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76106. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76107. this._effects[effectIndex].dispose(camera);
  76108. }
  76109. };
  76110. /**
  76111. * Internal
  76112. */
  76113. DepthOfFieldEffect.prototype._updateEffects = function () {
  76114. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76115. this._effects[effectIndex].updateEffect();
  76116. }
  76117. };
  76118. /**
  76119. * Internal
  76120. * @returns if all the contained post processes are ready.
  76121. */
  76122. DepthOfFieldEffect.prototype._isReady = function () {
  76123. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76124. if (!this._effects[effectIndex].isReady()) {
  76125. return false;
  76126. }
  76127. }
  76128. return true;
  76129. };
  76130. return DepthOfFieldEffect;
  76131. }(BABYLON.PostProcessRenderEffect));
  76132. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76133. })(BABYLON || (BABYLON = {}));
  76134. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76135. var BABYLON;
  76136. (function (BABYLON) {
  76137. /**
  76138. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76139. */
  76140. var BloomMergePostProcess = /** @class */ (function (_super) {
  76141. __extends(BloomMergePostProcess, _super);
  76142. /**
  76143. * Creates a new instance of @see BloomMergePostProcess
  76144. * @param name The name of the effect.
  76145. * @param originalFromInput Post process which's input will be used for the merge.
  76146. * @param blurred Blurred highlights post process which's output will be used.
  76147. * @param weight Weight of the bloom to be added to the original input.
  76148. * @param options The required width/height ratio to downsize to before computing the render pass.
  76149. * @param camera The camera to apply the render pass to.
  76150. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76151. * @param engine The engine which the post process will be applied. (default: current engine)
  76152. * @param reusable If the post process can be reused on the same frame. (default: false)
  76153. * @param textureType Type of textures used when performing the post process. (default: 0)
  76154. * @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)
  76155. */
  76156. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76157. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76158. if (blockCompilation === void 0) { blockCompilation = false; }
  76159. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76160. _this.weight = weight;
  76161. _this.onApplyObservable.add(function (effect) {
  76162. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76163. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76164. effect.setFloat("bloomWeight", _this.weight);
  76165. });
  76166. if (!blockCompilation) {
  76167. _this.updateEffect();
  76168. }
  76169. return _this;
  76170. }
  76171. return BloomMergePostProcess;
  76172. }(BABYLON.PostProcess));
  76173. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76174. })(BABYLON || (BABYLON = {}));
  76175. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76176. var BABYLON;
  76177. (function (BABYLON) {
  76178. /**
  76179. * 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.
  76180. */
  76181. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76182. __extends(ExtractHighlightsPostProcess, _super);
  76183. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76184. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76185. if (blockCompilation === void 0) { blockCompilation = false; }
  76186. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76187. /**
  76188. * The luminance threshold, pixels below this value will be set to black.
  76189. */
  76190. _this.threshold = 0.9;
  76191. /**
  76192. * Internal
  76193. */
  76194. _this._exposure = 1;
  76195. /**
  76196. * Post process which has the input texture to be used when performing highlight extraction
  76197. */
  76198. _this._inputPostProcess = null;
  76199. _this.onApplyObservable.add(function (effect) {
  76200. if (_this._inputPostProcess) {
  76201. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76202. }
  76203. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76204. effect.setFloat('exposure', _this._exposure);
  76205. });
  76206. return _this;
  76207. }
  76208. return ExtractHighlightsPostProcess;
  76209. }(BABYLON.PostProcess));
  76210. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76211. })(BABYLON || (BABYLON = {}));
  76212. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76213. var BABYLON;
  76214. (function (BABYLON) {
  76215. /**
  76216. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76217. */
  76218. var BloomEffect = /** @class */ (function (_super) {
  76219. __extends(BloomEffect, _super);
  76220. /**
  76221. * Creates a new instance of @see BloomEffect
  76222. * @param scene The scene the effect belongs to.
  76223. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76224. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76225. * @param bloomWeight The the strength of bloom.
  76226. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76227. * @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)
  76228. */
  76229. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76230. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76231. if (blockCompilation === void 0) { blockCompilation = false; }
  76232. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76233. return _this._effects;
  76234. }, true) || this;
  76235. _this.bloomScale = bloomScale;
  76236. /**
  76237. * Internal
  76238. */
  76239. _this._effects = [];
  76240. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76241. _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);
  76242. _this._blurX.alwaysForcePOT = true;
  76243. _this._blurX.autoClear = false;
  76244. _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);
  76245. _this._blurY.alwaysForcePOT = true;
  76246. _this._blurY.autoClear = false;
  76247. _this.kernel = bloomKernel;
  76248. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76249. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76250. _this._merge.autoClear = false;
  76251. _this._effects.push(_this._merge);
  76252. return _this;
  76253. }
  76254. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76255. /**
  76256. * The luminance threshold to find bright areas of the image to bloom.
  76257. */
  76258. get: function () {
  76259. return this._downscale.threshold;
  76260. },
  76261. set: function (value) {
  76262. this._downscale.threshold = value;
  76263. },
  76264. enumerable: true,
  76265. configurable: true
  76266. });
  76267. Object.defineProperty(BloomEffect.prototype, "weight", {
  76268. /**
  76269. * The strength of the bloom.
  76270. */
  76271. get: function () {
  76272. return this._merge.weight;
  76273. },
  76274. set: function (value) {
  76275. this._merge.weight = value;
  76276. },
  76277. enumerable: true,
  76278. configurable: true
  76279. });
  76280. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76281. /**
  76282. * Specifies the size of the bloom blur kernel, relative to the final output size
  76283. */
  76284. get: function () {
  76285. return this._blurX.kernel / this.bloomScale;
  76286. },
  76287. set: function (value) {
  76288. this._blurX.kernel = value * this.bloomScale;
  76289. this._blurY.kernel = value * this.bloomScale;
  76290. },
  76291. enumerable: true,
  76292. configurable: true
  76293. });
  76294. /**
  76295. * Disposes each of the internal effects for a given camera.
  76296. * @param camera The camera to dispose the effect on.
  76297. */
  76298. BloomEffect.prototype.disposeEffects = function (camera) {
  76299. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76300. this._effects[effectIndex].dispose(camera);
  76301. }
  76302. };
  76303. /**
  76304. * Internal
  76305. */
  76306. BloomEffect.prototype._updateEffects = function () {
  76307. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76308. this._effects[effectIndex].updateEffect();
  76309. }
  76310. };
  76311. /**
  76312. * Internal
  76313. * @returns if all the contained post processes are ready.
  76314. */
  76315. BloomEffect.prototype._isReady = function () {
  76316. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76317. if (!this._effects[effectIndex].isReady()) {
  76318. return false;
  76319. }
  76320. }
  76321. return true;
  76322. };
  76323. return BloomEffect;
  76324. }(BABYLON.PostProcessRenderEffect));
  76325. BABYLON.BloomEffect = BloomEffect;
  76326. })(BABYLON || (BABYLON = {}));
  76327. //# sourceMappingURL=babylon.bloomEffect.js.map
  76328. var BABYLON;
  76329. (function (BABYLON) {
  76330. /**
  76331. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76332. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76333. */
  76334. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76335. __extends(DefaultRenderingPipeline, _super);
  76336. /**
  76337. * @constructor
  76338. * @param {string} name - The rendering pipeline name (default: "")
  76339. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76340. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76341. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76342. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76343. */
  76344. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76345. if (name === void 0) { name = ""; }
  76346. if (hdr === void 0) { hdr = true; }
  76347. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76348. if (automaticBuild === void 0) { automaticBuild = true; }
  76349. var _this = _super.call(this, scene.getEngine(), name) || this;
  76350. _this._camerasToBeAttached = [];
  76351. /**
  76352. * ID of the sharpen post process,
  76353. */
  76354. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76355. /**
  76356. * ID of the image processing post process;
  76357. */
  76358. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76359. /**
  76360. * ID of the Fast Approximate Anti-Aliasing post process;
  76361. */
  76362. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76363. /**
  76364. * ID of the chromatic aberration post process,
  76365. */
  76366. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76367. /**
  76368. * ID of the grain post process
  76369. */
  76370. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76371. /**
  76372. * Glow post process which adds a glow to emmisive areas of the image
  76373. */
  76374. _this._glowLayer = null;
  76375. /**
  76376. * Animations which can be used to tweak settings over a period of time
  76377. */
  76378. _this.animations = [];
  76379. _this._imageProcessingConfigurationObserver = null;
  76380. // Values
  76381. _this._sharpenEnabled = false;
  76382. _this._bloomEnabled = false;
  76383. _this._depthOfFieldEnabled = false;
  76384. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76385. _this._fxaaEnabled = false;
  76386. _this._imageProcessingEnabled = true;
  76387. _this._bloomScale = 0.5;
  76388. _this._chromaticAberrationEnabled = false;
  76389. _this._grainEnabled = false;
  76390. _this._buildAllowed = true;
  76391. _this._resizeObserver = null;
  76392. _this._hardwareScaleLevel = 1.0;
  76393. _this._bloomKernel = 64;
  76394. /**
  76395. * Specifies the weight of the bloom in the final rendering
  76396. */
  76397. _this._bloomWeight = 0.15;
  76398. /**
  76399. * Specifies the luma threshold for the area that will be blurred by the bloom
  76400. */
  76401. _this._bloomThreshold = 0.9;
  76402. _this._samples = 1;
  76403. _this._hasCleared = false;
  76404. _this._prevPostProcess = null;
  76405. _this._prevPrevPostProcess = null;
  76406. _this._cameras = cameras || scene.cameras;
  76407. _this._camerasToBeAttached = _this._cameras.slice();
  76408. _this._buildAllowed = automaticBuild;
  76409. // Initialize
  76410. _this._scene = scene;
  76411. var caps = _this._scene.getEngine().getCaps();
  76412. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76413. // Misc
  76414. if (_this._hdr) {
  76415. if (caps.textureHalfFloatRender) {
  76416. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76417. }
  76418. else if (caps.textureFloatRender) {
  76419. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76420. }
  76421. }
  76422. else {
  76423. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76424. }
  76425. // Attach
  76426. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76427. var engine = _this._scene.getEngine();
  76428. // Create post processes before hand so they can be modified before enabled.
  76429. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76430. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76431. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76432. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76433. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76434. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76435. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76436. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76437. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76438. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76439. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76440. _this.bloomKernel = _this.bloomKernel;
  76441. });
  76442. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76443. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76444. });
  76445. _this._buildPipeline();
  76446. return _this;
  76447. }
  76448. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76449. get: function () {
  76450. return this._sharpenEnabled;
  76451. },
  76452. /**
  76453. * Enable or disable the sharpen process from the pipeline
  76454. */
  76455. set: function (enabled) {
  76456. if (this._sharpenEnabled === enabled) {
  76457. return;
  76458. }
  76459. this._sharpenEnabled = enabled;
  76460. this._buildPipeline();
  76461. },
  76462. enumerable: true,
  76463. configurable: true
  76464. });
  76465. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76466. /**
  76467. * Specifies the size of the bloom blur kernel, relative to the final output size
  76468. */
  76469. get: function () {
  76470. return this._bloomKernel;
  76471. },
  76472. set: function (value) {
  76473. this._bloomKernel = value;
  76474. this.bloom.kernel = value / this._hardwareScaleLevel;
  76475. },
  76476. enumerable: true,
  76477. configurable: true
  76478. });
  76479. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76480. get: function () {
  76481. return this._bloomWeight;
  76482. },
  76483. /**
  76484. * The strength of the bloom.
  76485. */
  76486. set: function (value) {
  76487. if (this._bloomWeight === value) {
  76488. return;
  76489. }
  76490. this.bloom.weight = value;
  76491. this._bloomWeight = value;
  76492. },
  76493. enumerable: true,
  76494. configurable: true
  76495. });
  76496. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76497. get: function () {
  76498. return this._bloomThreshold;
  76499. },
  76500. /**
  76501. * The strength of the bloom.
  76502. */
  76503. set: function (value) {
  76504. if (this._bloomThreshold === value) {
  76505. return;
  76506. }
  76507. this.bloom.threshold = value;
  76508. this._bloomThreshold = value;
  76509. },
  76510. enumerable: true,
  76511. configurable: true
  76512. });
  76513. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76514. get: function () {
  76515. return this._bloomScale;
  76516. },
  76517. /**
  76518. * The scale of the bloom, lower value will provide better performance.
  76519. */
  76520. set: function (value) {
  76521. if (this._bloomScale === value) {
  76522. return;
  76523. }
  76524. this._bloomScale = value;
  76525. // recreate bloom and dispose old as this setting is not dynamic
  76526. this._rebuildBloom();
  76527. this._buildPipeline();
  76528. },
  76529. enumerable: true,
  76530. configurable: true
  76531. });
  76532. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76533. get: function () {
  76534. return this._bloomEnabled;
  76535. },
  76536. /**
  76537. * Enable or disable the bloom from the pipeline
  76538. */
  76539. set: function (enabled) {
  76540. if (this._bloomEnabled === enabled) {
  76541. return;
  76542. }
  76543. this._bloomEnabled = enabled;
  76544. this._buildPipeline();
  76545. },
  76546. enumerable: true,
  76547. configurable: true
  76548. });
  76549. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76550. // recreate bloom and dispose old as this setting is not dynamic
  76551. var oldBloom = this.bloom;
  76552. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76553. this.bloom.threshold = oldBloom.threshold;
  76554. for (var i = 0; i < this._cameras.length; i++) {
  76555. oldBloom.disposeEffects(this._cameras[i]);
  76556. }
  76557. };
  76558. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76559. /**
  76560. * If the depth of field is enabled.
  76561. */
  76562. get: function () {
  76563. return this._depthOfFieldEnabled;
  76564. },
  76565. set: function (enabled) {
  76566. if (this._depthOfFieldEnabled === enabled) {
  76567. return;
  76568. }
  76569. this._depthOfFieldEnabled = enabled;
  76570. this._buildPipeline();
  76571. },
  76572. enumerable: true,
  76573. configurable: true
  76574. });
  76575. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76576. /**
  76577. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76578. */
  76579. get: function () {
  76580. return this._depthOfFieldBlurLevel;
  76581. },
  76582. set: function (value) {
  76583. if (this._depthOfFieldBlurLevel === value) {
  76584. return;
  76585. }
  76586. this._depthOfFieldBlurLevel = value;
  76587. // recreate dof and dispose old as this setting is not dynamic
  76588. var oldDof = this.depthOfField;
  76589. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76590. this.depthOfField.focalLength = oldDof.focalLength;
  76591. this.depthOfField.focusDistance = oldDof.focusDistance;
  76592. this.depthOfField.fStop = oldDof.fStop;
  76593. this.depthOfField.lensSize = oldDof.lensSize;
  76594. for (var i = 0; i < this._cameras.length; i++) {
  76595. oldDof.disposeEffects(this._cameras[i]);
  76596. }
  76597. this._buildPipeline();
  76598. },
  76599. enumerable: true,
  76600. configurable: true
  76601. });
  76602. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76603. get: function () {
  76604. return this._fxaaEnabled;
  76605. },
  76606. /**
  76607. * If the anti aliasing is enabled.
  76608. */
  76609. set: function (enabled) {
  76610. if (this._fxaaEnabled === enabled) {
  76611. return;
  76612. }
  76613. this._fxaaEnabled = enabled;
  76614. this._buildPipeline();
  76615. },
  76616. enumerable: true,
  76617. configurable: true
  76618. });
  76619. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76620. get: function () {
  76621. return this._samples;
  76622. },
  76623. /**
  76624. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76625. */
  76626. set: function (sampleCount) {
  76627. if (this._samples === sampleCount) {
  76628. return;
  76629. }
  76630. this._samples = sampleCount;
  76631. this._buildPipeline();
  76632. },
  76633. enumerable: true,
  76634. configurable: true
  76635. });
  76636. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76637. get: function () {
  76638. return this._imageProcessingEnabled;
  76639. },
  76640. /**
  76641. * If image processing is enabled.
  76642. */
  76643. set: function (enabled) {
  76644. if (this._imageProcessingEnabled === enabled) {
  76645. return;
  76646. }
  76647. this._imageProcessingEnabled = enabled;
  76648. this._buildPipeline();
  76649. },
  76650. enumerable: true,
  76651. configurable: true
  76652. });
  76653. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76654. get: function () {
  76655. return this._glowLayer == null;
  76656. },
  76657. /**
  76658. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76659. */
  76660. set: function (enabled) {
  76661. if (enabled && !this._glowLayer) {
  76662. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76663. }
  76664. else if (!enabled && this._glowLayer) {
  76665. this._glowLayer.dispose();
  76666. this._glowLayer = null;
  76667. }
  76668. },
  76669. enumerable: true,
  76670. configurable: true
  76671. });
  76672. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76673. get: function () {
  76674. return this._chromaticAberrationEnabled;
  76675. },
  76676. /**
  76677. * Enable or disable the chromaticAberration process from the pipeline
  76678. */
  76679. set: function (enabled) {
  76680. if (this._chromaticAberrationEnabled === enabled) {
  76681. return;
  76682. }
  76683. this._chromaticAberrationEnabled = enabled;
  76684. this._buildPipeline();
  76685. },
  76686. enumerable: true,
  76687. configurable: true
  76688. });
  76689. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76690. get: function () {
  76691. return this._grainEnabled;
  76692. },
  76693. /**
  76694. * Enable or disable the grain process from the pipeline
  76695. */
  76696. set: function (enabled) {
  76697. if (this._grainEnabled === enabled) {
  76698. return;
  76699. }
  76700. this._grainEnabled = enabled;
  76701. this._buildPipeline();
  76702. },
  76703. enumerable: true,
  76704. configurable: true
  76705. });
  76706. /**
  76707. * Force the compilation of the entire pipeline.
  76708. */
  76709. DefaultRenderingPipeline.prototype.prepare = function () {
  76710. var previousState = this._buildAllowed;
  76711. this._buildAllowed = true;
  76712. this._buildPipeline();
  76713. this._buildAllowed = previousState;
  76714. };
  76715. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76716. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76717. if (this._hasCleared) {
  76718. postProcess.autoClear = false;
  76719. }
  76720. else {
  76721. postProcess.autoClear = true;
  76722. this._scene.autoClear = false;
  76723. this._hasCleared = true;
  76724. }
  76725. if (!skipTextureSharing) {
  76726. if (this._prevPrevPostProcess) {
  76727. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76728. }
  76729. else {
  76730. postProcess.useOwnOutput();
  76731. }
  76732. if (this._prevPostProcess) {
  76733. this._prevPrevPostProcess = this._prevPostProcess;
  76734. }
  76735. this._prevPostProcess = postProcess;
  76736. }
  76737. };
  76738. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76739. var _this = this;
  76740. if (!this._buildAllowed) {
  76741. return;
  76742. }
  76743. this._scene.autoClear = true;
  76744. var engine = this._scene.getEngine();
  76745. this._disposePostProcesses();
  76746. if (this._cameras !== null) {
  76747. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76748. // get back cameras to be used to reattach pipeline
  76749. this._cameras = this._camerasToBeAttached.slice();
  76750. }
  76751. this._reset();
  76752. this._prevPostProcess = null;
  76753. this._prevPrevPostProcess = null;
  76754. this._hasCleared = false;
  76755. if (this.depthOfFieldEnabled) {
  76756. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76757. this.depthOfField.depthTexture = depthTexture;
  76758. if (!this.depthOfField._isReady()) {
  76759. this.depthOfField._updateEffects();
  76760. }
  76761. this.addEffect(this.depthOfField);
  76762. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76763. }
  76764. if (this.bloomEnabled) {
  76765. if (!this.bloom._isReady()) {
  76766. this.bloom._updateEffects();
  76767. }
  76768. this.addEffect(this.bloom);
  76769. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76770. }
  76771. if (this._imageProcessingEnabled) {
  76772. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76773. if (this._hdr) {
  76774. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76775. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76776. }
  76777. else {
  76778. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76779. }
  76780. }
  76781. if (this.sharpenEnabled) {
  76782. if (!this.sharpen.isReady()) {
  76783. this.sharpen.updateEffect();
  76784. }
  76785. this.addEffect(this._sharpenEffect);
  76786. this._setAutoClearAndTextureSharing(this.sharpen);
  76787. }
  76788. if (this.grainEnabled) {
  76789. if (!this.grain.isReady()) {
  76790. this.grain.updateEffect();
  76791. }
  76792. this.addEffect(this._grainEffect);
  76793. this._setAutoClearAndTextureSharing(this.grain);
  76794. }
  76795. if (this.chromaticAberrationEnabled) {
  76796. if (!this.chromaticAberration.isReady()) {
  76797. this.chromaticAberration.updateEffect();
  76798. }
  76799. this.addEffect(this._chromaticAberrationEffect);
  76800. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76801. }
  76802. if (this.fxaaEnabled) {
  76803. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76804. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76805. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76806. }
  76807. if (this._cameras !== null) {
  76808. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76809. }
  76810. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76811. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76812. }
  76813. };
  76814. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76815. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76816. for (var i = 0; i < this._cameras.length; i++) {
  76817. var camera = this._cameras[i];
  76818. if (this.imageProcessing) {
  76819. this.imageProcessing.dispose(camera);
  76820. }
  76821. if (this.fxaa) {
  76822. this.fxaa.dispose(camera);
  76823. }
  76824. // These are created in the constructor and should not be disposed on every pipeline change
  76825. if (disposeNonRecreated) {
  76826. if (this.sharpen) {
  76827. this.sharpen.dispose(camera);
  76828. }
  76829. if (this.depthOfField) {
  76830. this.depthOfField.disposeEffects(camera);
  76831. }
  76832. if (this.bloom) {
  76833. this.bloom.disposeEffects(camera);
  76834. }
  76835. if (this.chromaticAberration) {
  76836. this.chromaticAberration.dispose(camera);
  76837. }
  76838. if (this.grain) {
  76839. this.grain.dispose(camera);
  76840. }
  76841. if (this._glowLayer) {
  76842. this._glowLayer.dispose();
  76843. }
  76844. }
  76845. }
  76846. this.imageProcessing = null;
  76847. this.fxaa = null;
  76848. if (disposeNonRecreated) {
  76849. this.sharpen = null;
  76850. this._sharpenEffect = null;
  76851. this.depthOfField = null;
  76852. this.bloom = null;
  76853. this.chromaticAberration = null;
  76854. this._chromaticAberrationEffect = null;
  76855. this.grain = null;
  76856. this._grainEffect = null;
  76857. this._glowLayer = null;
  76858. }
  76859. };
  76860. /**
  76861. * Adds a camera to the pipeline
  76862. * @param camera the camera to be added
  76863. */
  76864. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  76865. this._camerasToBeAttached.push(camera);
  76866. this._buildPipeline();
  76867. };
  76868. /**
  76869. * Removes a camera from the pipeline
  76870. * @param camera the camera to remove
  76871. */
  76872. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  76873. var index = this._camerasToBeAttached.indexOf(camera);
  76874. this._camerasToBeAttached.splice(index, 1);
  76875. this._buildPipeline();
  76876. };
  76877. /**
  76878. * Dispose of the pipeline and stop all post processes
  76879. */
  76880. DefaultRenderingPipeline.prototype.dispose = function () {
  76881. this._disposePostProcesses(true);
  76882. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76883. this._scene.autoClear = true;
  76884. if (this._resizeObserver) {
  76885. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76886. this._resizeObserver = null;
  76887. }
  76888. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76889. _super.prototype.dispose.call(this);
  76890. };
  76891. /**
  76892. * Serialize the rendering pipeline (Used when exporting)
  76893. * @returns the serialized object
  76894. */
  76895. DefaultRenderingPipeline.prototype.serialize = function () {
  76896. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76897. serializationObject.customType = "DefaultRenderingPipeline";
  76898. return serializationObject;
  76899. };
  76900. /**
  76901. * Parse the serialized pipeline
  76902. * @param source Source pipeline.
  76903. * @param scene The scene to load the pipeline to.
  76904. * @param rootUrl The URL of the serialized pipeline.
  76905. * @returns An instantiated pipeline from the serialized object.
  76906. */
  76907. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76908. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76909. };
  76910. __decorate([
  76911. BABYLON.serialize()
  76912. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76913. __decorate([
  76914. BABYLON.serialize()
  76915. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76916. __decorate([
  76917. BABYLON.serialize()
  76918. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76919. __decorate([
  76920. BABYLON.serialize()
  76921. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76922. __decorate([
  76923. BABYLON.serialize()
  76924. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76925. __decorate([
  76926. BABYLON.serialize()
  76927. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76928. __decorate([
  76929. BABYLON.serialize()
  76930. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76931. __decorate([
  76932. BABYLON.serialize()
  76933. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76934. __decorate([
  76935. BABYLON.serialize()
  76936. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76937. __decorate([
  76938. BABYLON.serialize()
  76939. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76940. __decorate([
  76941. BABYLON.serialize()
  76942. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76943. __decorate([
  76944. BABYLON.serialize()
  76945. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76946. __decorate([
  76947. BABYLON.serialize()
  76948. ], DefaultRenderingPipeline.prototype, "samples", null);
  76949. __decorate([
  76950. BABYLON.serialize()
  76951. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76952. __decorate([
  76953. BABYLON.serialize()
  76954. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76955. __decorate([
  76956. BABYLON.serialize()
  76957. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76958. __decorate([
  76959. BABYLON.serialize()
  76960. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76961. return DefaultRenderingPipeline;
  76962. }(BABYLON.PostProcessRenderPipeline));
  76963. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76964. })(BABYLON || (BABYLON = {}));
  76965. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76966. var BABYLON;
  76967. (function (BABYLON) {
  76968. /**
  76969. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76970. */
  76971. var GeometryBufferRenderer = /** @class */ (function () {
  76972. /**
  76973. * Creates a new G Buffer for the scene
  76974. * @param scene The scene the buffer belongs to
  76975. * @param ratio How big is the buffer related to the main canvas.
  76976. */
  76977. function GeometryBufferRenderer(scene, ratio) {
  76978. if (ratio === void 0) { ratio = 1; }
  76979. this._enablePosition = false;
  76980. this._scene = scene;
  76981. this._ratio = ratio;
  76982. // Render target
  76983. this._createRenderTargets();
  76984. }
  76985. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76986. /**
  76987. * Set the render list (meshes to be rendered) used in the G buffer.
  76988. */
  76989. set: function (meshes) {
  76990. this._multiRenderTarget.renderList = meshes;
  76991. },
  76992. enumerable: true,
  76993. configurable: true
  76994. });
  76995. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76996. /**
  76997. * Gets wether or not G buffer are supported by the running hardware.
  76998. * This requires draw buffer supports
  76999. */
  77000. get: function () {
  77001. return this._multiRenderTarget.isSupported;
  77002. },
  77003. enumerable: true,
  77004. configurable: true
  77005. });
  77006. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77007. /**
  77008. * Gets wether or not position are enabled for the G buffer.
  77009. */
  77010. get: function () {
  77011. return this._enablePosition;
  77012. },
  77013. /**
  77014. * Sets wether or not position are enabled for the G buffer.
  77015. */
  77016. set: function (enable) {
  77017. this._enablePosition = enable;
  77018. this.dispose();
  77019. this._createRenderTargets();
  77020. },
  77021. enumerable: true,
  77022. configurable: true
  77023. });
  77024. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77025. /**
  77026. * Gets the scene associated with the buffer.
  77027. */
  77028. get: function () {
  77029. return this._scene;
  77030. },
  77031. enumerable: true,
  77032. configurable: true
  77033. });
  77034. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77035. /**
  77036. * Gets the ratio used by the buffer during its creation.
  77037. * How big is the buffer related to the main canvas.
  77038. */
  77039. get: function () {
  77040. return this._ratio;
  77041. },
  77042. enumerable: true,
  77043. configurable: true
  77044. });
  77045. /**
  77046. * Checks wether everything is ready to render a submesh to the G buffer.
  77047. * @param subMesh the submesh to check readiness for
  77048. * @param useInstances is the mesh drawn using instance or not
  77049. * @returns true if ready otherwise false
  77050. */
  77051. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77052. var material = subMesh.getMaterial();
  77053. if (material && material.disableDepthWrite) {
  77054. return false;
  77055. }
  77056. var defines = [];
  77057. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77058. var mesh = subMesh.getMesh();
  77059. // Alpha test
  77060. if (material && material.needAlphaTesting()) {
  77061. defines.push("#define ALPHATEST");
  77062. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77063. attribs.push(BABYLON.VertexBuffer.UVKind);
  77064. defines.push("#define UV1");
  77065. }
  77066. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77067. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77068. defines.push("#define UV2");
  77069. }
  77070. }
  77071. // Buffers
  77072. if (this._enablePosition) {
  77073. defines.push("#define POSITION");
  77074. }
  77075. // Bones
  77076. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77077. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77078. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77079. if (mesh.numBoneInfluencers > 4) {
  77080. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77081. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77082. }
  77083. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77084. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77085. }
  77086. else {
  77087. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77088. }
  77089. // Instances
  77090. if (useInstances) {
  77091. defines.push("#define INSTANCES");
  77092. attribs.push("world0");
  77093. attribs.push("world1");
  77094. attribs.push("world2");
  77095. attribs.push("world3");
  77096. }
  77097. // Get correct effect
  77098. var join = defines.join("\n");
  77099. if (this._cachedDefines !== join) {
  77100. this._cachedDefines = join;
  77101. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77102. }
  77103. return this._effect.isReady();
  77104. };
  77105. /**
  77106. * Gets the current underlying G Buffer.
  77107. * @returns the buffer
  77108. */
  77109. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77110. return this._multiRenderTarget;
  77111. };
  77112. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77113. /**
  77114. * Gets the number of samples used to render the buffer (anti aliasing).
  77115. */
  77116. get: function () {
  77117. return this._multiRenderTarget.samples;
  77118. },
  77119. /**
  77120. * Sets the number of samples used to render the buffer (anti aliasing).
  77121. */
  77122. set: function (value) {
  77123. this._multiRenderTarget.samples = value;
  77124. },
  77125. enumerable: true,
  77126. configurable: true
  77127. });
  77128. /**
  77129. * Disposes the renderer and frees up associated resources.
  77130. */
  77131. GeometryBufferRenderer.prototype.dispose = function () {
  77132. this.getGBuffer().dispose();
  77133. };
  77134. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77135. var _this = this;
  77136. var engine = this._scene.getEngine();
  77137. var count = this._enablePosition ? 3 : 2;
  77138. 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 });
  77139. if (!this.isSupported) {
  77140. return;
  77141. }
  77142. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77143. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77144. this._multiRenderTarget.refreshRate = 1;
  77145. this._multiRenderTarget.renderParticles = false;
  77146. this._multiRenderTarget.renderList = null;
  77147. // set default depth value to 1.0 (far away)
  77148. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77149. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77150. });
  77151. // Custom render function
  77152. var renderSubMesh = function (subMesh) {
  77153. var mesh = subMesh.getRenderingMesh();
  77154. var scene = _this._scene;
  77155. var engine = scene.getEngine();
  77156. var material = subMesh.getMaterial();
  77157. if (!material) {
  77158. return;
  77159. }
  77160. // Culling
  77161. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77162. // Managing instances
  77163. var batch = mesh._getInstancesRenderList(subMesh._id);
  77164. if (batch.mustReturn) {
  77165. return;
  77166. }
  77167. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77168. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77169. engine.enableEffect(_this._effect);
  77170. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77171. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77172. _this._effect.setMatrix("view", scene.getViewMatrix());
  77173. // Alpha test
  77174. if (material && material.needAlphaTesting()) {
  77175. var alphaTexture = material.getAlphaTestTexture();
  77176. if (alphaTexture) {
  77177. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77178. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77179. }
  77180. }
  77181. // Bones
  77182. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77183. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77184. }
  77185. // Draw
  77186. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77187. }
  77188. };
  77189. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77190. var index;
  77191. if (depthOnlySubMeshes.length) {
  77192. engine.setColorWrite(false);
  77193. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77194. renderSubMesh(depthOnlySubMeshes.data[index]);
  77195. }
  77196. engine.setColorWrite(true);
  77197. }
  77198. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77199. renderSubMesh(opaqueSubMeshes.data[index]);
  77200. }
  77201. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77202. renderSubMesh(alphaTestSubMeshes.data[index]);
  77203. }
  77204. };
  77205. };
  77206. return GeometryBufferRenderer;
  77207. }());
  77208. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77209. })(BABYLON || (BABYLON = {}));
  77210. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77211. var BABYLON;
  77212. (function (BABYLON) {
  77213. /**
  77214. * This groups together the common properties used for image processing either in direct forward pass
  77215. * or through post processing effect depending on the use of the image processing pipeline in your scene
  77216. * or not.
  77217. */
  77218. var ImageProcessingConfiguration = /** @class */ (function () {
  77219. function ImageProcessingConfiguration() {
  77220. /**
  77221. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  77222. */
  77223. this.colorCurves = new BABYLON.ColorCurves();
  77224. this._colorCurvesEnabled = false;
  77225. this._colorGradingEnabled = false;
  77226. this._colorGradingWithGreenDepth = true;
  77227. this._colorGradingBGR = true;
  77228. this._exposure = 1.0;
  77229. this._toneMappingEnabled = false;
  77230. this._contrast = 1.0;
  77231. /**
  77232. * Vignette stretch size.
  77233. */
  77234. this.vignetteStretch = 0;
  77235. /**
  77236. * Vignette centre X Offset.
  77237. */
  77238. this.vignetteCentreX = 0;
  77239. /**
  77240. * Vignette centre Y Offset.
  77241. */
  77242. this.vignetteCentreY = 0;
  77243. /**
  77244. * Vignette weight or intensity of the vignette effect.
  77245. */
  77246. this.vignetteWeight = 1.5;
  77247. /**
  77248. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77249. * if vignetteEnabled is set to true.
  77250. */
  77251. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77252. /**
  77253. * Camera field of view used by the Vignette effect.
  77254. */
  77255. this.vignetteCameraFov = 0.5;
  77256. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  77257. this._vignetteEnabled = false;
  77258. this._applyByPostProcess = false;
  77259. this._isEnabled = true;
  77260. /**
  77261. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  77262. */
  77263. this.onUpdateParameters = new BABYLON.Observable();
  77264. }
  77265. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  77266. /**
  77267. * Gets wether the color curves effect is enabled.
  77268. */
  77269. get: function () {
  77270. return this._colorCurvesEnabled;
  77271. },
  77272. /**
  77273. * Sets wether the color curves effect is enabled.
  77274. */
  77275. set: function (value) {
  77276. if (this._colorCurvesEnabled === value) {
  77277. return;
  77278. }
  77279. this._colorCurvesEnabled = value;
  77280. this._updateParameters();
  77281. },
  77282. enumerable: true,
  77283. configurable: true
  77284. });
  77285. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  77286. /**
  77287. * Gets wether the color grading effect is enabled.
  77288. */
  77289. get: function () {
  77290. return this._colorGradingEnabled;
  77291. },
  77292. /**
  77293. * Sets wether the color grading effect is enabled.
  77294. */
  77295. set: function (value) {
  77296. if (this._colorGradingEnabled === value) {
  77297. return;
  77298. }
  77299. this._colorGradingEnabled = value;
  77300. this._updateParameters();
  77301. },
  77302. enumerable: true,
  77303. configurable: true
  77304. });
  77305. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  77306. /**
  77307. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  77308. */
  77309. get: function () {
  77310. return this._colorGradingWithGreenDepth;
  77311. },
  77312. /**
  77313. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  77314. */
  77315. set: function (value) {
  77316. if (this._colorGradingWithGreenDepth === value) {
  77317. return;
  77318. }
  77319. this._colorGradingWithGreenDepth = value;
  77320. this._updateParameters();
  77321. },
  77322. enumerable: true,
  77323. configurable: true
  77324. });
  77325. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77326. /**
  77327. * Gets wether the color grading texture contains BGR values.
  77328. */
  77329. get: function () {
  77330. return this._colorGradingBGR;
  77331. },
  77332. /**
  77333. * Sets wether the color grading texture contains BGR values.
  77334. */
  77335. set: function (value) {
  77336. if (this._colorGradingBGR === value) {
  77337. return;
  77338. }
  77339. this._colorGradingBGR = value;
  77340. this._updateParameters();
  77341. },
  77342. enumerable: true,
  77343. configurable: true
  77344. });
  77345. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77346. /**
  77347. * Gets the Exposure used in the effect.
  77348. */
  77349. get: function () {
  77350. return this._exposure;
  77351. },
  77352. /**
  77353. * Sets the Exposure used in the effect.
  77354. */
  77355. set: function (value) {
  77356. if (this._exposure === value) {
  77357. return;
  77358. }
  77359. this._exposure = value;
  77360. this._updateParameters();
  77361. },
  77362. enumerable: true,
  77363. configurable: true
  77364. });
  77365. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77366. /**
  77367. * Gets wether the tone mapping effect is enabled.
  77368. */
  77369. get: function () {
  77370. return this._toneMappingEnabled;
  77371. },
  77372. /**
  77373. * Sets wether the tone mapping effect is enabled.
  77374. */
  77375. set: function (value) {
  77376. if (this._toneMappingEnabled === value) {
  77377. return;
  77378. }
  77379. this._toneMappingEnabled = value;
  77380. this._updateParameters();
  77381. },
  77382. enumerable: true,
  77383. configurable: true
  77384. });
  77385. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77386. /**
  77387. * Gets the contrast used in the effect.
  77388. */
  77389. get: function () {
  77390. return this._contrast;
  77391. },
  77392. /**
  77393. * Sets the contrast used in the effect.
  77394. */
  77395. set: function (value) {
  77396. if (this._contrast === value) {
  77397. return;
  77398. }
  77399. this._contrast = value;
  77400. this._updateParameters();
  77401. },
  77402. enumerable: true,
  77403. configurable: true
  77404. });
  77405. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77406. /**
  77407. * Gets the vignette blend mode allowing different kind of effect.
  77408. */
  77409. get: function () {
  77410. return this._vignetteBlendMode;
  77411. },
  77412. /**
  77413. * Sets the vignette blend mode allowing different kind of effect.
  77414. */
  77415. set: function (value) {
  77416. if (this._vignetteBlendMode === value) {
  77417. return;
  77418. }
  77419. this._vignetteBlendMode = value;
  77420. this._updateParameters();
  77421. },
  77422. enumerable: true,
  77423. configurable: true
  77424. });
  77425. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77426. /**
  77427. * Gets wether the vignette effect is enabled.
  77428. */
  77429. get: function () {
  77430. return this._vignetteEnabled;
  77431. },
  77432. /**
  77433. * Sets wether the vignette effect is enabled.
  77434. */
  77435. set: function (value) {
  77436. if (this._vignetteEnabled === value) {
  77437. return;
  77438. }
  77439. this._vignetteEnabled = value;
  77440. this._updateParameters();
  77441. },
  77442. enumerable: true,
  77443. configurable: true
  77444. });
  77445. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77446. /**
  77447. * Gets wether the image processing is applied through a post process or not.
  77448. */
  77449. get: function () {
  77450. return this._applyByPostProcess;
  77451. },
  77452. /**
  77453. * Sets wether the image processing is applied through a post process or not.
  77454. */
  77455. set: function (value) {
  77456. if (this._applyByPostProcess === value) {
  77457. return;
  77458. }
  77459. this._applyByPostProcess = value;
  77460. this._updateParameters();
  77461. },
  77462. enumerable: true,
  77463. configurable: true
  77464. });
  77465. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77466. /**
  77467. * Gets wether the image processing is enabled or not.
  77468. */
  77469. get: function () {
  77470. return this._isEnabled;
  77471. },
  77472. /**
  77473. * Sets wether the image processing is enabled or not.
  77474. */
  77475. set: function (value) {
  77476. if (this._isEnabled === value) {
  77477. return;
  77478. }
  77479. this._isEnabled = value;
  77480. this._updateParameters();
  77481. },
  77482. enumerable: true,
  77483. configurable: true
  77484. });
  77485. /**
  77486. * Method called each time the image processing information changes requires to recompile the effect.
  77487. */
  77488. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77489. this.onUpdateParameters.notifyObservers(this);
  77490. };
  77491. ImageProcessingConfiguration.prototype.getClassName = function () {
  77492. return "ImageProcessingConfiguration";
  77493. };
  77494. /**
  77495. * Prepare the list of uniforms associated with the Image Processing effects.
  77496. * @param uniformsList The list of uniforms used in the effect
  77497. * @param defines the list of defines currently in use
  77498. */
  77499. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77500. if (defines.EXPOSURE) {
  77501. uniforms.push("exposureLinear");
  77502. }
  77503. if (defines.CONTRAST) {
  77504. uniforms.push("contrast");
  77505. }
  77506. if (defines.COLORGRADING) {
  77507. uniforms.push("colorTransformSettings");
  77508. }
  77509. if (defines.VIGNETTE) {
  77510. uniforms.push("vInverseScreenSize");
  77511. uniforms.push("vignetteSettings1");
  77512. uniforms.push("vignetteSettings2");
  77513. }
  77514. if (defines.COLORCURVES) {
  77515. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77516. }
  77517. };
  77518. /**
  77519. * Prepare the list of samplers associated with the Image Processing effects.
  77520. * @param uniformsList The list of uniforms used in the effect
  77521. * @param defines the list of defines currently in use
  77522. */
  77523. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77524. if (defines.COLORGRADING) {
  77525. samplersList.push("txColorTransform");
  77526. }
  77527. };
  77528. /**
  77529. * Prepare the list of defines associated to the shader.
  77530. * @param defines the list of defines to complete
  77531. */
  77532. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77533. if (forPostProcess === void 0) { forPostProcess = false; }
  77534. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77535. defines.VIGNETTE = false;
  77536. defines.TONEMAPPING = false;
  77537. defines.CONTRAST = false;
  77538. defines.EXPOSURE = false;
  77539. defines.COLORCURVES = false;
  77540. defines.COLORGRADING = false;
  77541. defines.COLORGRADING3D = false;
  77542. defines.IMAGEPROCESSING = false;
  77543. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77544. return;
  77545. }
  77546. defines.VIGNETTE = this.vignetteEnabled;
  77547. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77548. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77549. defines.TONEMAPPING = this.toneMappingEnabled;
  77550. defines.CONTRAST = (this.contrast !== 1.0);
  77551. defines.EXPOSURE = (this.exposure !== 1.0);
  77552. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77553. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77554. if (defines.COLORGRADING) {
  77555. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77556. }
  77557. else {
  77558. defines.COLORGRADING3D = false;
  77559. }
  77560. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77561. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77562. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77563. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77564. };
  77565. /**
  77566. * Returns true if all the image processing information are ready.
  77567. */
  77568. ImageProcessingConfiguration.prototype.isReady = function () {
  77569. // Color Grading texure can not be none blocking.
  77570. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77571. };
  77572. /**
  77573. * Binds the image processing to the shader.
  77574. * @param effect The effect to bind to
  77575. */
  77576. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77577. if (aspectRatio === void 0) { aspectRatio = 1; }
  77578. // Color Curves
  77579. if (this._colorCurvesEnabled && this.colorCurves) {
  77580. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77581. }
  77582. // Vignette
  77583. if (this._vignetteEnabled) {
  77584. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77585. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77586. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77587. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77588. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77589. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77590. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77591. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77592. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77593. var vignettePower = -2.0 * this.vignetteWeight;
  77594. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77595. }
  77596. // Exposure
  77597. effect.setFloat("exposureLinear", this.exposure);
  77598. // Contrast
  77599. effect.setFloat("contrast", this.contrast);
  77600. // Color transform settings
  77601. if (this.colorGradingTexture) {
  77602. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77603. var textureSize = this.colorGradingTexture.getSize().height;
  77604. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77605. 0.5 / textureSize, // textureOffset
  77606. textureSize, // textureSize
  77607. this.colorGradingTexture.level // weight
  77608. );
  77609. }
  77610. };
  77611. /**
  77612. * Clones the current image processing instance.
  77613. * @return The cloned image processing
  77614. */
  77615. ImageProcessingConfiguration.prototype.clone = function () {
  77616. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77617. };
  77618. /**
  77619. * Serializes the current image processing instance to a json representation.
  77620. * @return a JSON representation
  77621. */
  77622. ImageProcessingConfiguration.prototype.serialize = function () {
  77623. return BABYLON.SerializationHelper.Serialize(this);
  77624. };
  77625. /**
  77626. * Parses the image processing from a json representation.
  77627. * @param source the JSON source to parse
  77628. * @return The parsed image processing
  77629. */
  77630. ImageProcessingConfiguration.Parse = function (source) {
  77631. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77632. };
  77633. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77634. /**
  77635. * Used to apply the vignette as a mix with the pixel color.
  77636. */
  77637. get: function () {
  77638. return this._VIGNETTEMODE_MULTIPLY;
  77639. },
  77640. enumerable: true,
  77641. configurable: true
  77642. });
  77643. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77644. /**
  77645. * Used to apply the vignette as a replacement of the pixel color.
  77646. */
  77647. get: function () {
  77648. return this._VIGNETTEMODE_OPAQUE;
  77649. },
  77650. enumerable: true,
  77651. configurable: true
  77652. });
  77653. // Static constants associated to the image processing.
  77654. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77655. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77656. __decorate([
  77657. BABYLON.serializeAsColorCurves()
  77658. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77659. __decorate([
  77660. BABYLON.serialize()
  77661. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77662. __decorate([
  77663. BABYLON.serializeAsTexture()
  77664. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77665. __decorate([
  77666. BABYLON.serialize()
  77667. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77668. __decorate([
  77669. BABYLON.serialize()
  77670. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77671. __decorate([
  77672. BABYLON.serialize()
  77673. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77674. __decorate([
  77675. BABYLON.serialize()
  77676. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77677. __decorate([
  77678. BABYLON.serialize()
  77679. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77680. __decorate([
  77681. BABYLON.serialize()
  77682. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77683. __decorate([
  77684. BABYLON.serialize()
  77685. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77686. __decorate([
  77687. BABYLON.serialize()
  77688. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77689. __decorate([
  77690. BABYLON.serialize()
  77691. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77692. __decorate([
  77693. BABYLON.serialize()
  77694. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77695. __decorate([
  77696. BABYLON.serializeAsColor4()
  77697. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77698. __decorate([
  77699. BABYLON.serialize()
  77700. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77701. __decorate([
  77702. BABYLON.serialize()
  77703. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77704. __decorate([
  77705. BABYLON.serialize()
  77706. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77707. __decorate([
  77708. BABYLON.serialize()
  77709. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77710. __decorate([
  77711. BABYLON.serialize()
  77712. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77713. return ImageProcessingConfiguration;
  77714. }());
  77715. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77716. })(BABYLON || (BABYLON = {}));
  77717. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77718. var BABYLON;
  77719. (function (BABYLON) {
  77720. /**
  77721. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77722. * It can help converting any input color in a desired output one. This can then be used to create effects
  77723. * from sepia, black and white to sixties or futuristic rendering...
  77724. *
  77725. * The only supported format is currently 3dl.
  77726. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77727. */
  77728. var ColorGradingTexture = /** @class */ (function (_super) {
  77729. __extends(ColorGradingTexture, _super);
  77730. /**
  77731. * Instantiates a ColorGradingTexture from the following parameters.
  77732. *
  77733. * @param url The location of the color gradind data (currently only supporting 3dl)
  77734. * @param scene The scene the texture will be used in
  77735. */
  77736. function ColorGradingTexture(url, scene) {
  77737. var _this = _super.call(this, scene) || this;
  77738. if (!url) {
  77739. return _this;
  77740. }
  77741. _this._engine = scene.getEngine();
  77742. _this._textureMatrix = BABYLON.Matrix.Identity();
  77743. _this.name = url;
  77744. _this.url = url;
  77745. _this.hasAlpha = false;
  77746. _this.isCube = false;
  77747. _this.is3D = _this._engine.webGLVersion > 1;
  77748. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77749. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77750. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77751. _this.anisotropicFilteringLevel = 1;
  77752. _this._texture = _this._getFromCache(url, true);
  77753. if (!_this._texture) {
  77754. if (!scene.useDelayedTextureLoading) {
  77755. _this.loadTexture();
  77756. }
  77757. else {
  77758. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77759. }
  77760. }
  77761. return _this;
  77762. }
  77763. /**
  77764. * Returns the texture matrix used in most of the material.
  77765. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77766. */
  77767. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77768. return this._textureMatrix;
  77769. };
  77770. /**
  77771. * Occurs when the file being loaded is a .3dl LUT file.
  77772. */
  77773. ColorGradingTexture.prototype.load3dlTexture = function () {
  77774. var engine = this._engine;
  77775. var texture;
  77776. if (engine.webGLVersion === 1) {
  77777. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77778. }
  77779. else {
  77780. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77781. }
  77782. this._texture = texture;
  77783. var callback = function (text) {
  77784. if (typeof text !== "string") {
  77785. return;
  77786. }
  77787. var data = null;
  77788. var tempData = null;
  77789. var line;
  77790. var lines = text.split('\n');
  77791. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77792. var maxColor = 0;
  77793. for (var i = 0; i < lines.length; i++) {
  77794. line = lines[i];
  77795. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77796. continue;
  77797. if (line.indexOf('#') === 0)
  77798. continue;
  77799. var words = line.split(" ");
  77800. if (size === 0) {
  77801. // Number of space + one
  77802. size = words.length;
  77803. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77804. tempData = new Float32Array(size * size * size * 4);
  77805. continue;
  77806. }
  77807. if (size != 0) {
  77808. var r = Math.max(parseInt(words[0]), 0);
  77809. var g = Math.max(parseInt(words[1]), 0);
  77810. var b = Math.max(parseInt(words[2]), 0);
  77811. maxColor = Math.max(r, maxColor);
  77812. maxColor = Math.max(g, maxColor);
  77813. maxColor = Math.max(b, maxColor);
  77814. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77815. if (tempData) {
  77816. tempData[pixelStorageIndex + 0] = r;
  77817. tempData[pixelStorageIndex + 1] = g;
  77818. tempData[pixelStorageIndex + 2] = b;
  77819. }
  77820. pixelIndexSlice++;
  77821. if (pixelIndexSlice % size == 0) {
  77822. pixelIndexH++;
  77823. pixelIndexSlice = 0;
  77824. if (pixelIndexH % size == 0) {
  77825. pixelIndexW++;
  77826. pixelIndexH = 0;
  77827. }
  77828. }
  77829. }
  77830. }
  77831. if (tempData && data) {
  77832. for (var i = 0; i < tempData.length; i++) {
  77833. if (i > 0 && (i + 1) % 4 === 0) {
  77834. data[i] = 255;
  77835. }
  77836. else {
  77837. var value = tempData[i];
  77838. data[i] = (value / maxColor * 255);
  77839. }
  77840. }
  77841. }
  77842. if (texture.is3D) {
  77843. texture.updateSize(size, size, size);
  77844. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77845. }
  77846. else {
  77847. texture.updateSize(size * size, size);
  77848. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77849. }
  77850. };
  77851. var scene = this.getScene();
  77852. if (scene) {
  77853. scene._loadFile(this.url, callback);
  77854. }
  77855. else {
  77856. this._engine._loadFile(this.url, callback);
  77857. }
  77858. return this._texture;
  77859. };
  77860. /**
  77861. * Starts the loading process of the texture.
  77862. */
  77863. ColorGradingTexture.prototype.loadTexture = function () {
  77864. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77865. this.load3dlTexture();
  77866. }
  77867. };
  77868. /**
  77869. * Clones the color gradind texture.
  77870. */
  77871. ColorGradingTexture.prototype.clone = function () {
  77872. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77873. // Base texture
  77874. newTexture.level = this.level;
  77875. return newTexture;
  77876. };
  77877. /**
  77878. * Called during delayed load for textures.
  77879. */
  77880. ColorGradingTexture.prototype.delayLoad = function () {
  77881. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77882. return;
  77883. }
  77884. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77885. this._texture = this._getFromCache(this.url, true);
  77886. if (!this._texture) {
  77887. this.loadTexture();
  77888. }
  77889. };
  77890. /**
  77891. * Parses a color grading texture serialized by Babylon.
  77892. * @param parsedTexture The texture information being parsedTexture
  77893. * @param scene The scene to load the texture in
  77894. * @param rootUrl The root url of the data assets to load
  77895. * @return A color gradind texture
  77896. */
  77897. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77898. var texture = null;
  77899. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77900. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77901. texture.name = parsedTexture.name;
  77902. texture.level = parsedTexture.level;
  77903. }
  77904. return texture;
  77905. };
  77906. /**
  77907. * Serializes the LUT texture to json format.
  77908. */
  77909. ColorGradingTexture.prototype.serialize = function () {
  77910. if (!this.name) {
  77911. return null;
  77912. }
  77913. var serializationObject = {};
  77914. serializationObject.name = this.name;
  77915. serializationObject.level = this.level;
  77916. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77917. return serializationObject;
  77918. };
  77919. /**
  77920. * Empty line regex stored for GC.
  77921. */
  77922. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77923. return ColorGradingTexture;
  77924. }(BABYLON.BaseTexture));
  77925. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77926. })(BABYLON || (BABYLON = {}));
  77927. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77928. var BABYLON;
  77929. (function (BABYLON) {
  77930. /**
  77931. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77932. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77933. * 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;
  77934. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77935. */
  77936. var ColorCurves = /** @class */ (function () {
  77937. function ColorCurves() {
  77938. this._dirty = true;
  77939. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77940. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77941. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77942. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77943. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77944. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77945. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77946. this._globalHue = 30;
  77947. this._globalDensity = 0;
  77948. this._globalSaturation = 0;
  77949. this._globalExposure = 0;
  77950. this._highlightsHue = 30;
  77951. this._highlightsDensity = 0;
  77952. this._highlightsSaturation = 0;
  77953. this._highlightsExposure = 0;
  77954. this._midtonesHue = 30;
  77955. this._midtonesDensity = 0;
  77956. this._midtonesSaturation = 0;
  77957. this._midtonesExposure = 0;
  77958. this._shadowsHue = 30;
  77959. this._shadowsDensity = 0;
  77960. this._shadowsSaturation = 0;
  77961. this._shadowsExposure = 0;
  77962. }
  77963. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77964. /**
  77965. * Gets the global Hue value.
  77966. * 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).
  77967. */
  77968. get: function () {
  77969. return this._globalHue;
  77970. },
  77971. /**
  77972. * Sets the global Hue value.
  77973. * 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).
  77974. */
  77975. set: function (value) {
  77976. this._globalHue = value;
  77977. this._dirty = true;
  77978. },
  77979. enumerable: true,
  77980. configurable: true
  77981. });
  77982. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77983. /**
  77984. * Gets the global Density value.
  77985. * 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.
  77986. * Values less than zero provide a filter of opposite hue.
  77987. */
  77988. get: function () {
  77989. return this._globalDensity;
  77990. },
  77991. /**
  77992. * Sets the global Density value.
  77993. * 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.
  77994. * Values less than zero provide a filter of opposite hue.
  77995. */
  77996. set: function (value) {
  77997. this._globalDensity = value;
  77998. this._dirty = true;
  77999. },
  78000. enumerable: true,
  78001. configurable: true
  78002. });
  78003. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  78004. /**
  78005. * Gets the global Saturation value.
  78006. * 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.
  78007. */
  78008. get: function () {
  78009. return this._globalSaturation;
  78010. },
  78011. /**
  78012. * Sets the global Saturation value.
  78013. * 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.
  78014. */
  78015. set: function (value) {
  78016. this._globalSaturation = value;
  78017. this._dirty = true;
  78018. },
  78019. enumerable: true,
  78020. configurable: true
  78021. });
  78022. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  78023. /**
  78024. * Gets the global Exposure value.
  78025. * 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.
  78026. */
  78027. get: function () {
  78028. return this._globalExposure;
  78029. },
  78030. /**
  78031. * Sets the global Exposure value.
  78032. * 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.
  78033. */
  78034. set: function (value) {
  78035. this._globalExposure = value;
  78036. this._dirty = true;
  78037. },
  78038. enumerable: true,
  78039. configurable: true
  78040. });
  78041. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  78042. /**
  78043. * Gets the highlights Hue value.
  78044. * 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).
  78045. */
  78046. get: function () {
  78047. return this._highlightsHue;
  78048. },
  78049. /**
  78050. * Sets the highlights Hue value.
  78051. * 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).
  78052. */
  78053. set: function (value) {
  78054. this._highlightsHue = value;
  78055. this._dirty = true;
  78056. },
  78057. enumerable: true,
  78058. configurable: true
  78059. });
  78060. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  78061. /**
  78062. * Gets the highlights Density value.
  78063. * 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.
  78064. * Values less than zero provide a filter of opposite hue.
  78065. */
  78066. get: function () {
  78067. return this._highlightsDensity;
  78068. },
  78069. /**
  78070. * Sets the highlights Density value.
  78071. * 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.
  78072. * Values less than zero provide a filter of opposite hue.
  78073. */
  78074. set: function (value) {
  78075. this._highlightsDensity = value;
  78076. this._dirty = true;
  78077. },
  78078. enumerable: true,
  78079. configurable: true
  78080. });
  78081. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  78082. /**
  78083. * Gets the highlights Saturation value.
  78084. * 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.
  78085. */
  78086. get: function () {
  78087. return this._highlightsSaturation;
  78088. },
  78089. /**
  78090. * Sets the highlights Saturation value.
  78091. * 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.
  78092. */
  78093. set: function (value) {
  78094. this._highlightsSaturation = value;
  78095. this._dirty = true;
  78096. },
  78097. enumerable: true,
  78098. configurable: true
  78099. });
  78100. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  78101. /**
  78102. * Gets the highlights Exposure value.
  78103. * 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.
  78104. */
  78105. get: function () {
  78106. return this._highlightsExposure;
  78107. },
  78108. /**
  78109. * Sets the highlights Exposure value.
  78110. * 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.
  78111. */
  78112. set: function (value) {
  78113. this._highlightsExposure = value;
  78114. this._dirty = true;
  78115. },
  78116. enumerable: true,
  78117. configurable: true
  78118. });
  78119. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  78120. /**
  78121. * Gets the midtones Hue value.
  78122. * 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).
  78123. */
  78124. get: function () {
  78125. return this._midtonesHue;
  78126. },
  78127. /**
  78128. * Sets the midtones Hue value.
  78129. * 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).
  78130. */
  78131. set: function (value) {
  78132. this._midtonesHue = value;
  78133. this._dirty = true;
  78134. },
  78135. enumerable: true,
  78136. configurable: true
  78137. });
  78138. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  78139. /**
  78140. * Gets the midtones Density value.
  78141. * 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.
  78142. * Values less than zero provide a filter of opposite hue.
  78143. */
  78144. get: function () {
  78145. return this._midtonesDensity;
  78146. },
  78147. /**
  78148. * Sets the midtones Density value.
  78149. * 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.
  78150. * Values less than zero provide a filter of opposite hue.
  78151. */
  78152. set: function (value) {
  78153. this._midtonesDensity = value;
  78154. this._dirty = true;
  78155. },
  78156. enumerable: true,
  78157. configurable: true
  78158. });
  78159. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  78160. /**
  78161. * Gets the midtones Saturation value.
  78162. * 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.
  78163. */
  78164. get: function () {
  78165. return this._midtonesSaturation;
  78166. },
  78167. /**
  78168. * Sets the midtones Saturation value.
  78169. * 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.
  78170. */
  78171. set: function (value) {
  78172. this._midtonesSaturation = value;
  78173. this._dirty = true;
  78174. },
  78175. enumerable: true,
  78176. configurable: true
  78177. });
  78178. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  78179. /**
  78180. * Gets the midtones Exposure value.
  78181. * 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.
  78182. */
  78183. get: function () {
  78184. return this._midtonesExposure;
  78185. },
  78186. /**
  78187. * Sets the midtones Exposure value.
  78188. * 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.
  78189. */
  78190. set: function (value) {
  78191. this._midtonesExposure = value;
  78192. this._dirty = true;
  78193. },
  78194. enumerable: true,
  78195. configurable: true
  78196. });
  78197. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  78198. /**
  78199. * Gets the shadows Hue value.
  78200. * 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).
  78201. */
  78202. get: function () {
  78203. return this._shadowsHue;
  78204. },
  78205. /**
  78206. * Sets the shadows Hue value.
  78207. * 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).
  78208. */
  78209. set: function (value) {
  78210. this._shadowsHue = value;
  78211. this._dirty = true;
  78212. },
  78213. enumerable: true,
  78214. configurable: true
  78215. });
  78216. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  78217. /**
  78218. * Gets the shadows Density value.
  78219. * 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.
  78220. * Values less than zero provide a filter of opposite hue.
  78221. */
  78222. get: function () {
  78223. return this._shadowsDensity;
  78224. },
  78225. /**
  78226. * Sets the shadows Density value.
  78227. * 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.
  78228. * Values less than zero provide a filter of opposite hue.
  78229. */
  78230. set: function (value) {
  78231. this._shadowsDensity = value;
  78232. this._dirty = true;
  78233. },
  78234. enumerable: true,
  78235. configurable: true
  78236. });
  78237. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  78238. /**
  78239. * Gets the shadows Saturation value.
  78240. * 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.
  78241. */
  78242. get: function () {
  78243. return this._shadowsSaturation;
  78244. },
  78245. /**
  78246. * Sets the shadows Saturation value.
  78247. * 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.
  78248. */
  78249. set: function (value) {
  78250. this._shadowsSaturation = value;
  78251. this._dirty = true;
  78252. },
  78253. enumerable: true,
  78254. configurable: true
  78255. });
  78256. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  78257. /**
  78258. * Gets the shadows Exposure value.
  78259. * 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.
  78260. */
  78261. get: function () {
  78262. return this._shadowsExposure;
  78263. },
  78264. /**
  78265. * Sets the shadows Exposure value.
  78266. * 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.
  78267. */
  78268. set: function (value) {
  78269. this._shadowsExposure = value;
  78270. this._dirty = true;
  78271. },
  78272. enumerable: true,
  78273. configurable: true
  78274. });
  78275. ColorCurves.prototype.getClassName = function () {
  78276. return "ColorCurves";
  78277. };
  78278. /**
  78279. * Binds the color curves to the shader.
  78280. * @param colorCurves The color curve to bind
  78281. * @param effect The effect to bind to
  78282. */
  78283. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  78284. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  78285. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  78286. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  78287. if (colorCurves._dirty) {
  78288. colorCurves._dirty = false;
  78289. // Fill in global info.
  78290. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  78291. // Compute highlights info.
  78292. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  78293. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  78294. // Compute midtones info.
  78295. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  78296. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  78297. // Compute shadows info.
  78298. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  78299. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  78300. // Compute deltas (neutral is midtones).
  78301. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  78302. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  78303. }
  78304. if (effect) {
  78305. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  78306. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  78307. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  78308. }
  78309. };
  78310. /**
  78311. * Prepare the list of uniforms associated with the ColorCurves effects.
  78312. * @param uniformsList The list of uniforms used in the effect
  78313. */
  78314. ColorCurves.PrepareUniforms = function (uniformsList) {
  78315. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  78316. };
  78317. /**
  78318. * Returns color grading data based on a hue, density, saturation and exposure value.
  78319. * @param filterHue The hue of the color filter.
  78320. * @param filterDensity The density of the color filter.
  78321. * @param saturation The saturation.
  78322. * @param exposure The exposure.
  78323. * @param result The result data container.
  78324. */
  78325. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78326. if (hue == null) {
  78327. return;
  78328. }
  78329. hue = ColorCurves.clamp(hue, 0, 360);
  78330. density = ColorCurves.clamp(density, -100, 100);
  78331. saturation = ColorCurves.clamp(saturation, -100, 100);
  78332. exposure = ColorCurves.clamp(exposure, -100, 100);
  78333. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78334. // so that the maximum filter density is only 50% control. This provides fine control
  78335. // for small values and reasonable range.
  78336. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78337. density *= 0.5;
  78338. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78339. if (density < 0) {
  78340. density *= -1;
  78341. hue = (hue + 180) % 360;
  78342. }
  78343. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78344. result.scaleToRef(2, result);
  78345. result.a = 1 + 0.01 * saturation;
  78346. };
  78347. /**
  78348. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78349. * @param value The input slider value in range [-100,100].
  78350. * @returns Adjusted value.
  78351. */
  78352. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78353. value /= 100;
  78354. var x = Math.abs(value);
  78355. x = Math.pow(x, 2);
  78356. if (value < 0) {
  78357. x *= -1;
  78358. }
  78359. x *= 100;
  78360. return x;
  78361. };
  78362. /**
  78363. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78364. * @param hue The hue (H) input.
  78365. * @param saturation The saturation (S) input.
  78366. * @param brightness The brightness (B) input.
  78367. * @result An RGBA color represented as Vector4.
  78368. */
  78369. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78370. var h = ColorCurves.clamp(hue, 0, 360);
  78371. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78372. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78373. if (s === 0) {
  78374. result.r = v;
  78375. result.g = v;
  78376. result.b = v;
  78377. }
  78378. else {
  78379. // sector 0 to 5
  78380. h /= 60;
  78381. var i = Math.floor(h);
  78382. // fractional part of h
  78383. var f = h - i;
  78384. var p = v * (1 - s);
  78385. var q = v * (1 - s * f);
  78386. var t = v * (1 - s * (1 - f));
  78387. switch (i) {
  78388. case 0:
  78389. result.r = v;
  78390. result.g = t;
  78391. result.b = p;
  78392. break;
  78393. case 1:
  78394. result.r = q;
  78395. result.g = v;
  78396. result.b = p;
  78397. break;
  78398. case 2:
  78399. result.r = p;
  78400. result.g = v;
  78401. result.b = t;
  78402. break;
  78403. case 3:
  78404. result.r = p;
  78405. result.g = q;
  78406. result.b = v;
  78407. break;
  78408. case 4:
  78409. result.r = t;
  78410. result.g = p;
  78411. result.b = v;
  78412. break;
  78413. default: // case 5:
  78414. result.r = v;
  78415. result.g = p;
  78416. result.b = q;
  78417. break;
  78418. }
  78419. }
  78420. result.a = 1;
  78421. };
  78422. /**
  78423. * Returns a value clamped between min and max
  78424. * @param value The value to clamp
  78425. * @param min The minimum of value
  78426. * @param max The maximum of value
  78427. * @returns The clamped value.
  78428. */
  78429. ColorCurves.clamp = function (value, min, max) {
  78430. return Math.min(Math.max(value, min), max);
  78431. };
  78432. /**
  78433. * Clones the current color curve instance.
  78434. * @return The cloned curves
  78435. */
  78436. ColorCurves.prototype.clone = function () {
  78437. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78438. };
  78439. /**
  78440. * Serializes the current color curve instance to a json representation.
  78441. * @return a JSON representation
  78442. */
  78443. ColorCurves.prototype.serialize = function () {
  78444. return BABYLON.SerializationHelper.Serialize(this);
  78445. };
  78446. /**
  78447. * Parses the color curve from a json representation.
  78448. * @param source the JSON source to parse
  78449. * @return The parsed curves
  78450. */
  78451. ColorCurves.Parse = function (source) {
  78452. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78453. };
  78454. __decorate([
  78455. BABYLON.serialize()
  78456. ], ColorCurves.prototype, "_globalHue", void 0);
  78457. __decorate([
  78458. BABYLON.serialize()
  78459. ], ColorCurves.prototype, "_globalDensity", void 0);
  78460. __decorate([
  78461. BABYLON.serialize()
  78462. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78463. __decorate([
  78464. BABYLON.serialize()
  78465. ], ColorCurves.prototype, "_globalExposure", void 0);
  78466. __decorate([
  78467. BABYLON.serialize()
  78468. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78469. __decorate([
  78470. BABYLON.serialize()
  78471. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78472. __decorate([
  78473. BABYLON.serialize()
  78474. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78475. __decorate([
  78476. BABYLON.serialize()
  78477. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78478. __decorate([
  78479. BABYLON.serialize()
  78480. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78481. __decorate([
  78482. BABYLON.serialize()
  78483. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78484. __decorate([
  78485. BABYLON.serialize()
  78486. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78487. __decorate([
  78488. BABYLON.serialize()
  78489. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78490. return ColorCurves;
  78491. }());
  78492. BABYLON.ColorCurves = ColorCurves;
  78493. })(BABYLON || (BABYLON = {}));
  78494. //# sourceMappingURL=babylon.colorCurves.js.map
  78495. var BABYLON;
  78496. (function (BABYLON) {
  78497. var RefractionPostProcess = /** @class */ (function (_super) {
  78498. __extends(RefractionPostProcess, _super);
  78499. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78500. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78501. _this.color = color;
  78502. _this.depth = depth;
  78503. _this.colorLevel = colorLevel;
  78504. _this._ownRefractionTexture = true;
  78505. _this.onActivateObservable.add(function (cam) {
  78506. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78507. });
  78508. _this.onApplyObservable.add(function (effect) {
  78509. effect.setColor3("baseColor", _this.color);
  78510. effect.setFloat("depth", _this.depth);
  78511. effect.setFloat("colorLevel", _this.colorLevel);
  78512. effect.setTexture("refractionSampler", _this._refTexture);
  78513. });
  78514. return _this;
  78515. }
  78516. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78517. /**
  78518. * Gets or sets the refraction texture
  78519. * Please note that you are responsible for disposing the texture if you set it manually
  78520. */
  78521. get: function () {
  78522. return this._refTexture;
  78523. },
  78524. set: function (value) {
  78525. if (this._refTexture && this._ownRefractionTexture) {
  78526. this._refTexture.dispose();
  78527. }
  78528. this._refTexture = value;
  78529. this._ownRefractionTexture = false;
  78530. },
  78531. enumerable: true,
  78532. configurable: true
  78533. });
  78534. // Methods
  78535. RefractionPostProcess.prototype.dispose = function (camera) {
  78536. if (this._refTexture && this._ownRefractionTexture) {
  78537. this._refTexture.dispose();
  78538. this._refTexture = null;
  78539. }
  78540. _super.prototype.dispose.call(this, camera);
  78541. };
  78542. return RefractionPostProcess;
  78543. }(BABYLON.PostProcess));
  78544. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78545. })(BABYLON || (BABYLON = {}));
  78546. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78547. var BABYLON;
  78548. (function (BABYLON) {
  78549. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78550. __extends(BlackAndWhitePostProcess, _super);
  78551. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78552. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78553. _this.degree = 1;
  78554. _this.onApplyObservable.add(function (effect) {
  78555. effect.setFloat("degree", _this.degree);
  78556. });
  78557. return _this;
  78558. }
  78559. return BlackAndWhitePostProcess;
  78560. }(BABYLON.PostProcess));
  78561. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78562. })(BABYLON || (BABYLON = {}));
  78563. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78564. var BABYLON;
  78565. (function (BABYLON) {
  78566. /**
  78567. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78568. * input texture to perform effects such as edge detection or sharpening
  78569. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78570. */
  78571. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78572. __extends(ConvolutionPostProcess, _super);
  78573. /**
  78574. * Creates a new instance ConvolutionPostProcess
  78575. * @param name The name of the effect.
  78576. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78577. * @param options The required width/height ratio to downsize to before computing the render pass.
  78578. * @param camera The camera to apply the render pass to.
  78579. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78580. * @param engine The engine which the post process will be applied. (default: current engine)
  78581. * @param reusable If the post process can be reused on the same frame. (default: false)
  78582. * @param textureType Type of textures used when performing the post process. (default: 0)
  78583. */
  78584. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78585. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78586. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78587. _this.kernel = kernel;
  78588. _this.onApply = function (effect) {
  78589. effect.setFloat2("screenSize", _this.width, _this.height);
  78590. effect.setArray("kernel", _this.kernel);
  78591. };
  78592. return _this;
  78593. }
  78594. // Statics
  78595. /**
  78596. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78597. */
  78598. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78599. /**
  78600. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78601. */
  78602. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78603. /**
  78604. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78605. */
  78606. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78607. /**
  78608. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78609. */
  78610. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78611. /**
  78612. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78613. */
  78614. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78615. /**
  78616. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78617. */
  78618. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78619. return ConvolutionPostProcess;
  78620. }(BABYLON.PostProcess));
  78621. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78622. })(BABYLON || (BABYLON = {}));
  78623. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78624. var BABYLON;
  78625. (function (BABYLON) {
  78626. var FilterPostProcess = /** @class */ (function (_super) {
  78627. __extends(FilterPostProcess, _super);
  78628. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78629. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78630. _this.kernelMatrix = kernelMatrix;
  78631. _this.onApply = function (effect) {
  78632. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78633. };
  78634. return _this;
  78635. }
  78636. return FilterPostProcess;
  78637. }(BABYLON.PostProcess));
  78638. BABYLON.FilterPostProcess = FilterPostProcess;
  78639. })(BABYLON || (BABYLON = {}));
  78640. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78641. var BABYLON;
  78642. (function (BABYLON) {
  78643. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78644. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78645. __extends(VolumetricLightScatteringPostProcess, _super);
  78646. /**
  78647. * @constructor
  78648. * @param {string} name - The post-process name
  78649. * @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)
  78650. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78651. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78652. * @param {number} samples - The post-process quality, default 100
  78653. * @param {number} samplingMode - The post-process filtering mode
  78654. * @param {BABYLON.Engine} engine - The babylon engine
  78655. * @param {boolean} reusable - If the post-process is reusable
  78656. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78657. */
  78658. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78659. if (samples === void 0) { samples = 100; }
  78660. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78661. 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;
  78662. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78663. /**
  78664. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78665. */
  78666. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78667. /**
  78668. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78669. */
  78670. _this.useCustomMeshPosition = false;
  78671. /**
  78672. * If the post-process should inverse the light scattering direction
  78673. */
  78674. _this.invert = true;
  78675. /**
  78676. * Array containing the excluded meshes not rendered in the internal pass
  78677. */
  78678. _this.excludedMeshes = new Array();
  78679. /**
  78680. * Controls the overall intensity of the post-process
  78681. */
  78682. _this.exposure = 0.3;
  78683. /**
  78684. * Dissipates each sample's contribution in range [0, 1]
  78685. */
  78686. _this.decay = 0.96815;
  78687. /**
  78688. * Controls the overall intensity of each sample
  78689. */
  78690. _this.weight = 0.58767;
  78691. /**
  78692. * Controls the density of each sample
  78693. */
  78694. _this.density = 0.926;
  78695. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78696. engine = scene.getEngine();
  78697. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78698. // Configure mesh
  78699. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78700. // Configure
  78701. _this._createPass(scene, ratio.passRatio || ratio);
  78702. _this.onActivate = function (camera) {
  78703. if (!_this.isSupported) {
  78704. _this.dispose(camera);
  78705. }
  78706. _this.onActivate = null;
  78707. };
  78708. _this.onApplyObservable.add(function (effect) {
  78709. _this._updateMeshScreenCoordinates(scene);
  78710. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78711. effect.setFloat("exposure", _this.exposure);
  78712. effect.setFloat("decay", _this.decay);
  78713. effect.setFloat("weight", _this.weight);
  78714. effect.setFloat("density", _this.density);
  78715. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78716. });
  78717. return _this;
  78718. }
  78719. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78720. get: function () {
  78721. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78722. return false;
  78723. },
  78724. set: function (useDiffuseColor) {
  78725. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78726. },
  78727. enumerable: true,
  78728. configurable: true
  78729. });
  78730. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78731. return "VolumetricLightScatteringPostProcess";
  78732. };
  78733. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78734. var mesh = subMesh.getMesh();
  78735. // Render this.mesh as default
  78736. if (mesh === this.mesh && mesh.material) {
  78737. return mesh.material.isReady(mesh);
  78738. }
  78739. var defines = [];
  78740. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78741. var material = subMesh.getMaterial();
  78742. // Alpha test
  78743. if (material) {
  78744. if (material.needAlphaTesting()) {
  78745. defines.push("#define ALPHATEST");
  78746. }
  78747. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78748. attribs.push(BABYLON.VertexBuffer.UVKind);
  78749. defines.push("#define UV1");
  78750. }
  78751. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78752. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78753. defines.push("#define UV2");
  78754. }
  78755. }
  78756. // Bones
  78757. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78758. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78759. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78760. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78761. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78762. }
  78763. else {
  78764. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78765. }
  78766. // Instances
  78767. if (useInstances) {
  78768. defines.push("#define INSTANCES");
  78769. attribs.push("world0");
  78770. attribs.push("world1");
  78771. attribs.push("world2");
  78772. attribs.push("world3");
  78773. }
  78774. // Get correct effect
  78775. var join = defines.join("\n");
  78776. if (this._cachedDefines !== join) {
  78777. this._cachedDefines = join;
  78778. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78779. }
  78780. return this._volumetricLightScatteringPass.isReady();
  78781. };
  78782. /**
  78783. * Sets the new light position for light scattering effect
  78784. * @param {BABYLON.Vector3} The new custom light position
  78785. */
  78786. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78787. this.customMeshPosition = position;
  78788. };
  78789. /**
  78790. * Returns the light position for light scattering effect
  78791. * @return {BABYLON.Vector3} The custom light position
  78792. */
  78793. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78794. return this.customMeshPosition;
  78795. };
  78796. /**
  78797. * Disposes the internal assets and detaches the post-process from the camera
  78798. */
  78799. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78800. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78801. if (rttIndex !== -1) {
  78802. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78803. }
  78804. this._volumetricLightScatteringRTT.dispose();
  78805. _super.prototype.dispose.call(this, camera);
  78806. };
  78807. /**
  78808. * Returns the render target texture used by the post-process
  78809. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78810. */
  78811. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78812. return this._volumetricLightScatteringRTT;
  78813. };
  78814. // Private methods
  78815. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78816. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78817. return true;
  78818. }
  78819. return false;
  78820. };
  78821. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78822. var _this = this;
  78823. var engine = scene.getEngine();
  78824. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78825. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78826. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78827. this._volumetricLightScatteringRTT.renderList = null;
  78828. this._volumetricLightScatteringRTT.renderParticles = false;
  78829. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78830. var camera = this.getCamera();
  78831. if (camera) {
  78832. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78833. }
  78834. else {
  78835. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78836. }
  78837. // Custom render function for submeshes
  78838. var renderSubMesh = function (subMesh) {
  78839. var mesh = subMesh.getRenderingMesh();
  78840. if (_this._meshExcluded(mesh)) {
  78841. return;
  78842. }
  78843. var material = subMesh.getMaterial();
  78844. if (!material) {
  78845. return;
  78846. }
  78847. var scene = mesh.getScene();
  78848. var engine = scene.getEngine();
  78849. // Culling
  78850. engine.setState(material.backFaceCulling);
  78851. // Managing instances
  78852. var batch = mesh._getInstancesRenderList(subMesh._id);
  78853. if (batch.mustReturn) {
  78854. return;
  78855. }
  78856. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78857. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78858. var effect = _this._volumetricLightScatteringPass;
  78859. if (mesh === _this.mesh) {
  78860. if (subMesh.effect) {
  78861. effect = subMesh.effect;
  78862. }
  78863. else {
  78864. effect = material.getEffect();
  78865. }
  78866. }
  78867. engine.enableEffect(effect);
  78868. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78869. if (mesh === _this.mesh) {
  78870. material.bind(mesh.getWorldMatrix(), mesh);
  78871. }
  78872. else {
  78873. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78874. // Alpha test
  78875. if (material && material.needAlphaTesting()) {
  78876. var alphaTexture = material.getAlphaTestTexture();
  78877. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78878. if (alphaTexture) {
  78879. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78880. }
  78881. }
  78882. // Bones
  78883. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78884. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78885. }
  78886. }
  78887. // Draw
  78888. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78889. }
  78890. };
  78891. // Render target texture callbacks
  78892. var savedSceneClearColor;
  78893. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78894. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78895. savedSceneClearColor = scene.clearColor;
  78896. scene.clearColor = sceneClearColor;
  78897. });
  78898. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78899. scene.clearColor = savedSceneClearColor;
  78900. });
  78901. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78902. var engine = scene.getEngine();
  78903. var index;
  78904. if (depthOnlySubMeshes.length) {
  78905. engine.setColorWrite(false);
  78906. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78907. renderSubMesh(depthOnlySubMeshes.data[index]);
  78908. }
  78909. engine.setColorWrite(true);
  78910. }
  78911. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78912. renderSubMesh(opaqueSubMeshes.data[index]);
  78913. }
  78914. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78915. renderSubMesh(alphaTestSubMeshes.data[index]);
  78916. }
  78917. if (transparentSubMeshes.length) {
  78918. // Sort sub meshes
  78919. for (index = 0; index < transparentSubMeshes.length; index++) {
  78920. var submesh = transparentSubMeshes.data[index];
  78921. var boundingInfo = submesh.getBoundingInfo();
  78922. if (boundingInfo && scene.activeCamera) {
  78923. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78924. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78925. }
  78926. }
  78927. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78928. sortedArray.sort(function (a, b) {
  78929. // Alpha index first
  78930. if (a._alphaIndex > b._alphaIndex) {
  78931. return 1;
  78932. }
  78933. if (a._alphaIndex < b._alphaIndex) {
  78934. return -1;
  78935. }
  78936. // Then distance to camera
  78937. if (a._distanceToCamera < b._distanceToCamera) {
  78938. return 1;
  78939. }
  78940. if (a._distanceToCamera > b._distanceToCamera) {
  78941. return -1;
  78942. }
  78943. return 0;
  78944. });
  78945. // Render sub meshes
  78946. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78947. for (index = 0; index < sortedArray.length; index++) {
  78948. renderSubMesh(sortedArray[index]);
  78949. }
  78950. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78951. }
  78952. };
  78953. };
  78954. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78955. var transform = scene.getTransformMatrix();
  78956. var meshPosition;
  78957. if (this.useCustomMeshPosition) {
  78958. meshPosition = this.customMeshPosition;
  78959. }
  78960. else if (this.attachedNode) {
  78961. meshPosition = this.attachedNode.position;
  78962. }
  78963. else {
  78964. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78965. }
  78966. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78967. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78968. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78969. if (this.invert)
  78970. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78971. };
  78972. // Static methods
  78973. /**
  78974. * Creates a default mesh for the Volumeric Light Scattering post-process
  78975. * @param {string} The mesh name
  78976. * @param {BABYLON.Scene} The scene where to create the mesh
  78977. * @return {BABYLON.Mesh} the default mesh
  78978. */
  78979. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78980. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78981. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78982. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78983. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78984. mesh.material = material;
  78985. return mesh;
  78986. };
  78987. __decorate([
  78988. BABYLON.serializeAsVector3()
  78989. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78990. __decorate([
  78991. BABYLON.serialize()
  78992. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78993. __decorate([
  78994. BABYLON.serialize()
  78995. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78996. __decorate([
  78997. BABYLON.serializeAsMeshReference()
  78998. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78999. __decorate([
  79000. BABYLON.serialize()
  79001. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  79002. __decorate([
  79003. BABYLON.serialize()
  79004. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  79005. __decorate([
  79006. BABYLON.serialize()
  79007. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  79008. __decorate([
  79009. BABYLON.serialize()
  79010. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  79011. __decorate([
  79012. BABYLON.serialize()
  79013. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  79014. return VolumetricLightScatteringPostProcess;
  79015. }(BABYLON.PostProcess));
  79016. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  79017. })(BABYLON || (BABYLON = {}));
  79018. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  79019. //
  79020. // This post-process allows the modification of rendered colors by using
  79021. // a 'look-up table' (LUT). This effect is also called Color Grading.
  79022. //
  79023. // The object needs to be provided an url to a texture containing the color
  79024. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  79025. // Use an image editing software to tweak the LUT to match your needs.
  79026. //
  79027. // For an example of a color LUT, see here:
  79028. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  79029. // For explanations on color grading, see here:
  79030. // http://udn.epicgames.com/Three/ColorGrading.html
  79031. //
  79032. var BABYLON;
  79033. (function (BABYLON) {
  79034. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  79035. __extends(ColorCorrectionPostProcess, _super);
  79036. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  79037. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  79038. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79039. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  79040. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79041. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79042. _this.onApply = function (effect) {
  79043. effect.setTexture("colorTable", _this._colorTableTexture);
  79044. };
  79045. return _this;
  79046. }
  79047. return ColorCorrectionPostProcess;
  79048. }(BABYLON.PostProcess));
  79049. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  79050. })(BABYLON || (BABYLON = {}));
  79051. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  79052. var BABYLON;
  79053. (function (BABYLON) {
  79054. /** Defines operator used for tonemapping */
  79055. var TonemappingOperator;
  79056. (function (TonemappingOperator) {
  79057. /** Hable */
  79058. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  79059. /** Reinhard */
  79060. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  79061. /** HejiDawson */
  79062. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  79063. /** Photographic */
  79064. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  79065. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  79066. ;
  79067. /**
  79068. * Defines a post process to apply tone mapping
  79069. */
  79070. var TonemapPostProcess = /** @class */ (function (_super) {
  79071. __extends(TonemapPostProcess, _super);
  79072. /**
  79073. * Creates a new TonemapPostProcess
  79074. * @param name defines the name of the postprocess
  79075. * @param _operator defines the operator to use
  79076. * @param exposureAdjustment defines the required exposure adjustement
  79077. * @param camera defines the camera to use (can be null)
  79078. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  79079. * @param engine defines the hosting engine (can be ignore if camera is set)
  79080. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  79081. */
  79082. function TonemapPostProcess(name, _operator,
  79083. /** Defines the required exposure adjustement */
  79084. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  79085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79086. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79087. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  79088. _this._operator = _operator;
  79089. _this.exposureAdjustment = exposureAdjustment;
  79090. var defines = "#define ";
  79091. if (_this._operator === TonemappingOperator.Hable)
  79092. defines += "HABLE_TONEMAPPING";
  79093. else if (_this._operator === TonemappingOperator.Reinhard)
  79094. defines += "REINHARD_TONEMAPPING";
  79095. else if (_this._operator === TonemappingOperator.HejiDawson)
  79096. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  79097. else if (_this._operator === TonemappingOperator.Photographic)
  79098. defines += "PHOTOGRAPHIC_TONEMAPPING";
  79099. //sadly a second call to create the effect.
  79100. _this.updateEffect(defines);
  79101. _this.onApply = function (effect) {
  79102. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  79103. };
  79104. return _this;
  79105. }
  79106. return TonemapPostProcess;
  79107. }(BABYLON.PostProcess));
  79108. BABYLON.TonemapPostProcess = TonemapPostProcess;
  79109. })(BABYLON || (BABYLON = {}));
  79110. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  79111. var BABYLON;
  79112. (function (BABYLON) {
  79113. var DisplayPassPostProcess = /** @class */ (function (_super) {
  79114. __extends(DisplayPassPostProcess, _super);
  79115. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  79116. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  79117. }
  79118. return DisplayPassPostProcess;
  79119. }(BABYLON.PostProcess));
  79120. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  79121. })(BABYLON || (BABYLON = {}));
  79122. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  79123. var BABYLON;
  79124. (function (BABYLON) {
  79125. var HighlightsPostProcess = /** @class */ (function (_super) {
  79126. __extends(HighlightsPostProcess, _super);
  79127. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79128. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79129. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79130. }
  79131. return HighlightsPostProcess;
  79132. }(BABYLON.PostProcess));
  79133. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  79134. })(BABYLON || (BABYLON = {}));
  79135. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  79136. var BABYLON;
  79137. (function (BABYLON) {
  79138. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  79139. __extends(ImageProcessingPostProcess, _super);
  79140. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  79141. if (camera === void 0) { camera = null; }
  79142. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79143. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  79144. _this._fromLinearSpace = true;
  79145. /**
  79146. * Defines cache preventing GC.
  79147. */
  79148. _this._defines = {
  79149. IMAGEPROCESSING: false,
  79150. VIGNETTE: false,
  79151. VIGNETTEBLENDMODEMULTIPLY: false,
  79152. VIGNETTEBLENDMODEOPAQUE: false,
  79153. TONEMAPPING: false,
  79154. CONTRAST: false,
  79155. COLORCURVES: false,
  79156. COLORGRADING: false,
  79157. COLORGRADING3D: false,
  79158. FROMLINEARSPACE: false,
  79159. SAMPLER3DGREENDEPTH: false,
  79160. SAMPLER3DBGRMAP: false,
  79161. IMAGEPROCESSINGPOSTPROCESS: false,
  79162. EXPOSURE: false,
  79163. };
  79164. // Setup the configuration as forced by the constructor. This would then not force the
  79165. // scene materials output in linear space and let untouched the default forward pass.
  79166. if (imageProcessingConfiguration) {
  79167. imageProcessingConfiguration.applyByPostProcess = true;
  79168. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  79169. // This will cause the shader to be compiled
  79170. _this.fromLinearSpace = false;
  79171. }
  79172. // Setup the default processing configuration to the scene.
  79173. else {
  79174. _this._attachImageProcessingConfiguration(null, true);
  79175. _this.imageProcessingConfiguration.applyByPostProcess = true;
  79176. }
  79177. _this.onApply = function (effect) {
  79178. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  79179. };
  79180. return _this;
  79181. }
  79182. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  79183. /**
  79184. * Gets the image processing configuration used either in this material.
  79185. */
  79186. get: function () {
  79187. return this._imageProcessingConfiguration;
  79188. },
  79189. /**
  79190. * Sets the Default image processing configuration used either in the this material.
  79191. *
  79192. * If sets to null, the scene one is in use.
  79193. */
  79194. set: function (value) {
  79195. this._attachImageProcessingConfiguration(value);
  79196. },
  79197. enumerable: true,
  79198. configurable: true
  79199. });
  79200. /**
  79201. * Attaches a new image processing configuration to the PBR Material.
  79202. * @param configuration
  79203. */
  79204. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  79205. var _this = this;
  79206. if (doNotBuild === void 0) { doNotBuild = false; }
  79207. if (configuration === this._imageProcessingConfiguration) {
  79208. return;
  79209. }
  79210. // Detaches observer.
  79211. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79212. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79213. }
  79214. // Pick the scene configuration if needed.
  79215. if (!configuration) {
  79216. var scene = null;
  79217. var engine = this.getEngine();
  79218. var camera = this.getCamera();
  79219. if (camera) {
  79220. scene = camera.getScene();
  79221. }
  79222. else if (engine && engine.scenes) {
  79223. var scenes = engine.scenes;
  79224. scene = scenes[scenes.length - 1];
  79225. }
  79226. else {
  79227. scene = BABYLON.Engine.LastCreatedScene;
  79228. }
  79229. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  79230. }
  79231. else {
  79232. this._imageProcessingConfiguration = configuration;
  79233. }
  79234. // Attaches observer.
  79235. if (this._imageProcessingConfiguration) {
  79236. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  79237. _this._updateParameters();
  79238. });
  79239. }
  79240. // Ensure the effect will be rebuilt.
  79241. if (!doNotBuild) {
  79242. this._updateParameters();
  79243. }
  79244. };
  79245. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  79246. /**
  79247. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79248. */
  79249. get: function () {
  79250. return this.imageProcessingConfiguration.colorCurves;
  79251. },
  79252. /**
  79253. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79254. */
  79255. set: function (value) {
  79256. this.imageProcessingConfiguration.colorCurves = value;
  79257. },
  79258. enumerable: true,
  79259. configurable: true
  79260. });
  79261. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  79262. /**
  79263. * Gets wether the color curves effect is enabled.
  79264. */
  79265. get: function () {
  79266. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79267. },
  79268. /**
  79269. * Sets wether the color curves effect is enabled.
  79270. */
  79271. set: function (value) {
  79272. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79273. },
  79274. enumerable: true,
  79275. configurable: true
  79276. });
  79277. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  79278. /**
  79279. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79280. */
  79281. get: function () {
  79282. return this.imageProcessingConfiguration.colorGradingTexture;
  79283. },
  79284. /**
  79285. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79286. */
  79287. set: function (value) {
  79288. this.imageProcessingConfiguration.colorGradingTexture = value;
  79289. },
  79290. enumerable: true,
  79291. configurable: true
  79292. });
  79293. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  79294. /**
  79295. * Gets wether the color grading effect is enabled.
  79296. */
  79297. get: function () {
  79298. return this.imageProcessingConfiguration.colorGradingEnabled;
  79299. },
  79300. /**
  79301. * Gets wether the color grading effect is enabled.
  79302. */
  79303. set: function (value) {
  79304. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79305. },
  79306. enumerable: true,
  79307. configurable: true
  79308. });
  79309. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  79310. /**
  79311. * Gets exposure used in the effect.
  79312. */
  79313. get: function () {
  79314. return this.imageProcessingConfiguration.exposure;
  79315. },
  79316. /**
  79317. * Sets exposure used in the effect.
  79318. */
  79319. set: function (value) {
  79320. this.imageProcessingConfiguration.exposure = value;
  79321. },
  79322. enumerable: true,
  79323. configurable: true
  79324. });
  79325. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79326. /**
  79327. * Gets wether tonemapping is enabled or not.
  79328. */
  79329. get: function () {
  79330. return this._imageProcessingConfiguration.toneMappingEnabled;
  79331. },
  79332. /**
  79333. * Sets wether tonemapping is enabled or not
  79334. */
  79335. set: function (value) {
  79336. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79337. },
  79338. enumerable: true,
  79339. configurable: true
  79340. });
  79341. ;
  79342. ;
  79343. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79344. /**
  79345. * Gets contrast used in the effect.
  79346. */
  79347. get: function () {
  79348. return this.imageProcessingConfiguration.contrast;
  79349. },
  79350. /**
  79351. * Sets contrast used in the effect.
  79352. */
  79353. set: function (value) {
  79354. this.imageProcessingConfiguration.contrast = value;
  79355. },
  79356. enumerable: true,
  79357. configurable: true
  79358. });
  79359. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79360. /**
  79361. * Gets Vignette stretch size.
  79362. */
  79363. get: function () {
  79364. return this.imageProcessingConfiguration.vignetteStretch;
  79365. },
  79366. /**
  79367. * Sets Vignette stretch size.
  79368. */
  79369. set: function (value) {
  79370. this.imageProcessingConfiguration.vignetteStretch = value;
  79371. },
  79372. enumerable: true,
  79373. configurable: true
  79374. });
  79375. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79376. /**
  79377. * Gets Vignette centre X Offset.
  79378. */
  79379. get: function () {
  79380. return this.imageProcessingConfiguration.vignetteCentreX;
  79381. },
  79382. /**
  79383. * Sets Vignette centre X Offset.
  79384. */
  79385. set: function (value) {
  79386. this.imageProcessingConfiguration.vignetteCentreX = value;
  79387. },
  79388. enumerable: true,
  79389. configurable: true
  79390. });
  79391. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79392. /**
  79393. * Gets Vignette centre Y Offset.
  79394. */
  79395. get: function () {
  79396. return this.imageProcessingConfiguration.vignetteCentreY;
  79397. },
  79398. /**
  79399. * Sets Vignette centre Y Offset.
  79400. */
  79401. set: function (value) {
  79402. this.imageProcessingConfiguration.vignetteCentreY = value;
  79403. },
  79404. enumerable: true,
  79405. configurable: true
  79406. });
  79407. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79408. /**
  79409. * Gets Vignette weight or intensity of the vignette effect.
  79410. */
  79411. get: function () {
  79412. return this.imageProcessingConfiguration.vignetteWeight;
  79413. },
  79414. /**
  79415. * Sets Vignette weight or intensity of the vignette effect.
  79416. */
  79417. set: function (value) {
  79418. this.imageProcessingConfiguration.vignetteWeight = value;
  79419. },
  79420. enumerable: true,
  79421. configurable: true
  79422. });
  79423. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79424. /**
  79425. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79426. * if vignetteEnabled is set to true.
  79427. */
  79428. get: function () {
  79429. return this.imageProcessingConfiguration.vignetteColor;
  79430. },
  79431. /**
  79432. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79433. * if vignetteEnabled is set to true.
  79434. */
  79435. set: function (value) {
  79436. this.imageProcessingConfiguration.vignetteColor = value;
  79437. },
  79438. enumerable: true,
  79439. configurable: true
  79440. });
  79441. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79442. /**
  79443. * Gets Camera field of view used by the Vignette effect.
  79444. */
  79445. get: function () {
  79446. return this.imageProcessingConfiguration.vignetteCameraFov;
  79447. },
  79448. /**
  79449. * Sets Camera field of view used by the Vignette effect.
  79450. */
  79451. set: function (value) {
  79452. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79453. },
  79454. enumerable: true,
  79455. configurable: true
  79456. });
  79457. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79458. /**
  79459. * Gets the vignette blend mode allowing different kind of effect.
  79460. */
  79461. get: function () {
  79462. return this.imageProcessingConfiguration.vignetteBlendMode;
  79463. },
  79464. /**
  79465. * Sets the vignette blend mode allowing different kind of effect.
  79466. */
  79467. set: function (value) {
  79468. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79469. },
  79470. enumerable: true,
  79471. configurable: true
  79472. });
  79473. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79474. /**
  79475. * Gets wether the vignette effect is enabled.
  79476. */
  79477. get: function () {
  79478. return this.imageProcessingConfiguration.vignetteEnabled;
  79479. },
  79480. /**
  79481. * Sets wether the vignette effect is enabled.
  79482. */
  79483. set: function (value) {
  79484. this.imageProcessingConfiguration.vignetteEnabled = value;
  79485. },
  79486. enumerable: true,
  79487. configurable: true
  79488. });
  79489. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79490. /**
  79491. * Gets wether the input of the processing is in Gamma or Linear Space.
  79492. */
  79493. get: function () {
  79494. return this._fromLinearSpace;
  79495. },
  79496. /**
  79497. * Sets wether the input of the processing is in Gamma or Linear Space.
  79498. */
  79499. set: function (value) {
  79500. if (this._fromLinearSpace === value) {
  79501. return;
  79502. }
  79503. this._fromLinearSpace = value;
  79504. this._updateParameters();
  79505. },
  79506. enumerable: true,
  79507. configurable: true
  79508. });
  79509. ImageProcessingPostProcess.prototype.getClassName = function () {
  79510. return "ImageProcessingPostProcess";
  79511. };
  79512. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79513. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79514. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79515. var defines = "";
  79516. for (var define in this._defines) {
  79517. if (this._defines[define]) {
  79518. defines += "#define " + define + ";\r\n";
  79519. }
  79520. }
  79521. var samplers = ["textureSampler"];
  79522. var uniforms = ["scale"];
  79523. if (BABYLON.ImageProcessingConfiguration) {
  79524. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79525. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79526. }
  79527. this.updateEffect(defines, uniforms, samplers);
  79528. };
  79529. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79530. _super.prototype.dispose.call(this, camera);
  79531. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79532. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79533. }
  79534. if (this._imageProcessingConfiguration) {
  79535. this.imageProcessingConfiguration.applyByPostProcess = false;
  79536. }
  79537. };
  79538. __decorate([
  79539. BABYLON.serialize()
  79540. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79541. return ImageProcessingPostProcess;
  79542. }(BABYLON.PostProcess));
  79543. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79544. })(BABYLON || (BABYLON = {}));
  79545. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79546. var BABYLON;
  79547. (function (BABYLON) {
  79548. /**
  79549. * Class used to store bone information
  79550. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79551. */
  79552. var Bone = /** @class */ (function (_super) {
  79553. __extends(Bone, _super);
  79554. /**
  79555. * Create a new bone
  79556. * @param name defines the bone name
  79557. * @param skeleton defines the parent skeleton
  79558. * @param parentBone defines the parent (can be null if the bone is the root)
  79559. * @param localMatrix defines the local matrix
  79560. * @param restPose defines the rest pose matrix
  79561. * @param baseMatrix defines the base matrix
  79562. * @param index defines index of the bone in the hiearchy
  79563. */
  79564. function Bone(
  79565. /**
  79566. * defines the bone name
  79567. */
  79568. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79569. if (parentBone === void 0) { parentBone = null; }
  79570. if (localMatrix === void 0) { localMatrix = null; }
  79571. if (restPose === void 0) { restPose = null; }
  79572. if (baseMatrix === void 0) { baseMatrix = null; }
  79573. if (index === void 0) { index = null; }
  79574. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79575. _this.name = name;
  79576. /**
  79577. * Gets the list of child bones
  79578. */
  79579. _this.children = new Array();
  79580. /** Gets the animations associated with this bone */
  79581. _this.animations = new Array();
  79582. /**
  79583. * @hidden Internal only
  79584. * Set this value to map this bone to a different index in the transform matrices
  79585. * Set this value to -1 to exclude the bone from the transform matrices
  79586. */
  79587. _this._index = null;
  79588. _this._absoluteTransform = new BABYLON.Matrix();
  79589. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79590. _this._scalingDeterminant = 1;
  79591. _this._worldTransform = new BABYLON.Matrix();
  79592. _this._needToDecompose = true;
  79593. _this._needToCompose = false;
  79594. _this._skeleton = skeleton;
  79595. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79596. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79597. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79598. _this._index = index;
  79599. skeleton.bones.push(_this);
  79600. _this.setParent(parentBone, false);
  79601. if (baseMatrix || localMatrix) {
  79602. _this._updateDifferenceMatrix();
  79603. }
  79604. return _this;
  79605. }
  79606. Object.defineProperty(Bone.prototype, "_matrix", {
  79607. /** @hidden */
  79608. get: function () {
  79609. this._compose();
  79610. return this._localMatrix;
  79611. },
  79612. /** @hidden */
  79613. set: function (value) {
  79614. this._localMatrix.copyFrom(value);
  79615. this._needToDecompose = true;
  79616. },
  79617. enumerable: true,
  79618. configurable: true
  79619. });
  79620. // Members
  79621. /**
  79622. * Gets the parent skeleton
  79623. * @returns a skeleton
  79624. */
  79625. Bone.prototype.getSkeleton = function () {
  79626. return this._skeleton;
  79627. };
  79628. /**
  79629. * Gets parent bone
  79630. * @returns a bone or null if the bone is the root of the bone hierarchy
  79631. */
  79632. Bone.prototype.getParent = function () {
  79633. return this._parent;
  79634. };
  79635. /**
  79636. * Sets the parent bone
  79637. * @param parent defines the parent (can be null if the bone is the root)
  79638. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79639. */
  79640. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79641. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79642. if (this._parent === parent) {
  79643. return;
  79644. }
  79645. if (this._parent) {
  79646. var index = this._parent.children.indexOf(this);
  79647. if (index !== -1) {
  79648. this._parent.children.splice(index, 1);
  79649. }
  79650. }
  79651. this._parent = parent;
  79652. if (this._parent) {
  79653. this._parent.children.push(this);
  79654. }
  79655. if (updateDifferenceMatrix) {
  79656. this._updateDifferenceMatrix();
  79657. }
  79658. this.markAsDirty();
  79659. };
  79660. /**
  79661. * Gets the local matrix
  79662. * @returns a matrix
  79663. */
  79664. Bone.prototype.getLocalMatrix = function () {
  79665. this._compose();
  79666. return this._localMatrix;
  79667. };
  79668. /**
  79669. * Gets the base matrix (initial matrix which remains unchanged)
  79670. * @returns a matrix
  79671. */
  79672. Bone.prototype.getBaseMatrix = function () {
  79673. return this._baseMatrix;
  79674. };
  79675. /**
  79676. * Gets the rest pose matrix
  79677. * @returns a matrix
  79678. */
  79679. Bone.prototype.getRestPose = function () {
  79680. return this._restPose;
  79681. };
  79682. /**
  79683. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79684. */
  79685. Bone.prototype.getWorldMatrix = function () {
  79686. return this._worldTransform;
  79687. };
  79688. /**
  79689. * Sets the local matrix to rest pose matrix
  79690. */
  79691. Bone.prototype.returnToRest = function () {
  79692. this.updateMatrix(this._restPose.clone());
  79693. };
  79694. /**
  79695. * Gets the inverse of the absolute transform matrix.
  79696. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79697. * @returns a matrix
  79698. */
  79699. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79700. return this._invertedAbsoluteTransform;
  79701. };
  79702. /**
  79703. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79704. * @returns a matrix
  79705. */
  79706. Bone.prototype.getAbsoluteTransform = function () {
  79707. return this._absoluteTransform;
  79708. };
  79709. Object.defineProperty(Bone.prototype, "position", {
  79710. // Properties (matches AbstractMesh properties)
  79711. /** Gets or sets current position (in local space) */
  79712. get: function () {
  79713. this._decompose();
  79714. return this._localPosition;
  79715. },
  79716. set: function (newPosition) {
  79717. this._decompose();
  79718. this._localPosition.copyFrom(newPosition);
  79719. this._markAsDirtyAndCompose();
  79720. },
  79721. enumerable: true,
  79722. configurable: true
  79723. });
  79724. Object.defineProperty(Bone.prototype, "rotation", {
  79725. /** Gets or sets current rotation (in local space) */
  79726. get: function () {
  79727. return this.getRotation();
  79728. },
  79729. set: function (newRotation) {
  79730. this.setRotation(newRotation);
  79731. },
  79732. enumerable: true,
  79733. configurable: true
  79734. });
  79735. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79736. /** Gets or sets current rotation quaternion (in local space) */
  79737. get: function () {
  79738. this._decompose();
  79739. return this._localRotation;
  79740. },
  79741. set: function (newRotation) {
  79742. this.setRotationQuaternion(newRotation);
  79743. },
  79744. enumerable: true,
  79745. configurable: true
  79746. });
  79747. Object.defineProperty(Bone.prototype, "scaling", {
  79748. /** Gets or sets current scaling (in local space) */
  79749. get: function () {
  79750. return this.getScale();
  79751. },
  79752. set: function (newScaling) {
  79753. this.setScale(newScaling);
  79754. },
  79755. enumerable: true,
  79756. configurable: true
  79757. });
  79758. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79759. /**
  79760. * Gets the animation properties override
  79761. */
  79762. get: function () {
  79763. return this._skeleton.animationPropertiesOverride;
  79764. },
  79765. enumerable: true,
  79766. configurable: true
  79767. });
  79768. // Methods
  79769. Bone.prototype._decompose = function () {
  79770. if (!this._needToDecompose) {
  79771. return;
  79772. }
  79773. this._needToDecompose = false;
  79774. if (!this._localScaling) {
  79775. this._localScaling = BABYLON.Vector3.Zero();
  79776. this._localRotation = BABYLON.Quaternion.Zero();
  79777. this._localPosition = BABYLON.Vector3.Zero();
  79778. }
  79779. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79780. };
  79781. Bone.prototype._compose = function () {
  79782. if (!this._needToCompose) {
  79783. return;
  79784. }
  79785. this._needToCompose = false;
  79786. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79787. };
  79788. /**
  79789. * Update the base and local matrices
  79790. * @param matrix defines the new base or local matrix
  79791. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79792. * @param updateLocalMatrix defines if the local matrix should be updated
  79793. */
  79794. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79795. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79796. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79797. this._baseMatrix.copyFrom(matrix);
  79798. if (updateDifferenceMatrix) {
  79799. this._updateDifferenceMatrix();
  79800. }
  79801. if (updateLocalMatrix) {
  79802. this._localMatrix.copyFrom(matrix);
  79803. this._markAsDirtyAndDecompose();
  79804. }
  79805. else {
  79806. this.markAsDirty();
  79807. }
  79808. };
  79809. /** @hidden */
  79810. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79811. if (updateChildren === void 0) { updateChildren = true; }
  79812. if (!rootMatrix) {
  79813. rootMatrix = this._baseMatrix;
  79814. }
  79815. if (this._parent) {
  79816. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79817. }
  79818. else {
  79819. this._absoluteTransform.copyFrom(rootMatrix);
  79820. }
  79821. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79822. if (updateChildren) {
  79823. for (var index = 0; index < this.children.length; index++) {
  79824. this.children[index]._updateDifferenceMatrix();
  79825. }
  79826. }
  79827. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79828. };
  79829. /**
  79830. * Flag the bone as dirty (Forcing it to update everything)
  79831. */
  79832. Bone.prototype.markAsDirty = function () {
  79833. this._currentRenderId++;
  79834. this._childRenderId++;
  79835. this._skeleton._markAsDirty();
  79836. };
  79837. Bone.prototype._markAsDirtyAndCompose = function () {
  79838. this.markAsDirty();
  79839. this._needToCompose = true;
  79840. };
  79841. Bone.prototype._markAsDirtyAndDecompose = function () {
  79842. this.markAsDirty();
  79843. this._needToDecompose = true;
  79844. };
  79845. /**
  79846. * Copy an animation range from another bone
  79847. * @param source defines the source bone
  79848. * @param rangeName defines the range name to copy
  79849. * @param frameOffset defines the frame offset
  79850. * @param rescaleAsRequired defines if rescaling must be applied if required
  79851. * @param skelDimensionsRatio defines the scaling ratio
  79852. * @returns true if operation was successful
  79853. */
  79854. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79855. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79856. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79857. // all animation may be coming from a library skeleton, so may need to create animation
  79858. if (this.animations.length === 0) {
  79859. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79860. this.animations[0].setKeys([]);
  79861. }
  79862. // get animation info / verify there is such a range from the source bone
  79863. var sourceRange = source.animations[0].getRange(rangeName);
  79864. if (!sourceRange) {
  79865. return false;
  79866. }
  79867. var from = sourceRange.from;
  79868. var to = sourceRange.to;
  79869. var sourceKeys = source.animations[0].getKeys();
  79870. // rescaling prep
  79871. var sourceBoneLength = source.length;
  79872. var sourceParent = source.getParent();
  79873. var parent = this.getParent();
  79874. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79875. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79876. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79877. var destKeys = this.animations[0].getKeys();
  79878. // loop vars declaration
  79879. var orig;
  79880. var origTranslation;
  79881. var mat;
  79882. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79883. orig = sourceKeys[key];
  79884. if (orig.frame >= from && orig.frame <= to) {
  79885. if (rescaleAsRequired) {
  79886. mat = orig.value.clone();
  79887. // scale based on parent ratio, when bone has parent
  79888. if (parentScalingReqd) {
  79889. origTranslation = mat.getTranslation();
  79890. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79891. // scale based on skeleton dimension ratio when root bone, and value is passed
  79892. }
  79893. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79894. origTranslation = mat.getTranslation();
  79895. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79896. // use original when root bone, and no data for skelDimensionsRatio
  79897. }
  79898. else {
  79899. mat = orig.value;
  79900. }
  79901. }
  79902. else {
  79903. mat = orig.value;
  79904. }
  79905. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79906. }
  79907. }
  79908. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79909. return true;
  79910. };
  79911. /**
  79912. * Translate the bone in local or world space
  79913. * @param vec The amount to translate the bone
  79914. * @param space The space that the translation is in
  79915. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79916. */
  79917. Bone.prototype.translate = function (vec, space, mesh) {
  79918. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79919. var lm = this.getLocalMatrix();
  79920. if (space == BABYLON.Space.LOCAL) {
  79921. lm.m[12] += vec.x;
  79922. lm.m[13] += vec.y;
  79923. lm.m[14] += vec.z;
  79924. }
  79925. else {
  79926. var wm = null;
  79927. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79928. if (mesh) {
  79929. wm = mesh.getWorldMatrix();
  79930. }
  79931. this._skeleton.computeAbsoluteTransforms();
  79932. var tmat = Bone._tmpMats[0];
  79933. var tvec = Bone._tmpVecs[0];
  79934. if (this._parent) {
  79935. if (mesh && wm) {
  79936. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79937. tmat.multiplyToRef(wm, tmat);
  79938. }
  79939. else {
  79940. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79941. }
  79942. }
  79943. tmat.m[12] = 0;
  79944. tmat.m[13] = 0;
  79945. tmat.m[14] = 0;
  79946. tmat.invert();
  79947. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79948. lm.m[12] += tvec.x;
  79949. lm.m[13] += tvec.y;
  79950. lm.m[14] += tvec.z;
  79951. }
  79952. this._markAsDirtyAndDecompose();
  79953. };
  79954. /**
  79955. * Set the postion of the bone in local or world space
  79956. * @param position The position to set the bone
  79957. * @param space The space that the position is in
  79958. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79959. */
  79960. Bone.prototype.setPosition = function (position, space, mesh) {
  79961. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79962. var lm = this.getLocalMatrix();
  79963. if (space == BABYLON.Space.LOCAL) {
  79964. lm.m[12] = position.x;
  79965. lm.m[13] = position.y;
  79966. lm.m[14] = position.z;
  79967. }
  79968. else {
  79969. var wm = null;
  79970. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79971. if (mesh) {
  79972. wm = mesh.getWorldMatrix();
  79973. }
  79974. this._skeleton.computeAbsoluteTransforms();
  79975. var tmat = Bone._tmpMats[0];
  79976. var vec = Bone._tmpVecs[0];
  79977. if (this._parent) {
  79978. if (mesh && wm) {
  79979. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79980. tmat.multiplyToRef(wm, tmat);
  79981. }
  79982. else {
  79983. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79984. }
  79985. }
  79986. tmat.invert();
  79987. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79988. lm.m[12] = vec.x;
  79989. lm.m[13] = vec.y;
  79990. lm.m[14] = vec.z;
  79991. }
  79992. this._markAsDirtyAndDecompose();
  79993. };
  79994. /**
  79995. * Set the absolute position of the bone (world space)
  79996. * @param position The position to set the bone
  79997. * @param mesh The mesh that this bone is attached to
  79998. */
  79999. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  80000. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  80001. };
  80002. /**
  80003. * Scale the bone on the x, y and z axes (in local space)
  80004. * @param x The amount to scale the bone on the x axis
  80005. * @param y The amount to scale the bone on the y axis
  80006. * @param z The amount to scale the bone on the z axis
  80007. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  80008. */
  80009. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  80010. if (scaleChildren === void 0) { scaleChildren = false; }
  80011. var locMat = this.getLocalMatrix();
  80012. // Apply new scaling on top of current local matrix
  80013. var scaleMat = Bone._tmpMats[0];
  80014. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  80015. scaleMat.multiplyToRef(locMat, locMat);
  80016. // Invert scaling matrix and apply the inverse to all children
  80017. scaleMat.invert();
  80018. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  80019. var child = _a[_i];
  80020. var cm = child.getLocalMatrix();
  80021. cm.multiplyToRef(scaleMat, cm);
  80022. cm.m[12] *= x;
  80023. cm.m[13] *= y;
  80024. cm.m[14] *= z;
  80025. child._markAsDirtyAndDecompose();
  80026. }
  80027. this._markAsDirtyAndDecompose();
  80028. if (scaleChildren) {
  80029. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  80030. var child = _c[_b];
  80031. child.scale(x, y, z, scaleChildren);
  80032. }
  80033. }
  80034. };
  80035. /**
  80036. * Set the bone scaling in local space
  80037. * @param scale defines the scaling vector
  80038. */
  80039. Bone.prototype.setScale = function (scale) {
  80040. this._decompose();
  80041. this._localScaling.copyFrom(scale);
  80042. this._markAsDirtyAndCompose();
  80043. };
  80044. /**
  80045. * Gets the current scaling in local space
  80046. * @returns the current scaling vector
  80047. */
  80048. Bone.prototype.getScale = function () {
  80049. this._decompose();
  80050. return this._localScaling;
  80051. };
  80052. /**
  80053. * Gets the current scaling in local space and stores it in a target vector
  80054. * @param result defines the target vector
  80055. */
  80056. Bone.prototype.getScaleToRef = function (result) {
  80057. this._decompose();
  80058. result.copyFrom(this._localScaling);
  80059. };
  80060. /**
  80061. * Set the yaw, pitch, and roll of the bone in local or world space
  80062. * @param yaw The rotation of the bone on the y axis
  80063. * @param pitch The rotation of the bone on the x axis
  80064. * @param roll The rotation of the bone on the z axis
  80065. * @param space The space that the axes of rotation are in
  80066. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80067. */
  80068. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  80069. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80070. if (space === BABYLON.Space.LOCAL) {
  80071. var quat = Bone._tmpQuat;
  80072. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  80073. this.setRotationQuaternion(quat, space, mesh);
  80074. return;
  80075. }
  80076. var rotMatInv = Bone._tmpMats[0];
  80077. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80078. return;
  80079. }
  80080. var rotMat = Bone._tmpMats[1];
  80081. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  80082. rotMatInv.multiplyToRef(rotMat, rotMat);
  80083. this._rotateWithMatrix(rotMat, space, mesh);
  80084. };
  80085. /**
  80086. * Add a rotation to the bone on an axis in local or world space
  80087. * @param axis The axis to rotate the bone on
  80088. * @param amount The amount to rotate the bone
  80089. * @param space The space that the axis is in
  80090. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80091. */
  80092. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  80093. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80094. var rmat = Bone._tmpMats[0];
  80095. rmat.m[12] = 0;
  80096. rmat.m[13] = 0;
  80097. rmat.m[14] = 0;
  80098. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  80099. this._rotateWithMatrix(rmat, space, mesh);
  80100. };
  80101. /**
  80102. * Set the rotation of the bone to a particular axis angle in local or world space
  80103. * @param axis The axis to rotate the bone on
  80104. * @param angle The angle that the bone should be rotated to
  80105. * @param space The space that the axis is in
  80106. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80107. */
  80108. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  80109. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80110. if (space === BABYLON.Space.LOCAL) {
  80111. var quat = Bone._tmpQuat;
  80112. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  80113. this.setRotationQuaternion(quat, space, mesh);
  80114. return;
  80115. }
  80116. var rotMatInv = Bone._tmpMats[0];
  80117. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80118. return;
  80119. }
  80120. var rotMat = Bone._tmpMats[1];
  80121. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  80122. rotMatInv.multiplyToRef(rotMat, rotMat);
  80123. this._rotateWithMatrix(rotMat, space, mesh);
  80124. };
  80125. /**
  80126. * Set the euler rotation of the bone in local of world space
  80127. * @param rotation The euler rotation that the bone should be set to
  80128. * @param space The space that the rotation is in
  80129. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80130. */
  80131. Bone.prototype.setRotation = function (rotation, space, mesh) {
  80132. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80133. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  80134. };
  80135. /**
  80136. * Set the quaternion rotation of the bone in local of world space
  80137. * @param quat The quaternion rotation that the bone should be set to
  80138. * @param space The space that the rotation is in
  80139. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80140. */
  80141. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  80142. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80143. if (space === BABYLON.Space.LOCAL) {
  80144. this._decompose();
  80145. this._localRotation.copyFrom(quat);
  80146. this._markAsDirtyAndCompose();
  80147. return;
  80148. }
  80149. var rotMatInv = Bone._tmpMats[0];
  80150. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80151. return;
  80152. }
  80153. var rotMat = Bone._tmpMats[1];
  80154. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  80155. rotMatInv.multiplyToRef(rotMat, rotMat);
  80156. this._rotateWithMatrix(rotMat, space, mesh);
  80157. };
  80158. /**
  80159. * Set the rotation matrix of the bone in local of world space
  80160. * @param rotMat The rotation matrix that the bone should be set to
  80161. * @param space The space that the rotation is in
  80162. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80163. */
  80164. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  80165. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80166. if (space === BABYLON.Space.LOCAL) {
  80167. var quat = Bone._tmpQuat;
  80168. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  80169. this.setRotationQuaternion(quat, space, mesh);
  80170. return;
  80171. }
  80172. var rotMatInv = Bone._tmpMats[0];
  80173. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80174. return;
  80175. }
  80176. var rotMat2 = Bone._tmpMats[1];
  80177. rotMat2.copyFrom(rotMat);
  80178. rotMatInv.multiplyToRef(rotMat, rotMat2);
  80179. this._rotateWithMatrix(rotMat2, space, mesh);
  80180. };
  80181. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  80182. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80183. var lmat = this.getLocalMatrix();
  80184. var lx = lmat.m[12];
  80185. var ly = lmat.m[13];
  80186. var lz = lmat.m[14];
  80187. var parent = this.getParent();
  80188. var parentScale = Bone._tmpMats[3];
  80189. var parentScaleInv = Bone._tmpMats[4];
  80190. if (parent && space == BABYLON.Space.WORLD) {
  80191. if (mesh) {
  80192. parentScale.copyFrom(mesh.getWorldMatrix());
  80193. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  80194. }
  80195. else {
  80196. parentScale.copyFrom(parent.getAbsoluteTransform());
  80197. }
  80198. parentScaleInv.copyFrom(parentScale);
  80199. parentScaleInv.invert();
  80200. lmat.multiplyToRef(parentScale, lmat);
  80201. lmat.multiplyToRef(rmat, lmat);
  80202. lmat.multiplyToRef(parentScaleInv, lmat);
  80203. }
  80204. else {
  80205. if (space == BABYLON.Space.WORLD && mesh) {
  80206. parentScale.copyFrom(mesh.getWorldMatrix());
  80207. parentScaleInv.copyFrom(parentScale);
  80208. parentScaleInv.invert();
  80209. lmat.multiplyToRef(parentScale, lmat);
  80210. lmat.multiplyToRef(rmat, lmat);
  80211. lmat.multiplyToRef(parentScaleInv, lmat);
  80212. }
  80213. else {
  80214. lmat.multiplyToRef(rmat, lmat);
  80215. }
  80216. }
  80217. lmat.m[12] = lx;
  80218. lmat.m[13] = ly;
  80219. lmat.m[14] = lz;
  80220. this.computeAbsoluteTransforms();
  80221. this._markAsDirtyAndDecompose();
  80222. };
  80223. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  80224. var scaleMatrix = Bone._tmpMats[2];
  80225. rotMatInv.copyFrom(this.getAbsoluteTransform());
  80226. if (mesh) {
  80227. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  80228. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  80229. }
  80230. rotMatInv.invert();
  80231. if (isNaN(rotMatInv.m[0])) {
  80232. // Matrix failed to invert.
  80233. // This can happen if scale is zero for example.
  80234. return false;
  80235. }
  80236. scaleMatrix.m[0] *= this._scalingDeterminant;
  80237. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  80238. return true;
  80239. };
  80240. /**
  80241. * Get the position of the bone in local or world space
  80242. * @param space The space that the returned position is in
  80243. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80244. * @returns The position of the bone
  80245. */
  80246. Bone.prototype.getPosition = function (space, mesh) {
  80247. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80248. if (mesh === void 0) { mesh = null; }
  80249. var pos = BABYLON.Vector3.Zero();
  80250. this.getPositionToRef(space, mesh, pos);
  80251. return pos;
  80252. };
  80253. /**
  80254. * Copy the position of the bone to a vector3 in local or world space
  80255. * @param space The space that the returned position is in
  80256. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80257. * @param result The vector3 to copy the position to
  80258. */
  80259. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  80260. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80261. if (space == BABYLON.Space.LOCAL) {
  80262. var lm = this.getLocalMatrix();
  80263. result.x = lm.m[12];
  80264. result.y = lm.m[13];
  80265. result.z = lm.m[14];
  80266. }
  80267. else {
  80268. var wm = null;
  80269. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80270. if (mesh) {
  80271. wm = mesh.getWorldMatrix();
  80272. }
  80273. this._skeleton.computeAbsoluteTransforms();
  80274. var tmat = Bone._tmpMats[0];
  80275. if (mesh && wm) {
  80276. tmat.copyFrom(this.getAbsoluteTransform());
  80277. tmat.multiplyToRef(wm, tmat);
  80278. }
  80279. else {
  80280. tmat = this.getAbsoluteTransform();
  80281. }
  80282. result.x = tmat.m[12];
  80283. result.y = tmat.m[13];
  80284. result.z = tmat.m[14];
  80285. }
  80286. };
  80287. /**
  80288. * Get the absolute position of the bone (world space)
  80289. * @param mesh The mesh that this bone is attached to
  80290. * @returns The absolute position of the bone
  80291. */
  80292. Bone.prototype.getAbsolutePosition = function (mesh) {
  80293. if (mesh === void 0) { mesh = null; }
  80294. var pos = BABYLON.Vector3.Zero();
  80295. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  80296. return pos;
  80297. };
  80298. /**
  80299. * Copy the absolute position of the bone (world space) to the result param
  80300. * @param mesh The mesh that this bone is attached to
  80301. * @param result The vector3 to copy the absolute position to
  80302. */
  80303. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  80304. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  80305. };
  80306. /**
  80307. * Compute the absolute transforms of this bone and its children
  80308. */
  80309. Bone.prototype.computeAbsoluteTransforms = function () {
  80310. this._compose();
  80311. if (this._parent) {
  80312. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80313. }
  80314. else {
  80315. this._absoluteTransform.copyFrom(this._localMatrix);
  80316. var poseMatrix = this._skeleton.getPoseMatrix();
  80317. if (poseMatrix) {
  80318. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80319. }
  80320. }
  80321. var children = this.children;
  80322. var len = children.length;
  80323. for (var i = 0; i < len; i++) {
  80324. children[i].computeAbsoluteTransforms();
  80325. }
  80326. };
  80327. /**
  80328. * Get the world direction from an axis that is in the local space of the bone
  80329. * @param localAxis The local direction that is used to compute the world direction
  80330. * @param mesh The mesh that this bone is attached to
  80331. * @returns The world direction
  80332. */
  80333. Bone.prototype.getDirection = function (localAxis, mesh) {
  80334. if (mesh === void 0) { mesh = null; }
  80335. var result = BABYLON.Vector3.Zero();
  80336. this.getDirectionToRef(localAxis, mesh, result);
  80337. return result;
  80338. };
  80339. /**
  80340. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80341. * @param localAxis The local direction that is used to compute the world direction
  80342. * @param mesh The mesh that this bone is attached to
  80343. * @param result The vector3 that the world direction will be copied to
  80344. */
  80345. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80346. if (mesh === void 0) { mesh = null; }
  80347. var wm = null;
  80348. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80349. if (mesh) {
  80350. wm = mesh.getWorldMatrix();
  80351. }
  80352. this._skeleton.computeAbsoluteTransforms();
  80353. var mat = Bone._tmpMats[0];
  80354. mat.copyFrom(this.getAbsoluteTransform());
  80355. if (mesh && wm) {
  80356. mat.multiplyToRef(wm, mat);
  80357. }
  80358. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80359. result.normalize();
  80360. };
  80361. /**
  80362. * Get the euler rotation of the bone in local or world space
  80363. * @param space The space that the rotation should be in
  80364. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80365. * @returns The euler rotation
  80366. */
  80367. Bone.prototype.getRotation = function (space, mesh) {
  80368. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80369. if (mesh === void 0) { mesh = null; }
  80370. var result = BABYLON.Vector3.Zero();
  80371. this.getRotationToRef(space, mesh, result);
  80372. return result;
  80373. };
  80374. /**
  80375. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80376. * @param space The space that the rotation should be in
  80377. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80378. * @param result The vector3 that the rotation should be copied to
  80379. */
  80380. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80381. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80382. if (mesh === void 0) { mesh = null; }
  80383. var quat = Bone._tmpQuat;
  80384. this.getRotationQuaternionToRef(space, mesh, quat);
  80385. quat.toEulerAnglesToRef(result);
  80386. };
  80387. /**
  80388. * Get the quaternion rotation of the bone in either local or world space
  80389. * @param space The space that the rotation should be in
  80390. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80391. * @returns The quaternion rotation
  80392. */
  80393. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80394. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80395. if (mesh === void 0) { mesh = null; }
  80396. var result = BABYLON.Quaternion.Identity();
  80397. this.getRotationQuaternionToRef(space, mesh, result);
  80398. return result;
  80399. };
  80400. /**
  80401. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80402. * @param space The space that the rotation should be in
  80403. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80404. * @param result The quaternion that the rotation should be copied to
  80405. */
  80406. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80407. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80408. if (mesh === void 0) { mesh = null; }
  80409. if (space == BABYLON.Space.LOCAL) {
  80410. this._decompose();
  80411. result.copyFrom(this._localRotation);
  80412. }
  80413. else {
  80414. var mat = Bone._tmpMats[0];
  80415. var amat = this.getAbsoluteTransform();
  80416. if (mesh) {
  80417. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80418. }
  80419. else {
  80420. mat.copyFrom(amat);
  80421. }
  80422. mat.m[0] *= this._scalingDeterminant;
  80423. mat.m[1] *= this._scalingDeterminant;
  80424. mat.m[2] *= this._scalingDeterminant;
  80425. mat.decompose(undefined, result, undefined);
  80426. }
  80427. };
  80428. /**
  80429. * Get the rotation matrix of the bone in local or world space
  80430. * @param space The space that the rotation should be in
  80431. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80432. * @returns The rotation matrix
  80433. */
  80434. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80435. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80436. var result = BABYLON.Matrix.Identity();
  80437. this.getRotationMatrixToRef(space, mesh, result);
  80438. return result;
  80439. };
  80440. /**
  80441. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80442. * @param space The space that the rotation should be in
  80443. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80444. * @param result The quaternion that the rotation should be copied to
  80445. */
  80446. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80447. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80448. if (space == BABYLON.Space.LOCAL) {
  80449. this.getLocalMatrix().getRotationMatrixToRef(result);
  80450. }
  80451. else {
  80452. var mat = Bone._tmpMats[0];
  80453. var amat = this.getAbsoluteTransform();
  80454. if (mesh) {
  80455. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80456. }
  80457. else {
  80458. mat.copyFrom(amat);
  80459. }
  80460. mat.m[0] *= this._scalingDeterminant;
  80461. mat.m[1] *= this._scalingDeterminant;
  80462. mat.m[2] *= this._scalingDeterminant;
  80463. mat.getRotationMatrixToRef(result);
  80464. }
  80465. };
  80466. /**
  80467. * Get the world position of a point that is in the local space of the bone
  80468. * @param position The local position
  80469. * @param mesh The mesh that this bone is attached to
  80470. * @returns The world position
  80471. */
  80472. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80473. if (mesh === void 0) { mesh = null; }
  80474. var result = BABYLON.Vector3.Zero();
  80475. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80476. return result;
  80477. };
  80478. /**
  80479. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80480. * @param position The local position
  80481. * @param mesh The mesh that this bone is attached to
  80482. * @param result The vector3 that the world position should be copied to
  80483. */
  80484. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80485. if (mesh === void 0) { mesh = null; }
  80486. var wm = null;
  80487. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80488. if (mesh) {
  80489. wm = mesh.getWorldMatrix();
  80490. }
  80491. this._skeleton.computeAbsoluteTransforms();
  80492. var tmat = Bone._tmpMats[0];
  80493. if (mesh && wm) {
  80494. tmat.copyFrom(this.getAbsoluteTransform());
  80495. tmat.multiplyToRef(wm, tmat);
  80496. }
  80497. else {
  80498. tmat = this.getAbsoluteTransform();
  80499. }
  80500. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80501. };
  80502. /**
  80503. * Get the local position of a point that is in world space
  80504. * @param position The world position
  80505. * @param mesh The mesh that this bone is attached to
  80506. * @returns The local position
  80507. */
  80508. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80509. if (mesh === void 0) { mesh = null; }
  80510. var result = BABYLON.Vector3.Zero();
  80511. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80512. return result;
  80513. };
  80514. /**
  80515. * Get the local position of a point that is in world space and copy it to the result param
  80516. * @param position The world position
  80517. * @param mesh The mesh that this bone is attached to
  80518. * @param result The vector3 that the local position should be copied to
  80519. */
  80520. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80521. if (mesh === void 0) { mesh = null; }
  80522. var wm = null;
  80523. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80524. if (mesh) {
  80525. wm = mesh.getWorldMatrix();
  80526. }
  80527. this._skeleton.computeAbsoluteTransforms();
  80528. var tmat = Bone._tmpMats[0];
  80529. tmat.copyFrom(this.getAbsoluteTransform());
  80530. if (mesh && wm) {
  80531. tmat.multiplyToRef(wm, tmat);
  80532. }
  80533. tmat.invert();
  80534. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80535. };
  80536. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80537. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80538. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80539. return Bone;
  80540. }(BABYLON.Node));
  80541. BABYLON.Bone = Bone;
  80542. })(BABYLON || (BABYLON = {}));
  80543. //# sourceMappingURL=babylon.bone.js.map
  80544. var BABYLON;
  80545. (function (BABYLON) {
  80546. /**
  80547. * Class used to apply inverse kinematics to bones
  80548. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80549. */
  80550. var BoneIKController = /** @class */ (function () {
  80551. /**
  80552. * Creates a new BoneIKController
  80553. * @param mesh defines the mesh to control
  80554. * @param bone defines the bone to control
  80555. * @param options defines options to set up the controller
  80556. */
  80557. function BoneIKController(mesh, bone, options) {
  80558. /**
  80559. * Gets or sets the target position
  80560. */
  80561. this.targetPosition = BABYLON.Vector3.Zero();
  80562. /**
  80563. * Gets or sets the pole target position
  80564. */
  80565. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80566. /**
  80567. * Gets or sets the pole target local offset
  80568. */
  80569. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80570. /**
  80571. * Gets or sets the pole angle
  80572. */
  80573. this.poleAngle = 0;
  80574. /**
  80575. * 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)
  80576. */
  80577. this.slerpAmount = 1;
  80578. this._bone1Quat = BABYLON.Quaternion.Identity();
  80579. this._bone1Mat = BABYLON.Matrix.Identity();
  80580. this._bone2Ang = Math.PI;
  80581. this._maxAngle = Math.PI;
  80582. this._rightHandedSystem = false;
  80583. this._bendAxis = BABYLON.Vector3.Right();
  80584. this._slerping = false;
  80585. this._adjustRoll = 0;
  80586. this._bone2 = bone;
  80587. this._bone1 = bone.getParent();
  80588. if (!this._bone1) {
  80589. return;
  80590. }
  80591. this.mesh = mesh;
  80592. var bonePos = bone.getPosition();
  80593. if (bone.getAbsoluteTransform().determinant() > 0) {
  80594. this._rightHandedSystem = true;
  80595. this._bendAxis.x = 0;
  80596. this._bendAxis.y = 0;
  80597. this._bendAxis.z = -1;
  80598. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80599. this._adjustRoll = Math.PI * .5;
  80600. this._bendAxis.z = 1;
  80601. }
  80602. }
  80603. if (this._bone1.length) {
  80604. var boneScale1 = this._bone1.getScale();
  80605. var boneScale2 = this._bone2.getScale();
  80606. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80607. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80608. }
  80609. else if (this._bone1.children[0]) {
  80610. mesh.computeWorldMatrix(true);
  80611. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80612. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80613. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80614. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80615. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80616. }
  80617. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80618. this.maxAngle = Math.PI;
  80619. if (options) {
  80620. if (options.targetMesh) {
  80621. this.targetMesh = options.targetMesh;
  80622. this.targetMesh.computeWorldMatrix(true);
  80623. }
  80624. if (options.poleTargetMesh) {
  80625. this.poleTargetMesh = options.poleTargetMesh;
  80626. this.poleTargetMesh.computeWorldMatrix(true);
  80627. }
  80628. else if (options.poleTargetBone) {
  80629. this.poleTargetBone = options.poleTargetBone;
  80630. }
  80631. else if (this._bone1.getParent()) {
  80632. this.poleTargetBone = this._bone1.getParent();
  80633. }
  80634. if (options.poleTargetLocalOffset) {
  80635. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80636. }
  80637. if (options.poleAngle) {
  80638. this.poleAngle = options.poleAngle;
  80639. }
  80640. if (options.bendAxis) {
  80641. this._bendAxis.copyFrom(options.bendAxis);
  80642. }
  80643. if (options.maxAngle) {
  80644. this.maxAngle = options.maxAngle;
  80645. }
  80646. if (options.slerpAmount) {
  80647. this.slerpAmount = options.slerpAmount;
  80648. }
  80649. }
  80650. }
  80651. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80652. /**
  80653. * Gets or sets maximum allowed angle
  80654. */
  80655. get: function () {
  80656. return this._maxAngle;
  80657. },
  80658. set: function (value) {
  80659. this._setMaxAngle(value);
  80660. },
  80661. enumerable: true,
  80662. configurable: true
  80663. });
  80664. BoneIKController.prototype._setMaxAngle = function (ang) {
  80665. if (ang < 0) {
  80666. ang = 0;
  80667. }
  80668. if (ang > Math.PI || ang == undefined) {
  80669. ang = Math.PI;
  80670. }
  80671. this._maxAngle = ang;
  80672. var a = this._bone1Length;
  80673. var b = this._bone2Length;
  80674. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80675. };
  80676. /**
  80677. * Force the controller to update the bones
  80678. */
  80679. BoneIKController.prototype.update = function () {
  80680. var bone1 = this._bone1;
  80681. if (!bone1) {
  80682. return;
  80683. }
  80684. var target = this.targetPosition;
  80685. var poleTarget = this.poleTargetPosition;
  80686. var mat1 = BoneIKController._tmpMats[0];
  80687. var mat2 = BoneIKController._tmpMats[1];
  80688. if (this.targetMesh) {
  80689. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80690. }
  80691. if (this.poleTargetBone) {
  80692. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80693. }
  80694. else if (this.poleTargetMesh) {
  80695. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80696. }
  80697. var bonePos = BoneIKController._tmpVecs[0];
  80698. var zaxis = BoneIKController._tmpVecs[1];
  80699. var xaxis = BoneIKController._tmpVecs[2];
  80700. var yaxis = BoneIKController._tmpVecs[3];
  80701. var upAxis = BoneIKController._tmpVecs[4];
  80702. var _tmpQuat = BoneIKController._tmpQuat;
  80703. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80704. poleTarget.subtractToRef(bonePos, upAxis);
  80705. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80706. upAxis.y = 1;
  80707. }
  80708. else {
  80709. upAxis.normalize();
  80710. }
  80711. target.subtractToRef(bonePos, yaxis);
  80712. yaxis.normalize();
  80713. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80714. zaxis.normalize();
  80715. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80716. xaxis.normalize();
  80717. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80718. var a = this._bone1Length;
  80719. var b = this._bone2Length;
  80720. var c = BABYLON.Vector3.Distance(bonePos, target);
  80721. if (this._maxReach > 0) {
  80722. c = Math.min(this._maxReach, c);
  80723. }
  80724. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80725. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80726. if (acosa > 1) {
  80727. acosa = 1;
  80728. }
  80729. if (acosb > 1) {
  80730. acosb = 1;
  80731. }
  80732. if (acosa < -1) {
  80733. acosa = -1;
  80734. }
  80735. if (acosb < -1) {
  80736. acosb = -1;
  80737. }
  80738. var angA = Math.acos(acosa);
  80739. var angB = Math.acos(acosb);
  80740. var angC = -angA - angB;
  80741. if (this._rightHandedSystem) {
  80742. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80743. mat2.multiplyToRef(mat1, mat1);
  80744. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80745. mat2.multiplyToRef(mat1, mat1);
  80746. }
  80747. else {
  80748. var _tmpVec = BoneIKController._tmpVecs[5];
  80749. _tmpVec.copyFrom(this._bendAxis);
  80750. _tmpVec.x *= -1;
  80751. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80752. mat2.multiplyToRef(mat1, mat1);
  80753. }
  80754. if (this.poleAngle) {
  80755. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80756. mat1.multiplyToRef(mat2, mat1);
  80757. }
  80758. if (this._bone1) {
  80759. if (this.slerpAmount < 1) {
  80760. if (!this._slerping) {
  80761. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80762. }
  80763. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80764. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80765. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80766. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80767. this._slerping = true;
  80768. }
  80769. else {
  80770. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80771. this._bone1Mat.copyFrom(mat1);
  80772. this._slerping = false;
  80773. }
  80774. }
  80775. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80776. this._bone2Ang = angC;
  80777. };
  80778. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80779. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80780. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80781. return BoneIKController;
  80782. }());
  80783. BABYLON.BoneIKController = BoneIKController;
  80784. })(BABYLON || (BABYLON = {}));
  80785. //# sourceMappingURL=babylon.boneIKController.js.map
  80786. var BABYLON;
  80787. (function (BABYLON) {
  80788. /**
  80789. * Class used to make a bone look toward a point in space
  80790. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80791. */
  80792. var BoneLookController = /** @class */ (function () {
  80793. /**
  80794. * Create a BoneLookController
  80795. * @param mesh the mesh that the bone belongs to
  80796. * @param bone the bone that will be looking to the target
  80797. * @param target the target Vector3 to look at
  80798. * @param settings optional settings:
  80799. * * maxYaw: the maximum angle the bone will yaw to
  80800. * * minYaw: the minimum angle the bone will yaw to
  80801. * * maxPitch: the maximum angle the bone will pitch to
  80802. * * minPitch: the minimum angle the bone will yaw to
  80803. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80804. * * upAxis: the up axis of the coordinate system
  80805. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80806. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80807. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80808. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80809. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80810. * * adjustRoll: used to make an adjustment to the roll of the bone
  80811. **/
  80812. function BoneLookController(mesh, bone, target, options) {
  80813. /**
  80814. * The up axis of the coordinate system that is used when the bone is rotated
  80815. */
  80816. this.upAxis = BABYLON.Vector3.Up();
  80817. /**
  80818. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80819. */
  80820. this.upAxisSpace = BABYLON.Space.LOCAL;
  80821. /**
  80822. * Used to make an adjustment to the yaw of the bone
  80823. */
  80824. this.adjustYaw = 0;
  80825. /**
  80826. * Used to make an adjustment to the pitch of the bone
  80827. */
  80828. this.adjustPitch = 0;
  80829. /**
  80830. * Used to make an adjustment to the roll of the bone
  80831. */
  80832. this.adjustRoll = 0;
  80833. /**
  80834. * 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)
  80835. */
  80836. this.slerpAmount = 1;
  80837. this._boneQuat = BABYLON.Quaternion.Identity();
  80838. this._slerping = false;
  80839. this._firstFrameSkipped = false;
  80840. this._fowardAxis = BABYLON.Vector3.Forward();
  80841. this.mesh = mesh;
  80842. this.bone = bone;
  80843. this.target = target;
  80844. if (options) {
  80845. if (options.adjustYaw) {
  80846. this.adjustYaw = options.adjustYaw;
  80847. }
  80848. if (options.adjustPitch) {
  80849. this.adjustPitch = options.adjustPitch;
  80850. }
  80851. if (options.adjustRoll) {
  80852. this.adjustRoll = options.adjustRoll;
  80853. }
  80854. if (options.maxYaw != null) {
  80855. this.maxYaw = options.maxYaw;
  80856. }
  80857. else {
  80858. this.maxYaw = Math.PI;
  80859. }
  80860. if (options.minYaw != null) {
  80861. this.minYaw = options.minYaw;
  80862. }
  80863. else {
  80864. this.minYaw = -Math.PI;
  80865. }
  80866. if (options.maxPitch != null) {
  80867. this.maxPitch = options.maxPitch;
  80868. }
  80869. else {
  80870. this.maxPitch = Math.PI;
  80871. }
  80872. if (options.minPitch != null) {
  80873. this.minPitch = options.minPitch;
  80874. }
  80875. else {
  80876. this.minPitch = -Math.PI;
  80877. }
  80878. if (options.slerpAmount != null) {
  80879. this.slerpAmount = options.slerpAmount;
  80880. }
  80881. if (options.upAxis != null) {
  80882. this.upAxis = options.upAxis;
  80883. }
  80884. if (options.upAxisSpace != null) {
  80885. this.upAxisSpace = options.upAxisSpace;
  80886. }
  80887. if (options.yawAxis != null || options.pitchAxis != null) {
  80888. var newYawAxis = BABYLON.Axis.Y;
  80889. var newPitchAxis = BABYLON.Axis.X;
  80890. if (options.yawAxis != null) {
  80891. newYawAxis = options.yawAxis.clone();
  80892. newYawAxis.normalize();
  80893. }
  80894. if (options.pitchAxis != null) {
  80895. newPitchAxis = options.pitchAxis.clone();
  80896. newPitchAxis.normalize();
  80897. }
  80898. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80899. this._transformYawPitch = BABYLON.Matrix.Identity();
  80900. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80901. this._transformYawPitchInv = this._transformYawPitch.clone();
  80902. this._transformYawPitch.invert();
  80903. }
  80904. }
  80905. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80906. this.upAxisSpace = BABYLON.Space.LOCAL;
  80907. }
  80908. }
  80909. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80910. /**
  80911. * Gets or sets the minimum yaw angle that the bone can look to
  80912. */
  80913. get: function () {
  80914. return this._minYaw;
  80915. },
  80916. set: function (value) {
  80917. this._minYaw = value;
  80918. this._minYawSin = Math.sin(value);
  80919. this._minYawCos = Math.cos(value);
  80920. if (this._maxYaw != null) {
  80921. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80922. this._yawRange = this._maxYaw - this._minYaw;
  80923. }
  80924. },
  80925. enumerable: true,
  80926. configurable: true
  80927. });
  80928. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80929. /**
  80930. * Gets or sets the maximum yaw angle that the bone can look to
  80931. */
  80932. get: function () {
  80933. return this._maxYaw;
  80934. },
  80935. set: function (value) {
  80936. this._maxYaw = value;
  80937. this._maxYawSin = Math.sin(value);
  80938. this._maxYawCos = Math.cos(value);
  80939. if (this._minYaw != null) {
  80940. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80941. this._yawRange = this._maxYaw - this._minYaw;
  80942. }
  80943. },
  80944. enumerable: true,
  80945. configurable: true
  80946. });
  80947. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80948. /**
  80949. * Gets or sets the minimum pitch angle that the bone can look to
  80950. */
  80951. get: function () {
  80952. return this._minPitch;
  80953. },
  80954. set: function (value) {
  80955. this._minPitch = value;
  80956. this._minPitchTan = Math.tan(value);
  80957. },
  80958. enumerable: true,
  80959. configurable: true
  80960. });
  80961. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80962. /**
  80963. * Gets or sets the maximum pitch angle that the bone can look to
  80964. */
  80965. get: function () {
  80966. return this._maxPitch;
  80967. },
  80968. set: function (value) {
  80969. this._maxPitch = value;
  80970. this._maxPitchTan = Math.tan(value);
  80971. },
  80972. enumerable: true,
  80973. configurable: true
  80974. });
  80975. /**
  80976. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80977. */
  80978. BoneLookController.prototype.update = function () {
  80979. //skip the first frame when slerping so that the mesh rotation is correct
  80980. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80981. this._firstFrameSkipped = true;
  80982. return;
  80983. }
  80984. var bone = this.bone;
  80985. var bonePos = BoneLookController._tmpVecs[0];
  80986. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80987. var target = this.target;
  80988. var _tmpMat1 = BoneLookController._tmpMats[0];
  80989. var _tmpMat2 = BoneLookController._tmpMats[1];
  80990. var mesh = this.mesh;
  80991. var parentBone = bone.getParent();
  80992. var upAxis = BoneLookController._tmpVecs[1];
  80993. upAxis.copyFrom(this.upAxis);
  80994. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80995. if (this._transformYawPitch) {
  80996. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80997. }
  80998. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80999. }
  81000. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  81001. mesh.getDirectionToRef(upAxis, upAxis);
  81002. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  81003. upAxis.normalize();
  81004. }
  81005. }
  81006. var checkYaw = false;
  81007. var checkPitch = false;
  81008. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  81009. checkYaw = true;
  81010. }
  81011. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  81012. checkPitch = true;
  81013. }
  81014. if (checkYaw || checkPitch) {
  81015. var spaceMat = BoneLookController._tmpMats[2];
  81016. var spaceMatInv = BoneLookController._tmpMats[3];
  81017. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  81018. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  81019. }
  81020. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  81021. spaceMat.copyFrom(mesh.getWorldMatrix());
  81022. }
  81023. else {
  81024. var forwardAxis = BoneLookController._tmpVecs[2];
  81025. forwardAxis.copyFrom(this._fowardAxis);
  81026. if (this._transformYawPitch) {
  81027. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  81028. }
  81029. if (parentBone) {
  81030. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  81031. }
  81032. else {
  81033. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  81034. }
  81035. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  81036. rightAxis.normalize();
  81037. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  81038. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  81039. }
  81040. spaceMat.invertToRef(spaceMatInv);
  81041. var xzlen = null;
  81042. if (checkPitch) {
  81043. var localTarget = BoneLookController._tmpVecs[3];
  81044. target.subtractToRef(bonePos, localTarget);
  81045. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81046. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81047. var pitch = Math.atan2(localTarget.y, xzlen);
  81048. var newPitch = pitch;
  81049. if (pitch > this._maxPitch) {
  81050. localTarget.y = this._maxPitchTan * xzlen;
  81051. newPitch = this._maxPitch;
  81052. }
  81053. else if (pitch < this._minPitch) {
  81054. localTarget.y = this._minPitchTan * xzlen;
  81055. newPitch = this._minPitch;
  81056. }
  81057. if (pitch != newPitch) {
  81058. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81059. localTarget.addInPlace(bonePos);
  81060. target = localTarget;
  81061. }
  81062. }
  81063. if (checkYaw) {
  81064. var localTarget = BoneLookController._tmpVecs[4];
  81065. target.subtractToRef(bonePos, localTarget);
  81066. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81067. var yaw = Math.atan2(localTarget.x, localTarget.z);
  81068. var newYaw = yaw;
  81069. if (yaw > this._maxYaw || yaw < this._minYaw) {
  81070. if (xzlen == null) {
  81071. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81072. }
  81073. if (this._yawRange > Math.PI) {
  81074. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  81075. localTarget.z = this._maxYawCos * xzlen;
  81076. localTarget.x = this._maxYawSin * xzlen;
  81077. newYaw = this._maxYaw;
  81078. }
  81079. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  81080. localTarget.z = this._minYawCos * xzlen;
  81081. localTarget.x = this._minYawSin * xzlen;
  81082. newYaw = this._minYaw;
  81083. }
  81084. }
  81085. else {
  81086. if (yaw > this._maxYaw) {
  81087. localTarget.z = this._maxYawCos * xzlen;
  81088. localTarget.x = this._maxYawSin * xzlen;
  81089. newYaw = this._maxYaw;
  81090. }
  81091. else if (yaw < this._minYaw) {
  81092. localTarget.z = this._minYawCos * xzlen;
  81093. localTarget.x = this._minYawSin * xzlen;
  81094. newYaw = this._minYaw;
  81095. }
  81096. }
  81097. }
  81098. if (this._slerping && this._yawRange > Math.PI) {
  81099. //are we going to be crossing into the min/max region?
  81100. var boneFwd = BoneLookController._tmpVecs[8];
  81101. boneFwd.copyFrom(BABYLON.Axis.Z);
  81102. if (this._transformYawPitch) {
  81103. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  81104. }
  81105. var boneRotMat = BoneLookController._tmpMats[4];
  81106. this._boneQuat.toRotationMatrix(boneRotMat);
  81107. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  81108. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  81109. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  81110. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  81111. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  81112. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  81113. if (angBtwTar > angBtwMidYaw) {
  81114. if (xzlen == null) {
  81115. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81116. }
  81117. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  81118. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  81119. if (angBtwMin < angBtwMax) {
  81120. newYaw = boneYaw + Math.PI * .75;
  81121. localTarget.z = Math.cos(newYaw) * xzlen;
  81122. localTarget.x = Math.sin(newYaw) * xzlen;
  81123. }
  81124. else {
  81125. newYaw = boneYaw - Math.PI * .75;
  81126. localTarget.z = Math.cos(newYaw) * xzlen;
  81127. localTarget.x = Math.sin(newYaw) * xzlen;
  81128. }
  81129. }
  81130. }
  81131. if (yaw != newYaw) {
  81132. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81133. localTarget.addInPlace(bonePos);
  81134. target = localTarget;
  81135. }
  81136. }
  81137. }
  81138. var zaxis = BoneLookController._tmpVecs[5];
  81139. var xaxis = BoneLookController._tmpVecs[6];
  81140. var yaxis = BoneLookController._tmpVecs[7];
  81141. var _tmpQuat = BoneLookController._tmpQuat;
  81142. target.subtractToRef(bonePos, zaxis);
  81143. zaxis.normalize();
  81144. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  81145. xaxis.normalize();
  81146. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  81147. yaxis.normalize();
  81148. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  81149. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  81150. return;
  81151. }
  81152. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  81153. return;
  81154. }
  81155. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  81156. return;
  81157. }
  81158. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  81159. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  81160. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  81161. }
  81162. if (this.slerpAmount < 1) {
  81163. if (!this._slerping) {
  81164. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  81165. }
  81166. if (this._transformYawPitch) {
  81167. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81168. }
  81169. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  81170. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  81171. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  81172. this._slerping = true;
  81173. }
  81174. else {
  81175. if (this._transformYawPitch) {
  81176. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81177. }
  81178. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  81179. this._slerping = false;
  81180. }
  81181. };
  81182. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  81183. var angDiff = ang2 - ang1;
  81184. angDiff %= Math.PI * 2;
  81185. if (angDiff > Math.PI) {
  81186. angDiff -= Math.PI * 2;
  81187. }
  81188. else if (angDiff < -Math.PI) {
  81189. angDiff += Math.PI * 2;
  81190. }
  81191. return angDiff;
  81192. };
  81193. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  81194. ang1 %= (2 * Math.PI);
  81195. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81196. ang2 %= (2 * Math.PI);
  81197. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81198. var ab = 0;
  81199. if (ang1 < ang2) {
  81200. ab = ang2 - ang1;
  81201. }
  81202. else {
  81203. ab = ang1 - ang2;
  81204. }
  81205. if (ab > Math.PI) {
  81206. ab = Math.PI * 2 - ab;
  81207. }
  81208. return ab;
  81209. };
  81210. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  81211. ang %= (2 * Math.PI);
  81212. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  81213. ang1 %= (2 * Math.PI);
  81214. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81215. ang2 %= (2 * Math.PI);
  81216. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81217. if (ang1 < ang2) {
  81218. if (ang > ang1 && ang < ang2) {
  81219. return true;
  81220. }
  81221. }
  81222. else {
  81223. if (ang > ang2 && ang < ang1) {
  81224. return true;
  81225. }
  81226. }
  81227. return false;
  81228. };
  81229. 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()];
  81230. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  81231. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81232. return BoneLookController;
  81233. }());
  81234. BABYLON.BoneLookController = BoneLookController;
  81235. })(BABYLON || (BABYLON = {}));
  81236. //# sourceMappingURL=babylon.boneLookController.js.map
  81237. var BABYLON;
  81238. (function (BABYLON) {
  81239. /**
  81240. * Class used to handle skinning animations
  81241. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81242. */
  81243. var Skeleton = /** @class */ (function () {
  81244. /**
  81245. * Creates a new skeleton
  81246. * @param name defines the skeleton name
  81247. * @param id defines the skeleton Id
  81248. * @param scene defines the hosting scene
  81249. */
  81250. function Skeleton(
  81251. /** defines the skeleton name */
  81252. name,
  81253. /** defines the skeleton Id */
  81254. id, scene) {
  81255. this.name = name;
  81256. this.id = id;
  81257. /**
  81258. * Gets the list of child bones
  81259. */
  81260. this.bones = new Array();
  81261. /**
  81262. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  81263. */
  81264. this.needInitialSkinMatrix = false;
  81265. this._isDirty = true;
  81266. this._meshesWithPoseMatrix = new Array();
  81267. this._identity = BABYLON.Matrix.Identity();
  81268. this._ranges = {};
  81269. this._lastAbsoluteTransformsUpdateId = -1;
  81270. /**
  81271. * Specifies if the skeleton should be serialized
  81272. */
  81273. this.doNotSerialize = false;
  81274. this._animationPropertiesOverride = null;
  81275. // Events
  81276. /**
  81277. * An observable triggered before computing the skeleton's matrices
  81278. */
  81279. this.onBeforeComputeObservable = new BABYLON.Observable();
  81280. this.bones = [];
  81281. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81282. scene.skeletons.push(this);
  81283. //make sure it will recalculate the matrix next time prepare is called.
  81284. this._isDirty = true;
  81285. }
  81286. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  81287. /**
  81288. * Gets or sets the animation properties override
  81289. */
  81290. get: function () {
  81291. if (!this._animationPropertiesOverride) {
  81292. return this._scene.animationPropertiesOverride;
  81293. }
  81294. return this._animationPropertiesOverride;
  81295. },
  81296. set: function (value) {
  81297. this._animationPropertiesOverride = value;
  81298. },
  81299. enumerable: true,
  81300. configurable: true
  81301. });
  81302. // Members
  81303. /**
  81304. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  81305. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  81306. * @returns a Float32Array containing matrices data
  81307. */
  81308. Skeleton.prototype.getTransformMatrices = function (mesh) {
  81309. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  81310. return mesh._bonesTransformMatrices;
  81311. }
  81312. if (!this._transformMatrices) {
  81313. this.prepare();
  81314. }
  81315. return this._transformMatrices;
  81316. };
  81317. /**
  81318. * Gets the current hosting scene
  81319. * @returns a scene object
  81320. */
  81321. Skeleton.prototype.getScene = function () {
  81322. return this._scene;
  81323. };
  81324. // Methods
  81325. /**
  81326. * Gets a string representing the current skeleton data
  81327. * @param fullDetails defines a boolean indicating if we want a verbose version
  81328. * @returns a string representing the current skeleton data
  81329. */
  81330. Skeleton.prototype.toString = function (fullDetails) {
  81331. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81332. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81333. if (fullDetails) {
  81334. ret += ", Ranges: {";
  81335. var first = true;
  81336. for (var name_1 in this._ranges) {
  81337. if (first) {
  81338. ret += ", ";
  81339. first = false;
  81340. }
  81341. ret += name_1;
  81342. }
  81343. ret += "}";
  81344. }
  81345. return ret;
  81346. };
  81347. /**
  81348. * Get bone's index searching by name
  81349. * @param name defines bone's name to search for
  81350. * @return the indice of the bone. Returns -1 if not found
  81351. */
  81352. Skeleton.prototype.getBoneIndexByName = function (name) {
  81353. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81354. if (this.bones[boneIndex].name === name) {
  81355. return boneIndex;
  81356. }
  81357. }
  81358. return -1;
  81359. };
  81360. /**
  81361. * Creater a new animation range
  81362. * @param name defines the name of the range
  81363. * @param from defines the start key
  81364. * @param to defines the end key
  81365. */
  81366. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81367. // check name not already in use
  81368. if (!this._ranges[name]) {
  81369. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81370. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81371. if (this.bones[i].animations[0]) {
  81372. this.bones[i].animations[0].createRange(name, from, to);
  81373. }
  81374. }
  81375. }
  81376. };
  81377. /**
  81378. * Delete a specific animation range
  81379. * @param name defines the name of the range
  81380. * @param deleteFrames defines if frames must be removed as well
  81381. */
  81382. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81383. if (deleteFrames === void 0) { deleteFrames = true; }
  81384. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81385. if (this.bones[i].animations[0]) {
  81386. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81387. }
  81388. }
  81389. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81390. };
  81391. /**
  81392. * Gets a specific animation range
  81393. * @param name defines the name of the range to look for
  81394. * @returns the requested animation range or null if not found
  81395. */
  81396. Skeleton.prototype.getAnimationRange = function (name) {
  81397. return this._ranges[name];
  81398. };
  81399. /**
  81400. * Gets the list of all animation ranges defined on this skeleton
  81401. * @returns an array
  81402. */
  81403. Skeleton.prototype.getAnimationRanges = function () {
  81404. var animationRanges = [];
  81405. var name;
  81406. var i = 0;
  81407. for (name in this._ranges) {
  81408. animationRanges[i] = this._ranges[name];
  81409. i++;
  81410. }
  81411. return animationRanges;
  81412. };
  81413. /**
  81414. * Copy animation range from a source skeleton.
  81415. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81416. * @param source defines the source skeleton
  81417. * @param name defines the name of the range to copy
  81418. * @param rescaleAsRequired defines if rescaling must be applied if required
  81419. * @returns true if operation was successful
  81420. */
  81421. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81422. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81423. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81424. return false;
  81425. }
  81426. var ret = true;
  81427. var frameOffset = this._getHighestAnimationFrame() + 1;
  81428. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81429. var boneDict = {};
  81430. var sourceBones = source.bones;
  81431. var nBones;
  81432. var i;
  81433. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81434. boneDict[sourceBones[i].name] = sourceBones[i];
  81435. }
  81436. if (this.bones.length !== sourceBones.length) {
  81437. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81438. ret = false;
  81439. }
  81440. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81441. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81442. var boneName = this.bones[i].name;
  81443. var sourceBone = boneDict[boneName];
  81444. if (sourceBone) {
  81445. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81446. }
  81447. else {
  81448. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81449. ret = false;
  81450. }
  81451. }
  81452. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81453. var range = source.getAnimationRange(name);
  81454. if (range) {
  81455. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81456. }
  81457. return ret;
  81458. };
  81459. /**
  81460. * Forces the skeleton to go to rest pose
  81461. */
  81462. Skeleton.prototype.returnToRest = function () {
  81463. for (var index = 0; index < this.bones.length; index++) {
  81464. this.bones[index].returnToRest();
  81465. }
  81466. };
  81467. Skeleton.prototype._getHighestAnimationFrame = function () {
  81468. var ret = 0;
  81469. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81470. if (this.bones[i].animations[0]) {
  81471. var highest = this.bones[i].animations[0].getHighestFrame();
  81472. if (ret < highest) {
  81473. ret = highest;
  81474. }
  81475. }
  81476. }
  81477. return ret;
  81478. };
  81479. /**
  81480. * Begin a specific animation range
  81481. * @param name defines the name of the range to start
  81482. * @param loop defines if looping must be turned on (false by default)
  81483. * @param speedRatio defines the speed ratio to apply (1 by default)
  81484. * @param onAnimationEnd defines a callback which will be called when animation will end
  81485. * @returns a new animatable
  81486. */
  81487. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81488. var range = this.getAnimationRange(name);
  81489. if (!range) {
  81490. return null;
  81491. }
  81492. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81493. };
  81494. /** @hidden */
  81495. Skeleton.prototype._markAsDirty = function () {
  81496. this._isDirty = true;
  81497. };
  81498. /** @hidden */
  81499. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81500. this._meshesWithPoseMatrix.push(mesh);
  81501. };
  81502. /** @hidden */
  81503. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81504. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81505. if (index > -1) {
  81506. this._meshesWithPoseMatrix.splice(index, 1);
  81507. }
  81508. };
  81509. /** @hidden */
  81510. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81511. this.onBeforeComputeObservable.notifyObservers(this);
  81512. for (var index = 0; index < this.bones.length; index++) {
  81513. var bone = this.bones[index];
  81514. var parentBone = bone.getParent();
  81515. if (parentBone) {
  81516. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81517. }
  81518. else {
  81519. if (initialSkinMatrix) {
  81520. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81521. }
  81522. else {
  81523. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81524. }
  81525. }
  81526. if (bone._index !== -1) {
  81527. var mappedIndex = bone._index === null ? index : bone._index;
  81528. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81529. }
  81530. }
  81531. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81532. };
  81533. /**
  81534. * Build all resources required to render a skeleton
  81535. */
  81536. Skeleton.prototype.prepare = function () {
  81537. if (!this._isDirty) {
  81538. return;
  81539. }
  81540. if (this.needInitialSkinMatrix) {
  81541. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81542. var mesh = this._meshesWithPoseMatrix[index];
  81543. var poseMatrix = mesh.getPoseMatrix();
  81544. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81545. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81546. }
  81547. if (this._synchronizedWithMesh !== mesh) {
  81548. this._synchronizedWithMesh = mesh;
  81549. // Prepare bones
  81550. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81551. var bone = this.bones[boneIndex];
  81552. if (!bone.getParent()) {
  81553. var matrix = bone.getBaseMatrix();
  81554. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81555. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81556. }
  81557. }
  81558. }
  81559. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81560. }
  81561. }
  81562. else {
  81563. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81564. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81565. }
  81566. this._computeTransformMatrices(this._transformMatrices, null);
  81567. }
  81568. this._isDirty = false;
  81569. this._scene._activeBones.addCount(this.bones.length, false);
  81570. };
  81571. /**
  81572. * Gets the list of animatables currently running for this skeleton
  81573. * @returns an array of animatables
  81574. */
  81575. Skeleton.prototype.getAnimatables = function () {
  81576. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81577. this._animatables = [];
  81578. for (var index = 0; index < this.bones.length; index++) {
  81579. this._animatables.push(this.bones[index]);
  81580. }
  81581. }
  81582. return this._animatables;
  81583. };
  81584. /**
  81585. * Clone the current skeleton
  81586. * @param name defines the name of the new skeleton
  81587. * @param id defines the id of the enw skeleton
  81588. * @returns the new skeleton
  81589. */
  81590. Skeleton.prototype.clone = function (name, id) {
  81591. var result = new Skeleton(name, id || name, this._scene);
  81592. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81593. for (var index = 0; index < this.bones.length; index++) {
  81594. var source = this.bones[index];
  81595. var parentBone = null;
  81596. var parent_1 = source.getParent();
  81597. if (parent_1) {
  81598. var parentIndex = this.bones.indexOf(parent_1);
  81599. parentBone = result.bones[parentIndex];
  81600. }
  81601. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81602. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81603. }
  81604. if (this._ranges) {
  81605. result._ranges = {};
  81606. for (var rangeName in this._ranges) {
  81607. var range = this._ranges[rangeName];
  81608. if (range) {
  81609. result._ranges[rangeName] = range.clone();
  81610. }
  81611. }
  81612. }
  81613. this._isDirty = true;
  81614. return result;
  81615. };
  81616. /**
  81617. * Enable animation blending for this skeleton
  81618. * @param blendingSpeed defines the blending speed to apply
  81619. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81620. */
  81621. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81622. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81623. this.bones.forEach(function (bone) {
  81624. bone.animations.forEach(function (animation) {
  81625. animation.enableBlending = true;
  81626. animation.blendingSpeed = blendingSpeed;
  81627. });
  81628. });
  81629. };
  81630. /**
  81631. * Releases all resources associated with the current skeleton
  81632. */
  81633. Skeleton.prototype.dispose = function () {
  81634. this._meshesWithPoseMatrix = [];
  81635. // Animations
  81636. this.getScene().stopAnimation(this);
  81637. // Remove from scene
  81638. this.getScene().removeSkeleton(this);
  81639. };
  81640. /**
  81641. * Serialize the skeleton in a JSON object
  81642. * @returns a JSON object
  81643. */
  81644. Skeleton.prototype.serialize = function () {
  81645. var serializationObject = {};
  81646. serializationObject.name = this.name;
  81647. serializationObject.id = this.id;
  81648. if (this.dimensionsAtRest) {
  81649. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81650. }
  81651. serializationObject.bones = [];
  81652. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81653. for (var index = 0; index < this.bones.length; index++) {
  81654. var bone = this.bones[index];
  81655. var parent_2 = bone.getParent();
  81656. var serializedBone = {
  81657. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81658. name: bone.name,
  81659. matrix: bone.getBaseMatrix().toArray(),
  81660. rest: bone.getRestPose().toArray()
  81661. };
  81662. serializationObject.bones.push(serializedBone);
  81663. if (bone.length) {
  81664. serializedBone.length = bone.length;
  81665. }
  81666. if (bone.metadata) {
  81667. serializedBone.metadata = bone.metadata;
  81668. }
  81669. if (bone.animations && bone.animations.length > 0) {
  81670. serializedBone.animation = bone.animations[0].serialize();
  81671. }
  81672. serializationObject.ranges = [];
  81673. for (var name in this._ranges) {
  81674. var source = this._ranges[name];
  81675. if (!source) {
  81676. continue;
  81677. }
  81678. var range = {};
  81679. range.name = name;
  81680. range.from = source.from;
  81681. range.to = source.to;
  81682. serializationObject.ranges.push(range);
  81683. }
  81684. }
  81685. return serializationObject;
  81686. };
  81687. /**
  81688. * Creates a new skeleton from serialized data
  81689. * @param parsedSkeleton defines the serialized data
  81690. * @param scene defines the hosting scene
  81691. * @returns a new skeleton
  81692. */
  81693. Skeleton.Parse = function (parsedSkeleton, scene) {
  81694. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81695. if (parsedSkeleton.dimensionsAtRest) {
  81696. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81697. }
  81698. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81699. var index;
  81700. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81701. var parsedBone = parsedSkeleton.bones[index];
  81702. var parentBone = null;
  81703. if (parsedBone.parentBoneIndex > -1) {
  81704. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81705. }
  81706. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81707. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81708. if (parsedBone.length) {
  81709. bone.length = parsedBone.length;
  81710. }
  81711. if (parsedBone.metadata) {
  81712. bone.metadata = parsedBone.metadata;
  81713. }
  81714. if (parsedBone.animation) {
  81715. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81716. }
  81717. }
  81718. // placed after bones, so createAnimationRange can cascade down
  81719. if (parsedSkeleton.ranges) {
  81720. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81721. var data = parsedSkeleton.ranges[index];
  81722. skeleton.createAnimationRange(data.name, data.from, data.to);
  81723. }
  81724. }
  81725. return skeleton;
  81726. };
  81727. /**
  81728. * Compute all node absolute transforms
  81729. * @param forceUpdate defines if computation must be done even if cache is up to date
  81730. */
  81731. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81732. if (forceUpdate === void 0) { forceUpdate = false; }
  81733. var renderId = this._scene.getRenderId();
  81734. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81735. this.bones[0].computeAbsoluteTransforms();
  81736. this._lastAbsoluteTransformsUpdateId = renderId;
  81737. }
  81738. };
  81739. /**
  81740. * Gets the root pose matrix
  81741. * @returns a matrix
  81742. */
  81743. Skeleton.prototype.getPoseMatrix = function () {
  81744. var poseMatrix = null;
  81745. if (this._meshesWithPoseMatrix.length > 0) {
  81746. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81747. }
  81748. return poseMatrix;
  81749. };
  81750. /**
  81751. * Sorts bones per internal index
  81752. */
  81753. Skeleton.prototype.sortBones = function () {
  81754. var bones = new Array();
  81755. var visited = new Array(this.bones.length);
  81756. for (var index = 0; index < this.bones.length; index++) {
  81757. this._sortBones(index, bones, visited);
  81758. }
  81759. this.bones = bones;
  81760. };
  81761. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81762. if (visited[index]) {
  81763. return;
  81764. }
  81765. visited[index] = true;
  81766. var bone = this.bones[index];
  81767. if (bone._index === undefined) {
  81768. bone._index = index;
  81769. }
  81770. var parentBone = bone.getParent();
  81771. if (parentBone) {
  81772. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81773. }
  81774. bones.push(bone);
  81775. };
  81776. return Skeleton;
  81777. }());
  81778. BABYLON.Skeleton = Skeleton;
  81779. })(BABYLON || (BABYLON = {}));
  81780. //# sourceMappingURL=babylon.skeleton.js.map
  81781. var BABYLON;
  81782. (function (BABYLON) {
  81783. var SphericalPolynomial = /** @class */ (function () {
  81784. function SphericalPolynomial() {
  81785. this.x = BABYLON.Vector3.Zero();
  81786. this.y = BABYLON.Vector3.Zero();
  81787. this.z = BABYLON.Vector3.Zero();
  81788. this.xx = BABYLON.Vector3.Zero();
  81789. this.yy = BABYLON.Vector3.Zero();
  81790. this.zz = BABYLON.Vector3.Zero();
  81791. this.xy = BABYLON.Vector3.Zero();
  81792. this.yz = BABYLON.Vector3.Zero();
  81793. this.zx = BABYLON.Vector3.Zero();
  81794. }
  81795. SphericalPolynomial.prototype.addAmbient = function (color) {
  81796. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81797. this.xx = this.xx.add(colorVector);
  81798. this.yy = this.yy.add(colorVector);
  81799. this.zz = this.zz.add(colorVector);
  81800. };
  81801. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  81802. var result = new SphericalPolynomial();
  81803. result.x = harmonics.L11.scale(1.02333);
  81804. result.y = harmonics.L1_1.scale(1.02333);
  81805. result.z = harmonics.L10.scale(1.02333);
  81806. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  81807. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  81808. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  81809. result.yz = harmonics.L2_1.scale(0.858086);
  81810. result.zx = harmonics.L21.scale(0.858086);
  81811. result.xy = harmonics.L2_2.scale(0.858086);
  81812. result.scale(1.0 / Math.PI);
  81813. return result;
  81814. };
  81815. SphericalPolynomial.prototype.scale = function (scale) {
  81816. this.x = this.x.scale(scale);
  81817. this.y = this.y.scale(scale);
  81818. this.z = this.z.scale(scale);
  81819. this.xx = this.xx.scale(scale);
  81820. this.yy = this.yy.scale(scale);
  81821. this.zz = this.zz.scale(scale);
  81822. this.yz = this.yz.scale(scale);
  81823. this.zx = this.zx.scale(scale);
  81824. this.xy = this.xy.scale(scale);
  81825. };
  81826. return SphericalPolynomial;
  81827. }());
  81828. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81829. var SphericalHarmonics = /** @class */ (function () {
  81830. function SphericalHarmonics() {
  81831. this.L00 = BABYLON.Vector3.Zero();
  81832. this.L1_1 = BABYLON.Vector3.Zero();
  81833. this.L10 = BABYLON.Vector3.Zero();
  81834. this.L11 = BABYLON.Vector3.Zero();
  81835. this.L2_2 = BABYLON.Vector3.Zero();
  81836. this.L2_1 = BABYLON.Vector3.Zero();
  81837. this.L20 = BABYLON.Vector3.Zero();
  81838. this.L21 = BABYLON.Vector3.Zero();
  81839. this.L22 = BABYLON.Vector3.Zero();
  81840. }
  81841. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81842. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81843. var c = colorVector.scale(deltaSolidAngle);
  81844. this.L00 = this.L00.add(c.scale(0.282095));
  81845. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  81846. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  81847. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  81848. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81849. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81850. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  81851. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81852. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81853. };
  81854. SphericalHarmonics.prototype.scale = function (scale) {
  81855. this.L00 = this.L00.scale(scale);
  81856. this.L1_1 = this.L1_1.scale(scale);
  81857. this.L10 = this.L10.scale(scale);
  81858. this.L11 = this.L11.scale(scale);
  81859. this.L2_2 = this.L2_2.scale(scale);
  81860. this.L2_1 = this.L2_1.scale(scale);
  81861. this.L20 = this.L20.scale(scale);
  81862. this.L21 = this.L21.scale(scale);
  81863. this.L22 = this.L22.scale(scale);
  81864. };
  81865. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81866. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81867. //
  81868. // E_lm = A_l * L_lm
  81869. //
  81870. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81871. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81872. // the scaling factors are given in equation 9.
  81873. // Constant (Band 0)
  81874. this.L00 = this.L00.scale(3.141593);
  81875. // Linear (Band 1)
  81876. this.L1_1 = this.L1_1.scale(2.094395);
  81877. this.L10 = this.L10.scale(2.094395);
  81878. this.L11 = this.L11.scale(2.094395);
  81879. // Quadratic (Band 2)
  81880. this.L2_2 = this.L2_2.scale(0.785398);
  81881. this.L2_1 = this.L2_1.scale(0.785398);
  81882. this.L20 = this.L20.scale(0.785398);
  81883. this.L21 = this.L21.scale(0.785398);
  81884. this.L22 = this.L22.scale(0.785398);
  81885. };
  81886. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81887. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81888. // L = (1/pi) * E * rho
  81889. //
  81890. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81891. this.scale(1.0 / Math.PI);
  81892. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81893. // (The pixel shader must apply albedo after texture fetches, etc).
  81894. };
  81895. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  81896. var result = new SphericalHarmonics();
  81897. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81898. result.L1_1 = polynomial.y.scale(0.977204);
  81899. result.L10 = polynomial.z.scale(0.977204);
  81900. result.L11 = polynomial.x.scale(0.977204);
  81901. result.L2_2 = polynomial.xy.scale(1.16538);
  81902. result.L2_1 = polynomial.yz.scale(1.16538);
  81903. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81904. result.L21 = polynomial.zx.scale(1.16538);
  81905. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81906. result.scale(Math.PI);
  81907. return result;
  81908. };
  81909. return SphericalHarmonics;
  81910. }());
  81911. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81912. })(BABYLON || (BABYLON = {}));
  81913. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81914. var BABYLON;
  81915. (function (BABYLON) {
  81916. var FileFaceOrientation = /** @class */ (function () {
  81917. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81918. this.name = name;
  81919. this.worldAxisForNormal = worldAxisForNormal;
  81920. this.worldAxisForFileX = worldAxisForFileX;
  81921. this.worldAxisForFileY = worldAxisForFileY;
  81922. }
  81923. return FileFaceOrientation;
  81924. }());
  81925. ;
  81926. /**
  81927. * Helper class dealing with the extraction of spherical polynomial dataArray
  81928. * from a cube map.
  81929. */
  81930. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81931. function CubeMapToSphericalPolynomialTools() {
  81932. }
  81933. /**
  81934. * Converts a texture to the according Spherical Polynomial data.
  81935. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81936. *
  81937. * @param texture The texture to extract the information from.
  81938. * @return The Spherical Polynomial data.
  81939. */
  81940. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81941. if (!texture.isCube) {
  81942. // Only supports cube Textures currently.
  81943. return null;
  81944. }
  81945. var size = texture.getSize().width;
  81946. var right = texture.readPixels(0);
  81947. var left = texture.readPixels(1);
  81948. var up;
  81949. var down;
  81950. if (texture.isRenderTarget) {
  81951. up = texture.readPixels(3);
  81952. down = texture.readPixels(2);
  81953. }
  81954. else {
  81955. up = texture.readPixels(2);
  81956. down = texture.readPixels(3);
  81957. }
  81958. var front = texture.readPixels(4);
  81959. var back = texture.readPixels(5);
  81960. var gammaSpace = texture.gammaSpace;
  81961. // Always read as RGBA.
  81962. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81963. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81964. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81965. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81966. }
  81967. var cubeInfo = {
  81968. size: size,
  81969. right: right,
  81970. left: left,
  81971. up: up,
  81972. down: down,
  81973. front: front,
  81974. back: back,
  81975. format: format,
  81976. type: type,
  81977. gammaSpace: gammaSpace,
  81978. };
  81979. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81980. };
  81981. /**
  81982. * Converts a cubemap to the according Spherical Polynomial data.
  81983. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81984. *
  81985. * @param cubeInfo The Cube map to extract the information from.
  81986. * @return The Spherical Polynomial data.
  81987. */
  81988. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81989. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81990. var totalSolidAngle = 0.0;
  81991. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81992. var du = 2.0 / cubeInfo.size;
  81993. var dv = du;
  81994. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81995. var minUV = du * 0.5 - 1.0;
  81996. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81997. var fileFace = this.FileFaces[faceIndex];
  81998. var dataArray = cubeInfo[fileFace.name];
  81999. var v = minUV;
  82000. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  82001. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  82002. // Because SP is still linear, so summation is fine in that basis.
  82003. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  82004. for (var y = 0; y < cubeInfo.size; y++) {
  82005. var u = minUV;
  82006. for (var x = 0; x < cubeInfo.size; x++) {
  82007. // World direction (not normalised)
  82008. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  82009. worldDirection.normalize();
  82010. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  82011. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  82012. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  82013. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  82014. // Handle Integer types.
  82015. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82016. r /= 255;
  82017. g /= 255;
  82018. b /= 255;
  82019. }
  82020. // Handle Gamma space textures.
  82021. if (cubeInfo.gammaSpace) {
  82022. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  82023. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  82024. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  82025. }
  82026. var color = new BABYLON.Color3(r, g, b);
  82027. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  82028. totalSolidAngle += deltaSolidAngle;
  82029. u += du;
  82030. }
  82031. v += dv;
  82032. }
  82033. }
  82034. // Solid angle for entire sphere is 4*pi
  82035. var sphereSolidAngle = 4.0 * Math.PI;
  82036. // Adjust the solid angle to allow for how many faces we processed.
  82037. var facesProcessed = 6.0;
  82038. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  82039. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  82040. // This is needed because the numerical integration over the cube uses a
  82041. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  82042. // and also to compensate for accumulative error due to float precision in the summation.
  82043. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  82044. sphericalHarmonics.scale(correctionFactor);
  82045. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  82046. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  82047. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  82048. };
  82049. CubeMapToSphericalPolynomialTools.FileFaces = [
  82050. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  82051. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  82052. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  82053. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  82054. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  82055. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  82056. ];
  82057. return CubeMapToSphericalPolynomialTools;
  82058. }());
  82059. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  82060. })(BABYLON || (BABYLON = {}));
  82061. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  82062. var BABYLON;
  82063. (function (BABYLON) {
  82064. /**
  82065. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  82066. */
  82067. var PanoramaToCubeMapTools = /** @class */ (function () {
  82068. function PanoramaToCubeMapTools() {
  82069. }
  82070. /**
  82071. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  82072. *
  82073. * @param float32Array The source data.
  82074. * @param inputWidth The width of the input panorama.
  82075. * @param inputhHeight The height of the input panorama.
  82076. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  82077. * @return The cubemap data
  82078. */
  82079. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  82080. if (!float32Array) {
  82081. throw "ConvertPanoramaToCubemap: input cannot be null";
  82082. }
  82083. if (float32Array.length != inputWidth * inputHeight * 3) {
  82084. throw "ConvertPanoramaToCubemap: input size is wrong";
  82085. }
  82086. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  82087. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  82088. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  82089. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  82090. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  82091. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  82092. return {
  82093. front: textureFront,
  82094. back: textureBack,
  82095. left: textureLeft,
  82096. right: textureRight,
  82097. up: textureUp,
  82098. down: textureDown,
  82099. size: size,
  82100. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  82101. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  82102. gammaSpace: false,
  82103. };
  82104. };
  82105. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  82106. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  82107. var textureArray = new Float32Array(buffer);
  82108. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  82109. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  82110. var dy = 1 / texSize;
  82111. var fy = 0;
  82112. for (var y = 0; y < texSize; y++) {
  82113. var xv1 = faceData[0];
  82114. var xv2 = faceData[2];
  82115. for (var x = 0; x < texSize; x++) {
  82116. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  82117. v.normalize();
  82118. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  82119. // 3 channels per pixels
  82120. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  82121. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  82122. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  82123. xv1 = xv1.add(rotDX1);
  82124. xv2 = xv2.add(rotDX2);
  82125. }
  82126. fy += dy;
  82127. }
  82128. return textureArray;
  82129. };
  82130. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  82131. var theta = Math.atan2(vDir.z, vDir.x);
  82132. var phi = Math.acos(vDir.y);
  82133. while (theta < -Math.PI)
  82134. theta += 2 * Math.PI;
  82135. while (theta > Math.PI)
  82136. theta -= 2 * Math.PI;
  82137. var dx = theta / Math.PI;
  82138. var dy = phi / Math.PI;
  82139. // recenter.
  82140. dx = dx * 0.5 + 0.5;
  82141. var px = Math.round(dx * inputWidth);
  82142. if (px < 0)
  82143. px = 0;
  82144. else if (px >= inputWidth)
  82145. px = inputWidth - 1;
  82146. var py = Math.round(dy * inputHeight);
  82147. if (py < 0)
  82148. py = 0;
  82149. else if (py >= inputHeight)
  82150. py = inputHeight - 1;
  82151. var inputY = (inputHeight - py - 1);
  82152. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  82153. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  82154. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  82155. return {
  82156. r: r,
  82157. g: g,
  82158. b: b
  82159. };
  82160. };
  82161. PanoramaToCubeMapTools.FACE_FRONT = [
  82162. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82163. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82164. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82165. new BABYLON.Vector3(1.0, 1.0, -1.0)
  82166. ];
  82167. PanoramaToCubeMapTools.FACE_BACK = [
  82168. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82169. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82170. new BABYLON.Vector3(1.0, 1.0, 1.0),
  82171. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  82172. ];
  82173. PanoramaToCubeMapTools.FACE_RIGHT = [
  82174. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82175. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82176. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82177. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82178. ];
  82179. PanoramaToCubeMapTools.FACE_LEFT = [
  82180. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82181. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82182. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82183. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  82184. ];
  82185. PanoramaToCubeMapTools.FACE_DOWN = [
  82186. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82187. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82188. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82189. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82190. ];
  82191. PanoramaToCubeMapTools.FACE_UP = [
  82192. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82193. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82194. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82195. new BABYLON.Vector3(1.0, -1.0, -1.0)
  82196. ];
  82197. return PanoramaToCubeMapTools;
  82198. }());
  82199. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  82200. })(BABYLON || (BABYLON = {}));
  82201. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  82202. var BABYLON;
  82203. (function (BABYLON) {
  82204. ;
  82205. /**
  82206. * This groups tools to convert HDR texture to native colors array.
  82207. */
  82208. var HDRTools = /** @class */ (function () {
  82209. function HDRTools() {
  82210. }
  82211. HDRTools.Ldexp = function (mantissa, exponent) {
  82212. if (exponent > 1023) {
  82213. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  82214. }
  82215. if (exponent < -1074) {
  82216. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  82217. }
  82218. return mantissa * Math.pow(2, exponent);
  82219. };
  82220. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  82221. if (exponent > 0) { /*nonzero pixel*/
  82222. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  82223. float32array[index + 0] = red * exponent;
  82224. float32array[index + 1] = green * exponent;
  82225. float32array[index + 2] = blue * exponent;
  82226. }
  82227. else {
  82228. float32array[index + 0] = 0;
  82229. float32array[index + 1] = 0;
  82230. float32array[index + 2] = 0;
  82231. }
  82232. };
  82233. HDRTools.readStringLine = function (uint8array, startIndex) {
  82234. var line = "";
  82235. var character = "";
  82236. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  82237. character = String.fromCharCode(uint8array[i]);
  82238. if (character == "\n") {
  82239. break;
  82240. }
  82241. line += character;
  82242. }
  82243. return line;
  82244. };
  82245. /**
  82246. * Reads header information from an RGBE texture stored in a native array.
  82247. * More information on this format are available here:
  82248. * https://en.wikipedia.org/wiki/RGBE_image_format
  82249. *
  82250. * @param uint8array The binary file stored in native array.
  82251. * @return The header information.
  82252. */
  82253. HDRTools.RGBE_ReadHeader = function (uint8array) {
  82254. var height = 0;
  82255. var width = 0;
  82256. var line = this.readStringLine(uint8array, 0);
  82257. if (line[0] != '#' || line[1] != '?') {
  82258. throw "Bad HDR Format.";
  82259. }
  82260. var endOfHeader = false;
  82261. var findFormat = false;
  82262. var lineIndex = 0;
  82263. do {
  82264. lineIndex += (line.length + 1);
  82265. line = this.readStringLine(uint8array, lineIndex);
  82266. if (line == "FORMAT=32-bit_rle_rgbe") {
  82267. findFormat = true;
  82268. }
  82269. else if (line.length == 0) {
  82270. endOfHeader = true;
  82271. }
  82272. } while (!endOfHeader);
  82273. if (!findFormat) {
  82274. throw "HDR Bad header format, unsupported FORMAT";
  82275. }
  82276. lineIndex += (line.length + 1);
  82277. line = this.readStringLine(uint8array, lineIndex);
  82278. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  82279. var match = sizeRegexp.exec(line);
  82280. // TODO. Support +Y and -X if needed.
  82281. if (!match || match.length < 3) {
  82282. throw "HDR Bad header format, no size";
  82283. }
  82284. width = parseInt(match[2]);
  82285. height = parseInt(match[1]);
  82286. if (width < 8 || width > 0x7fff) {
  82287. throw "HDR Bad header format, unsupported size";
  82288. }
  82289. lineIndex += (line.length + 1);
  82290. return {
  82291. height: height,
  82292. width: width,
  82293. dataPosition: lineIndex
  82294. };
  82295. };
  82296. /**
  82297. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  82298. * This RGBE texture needs to store the information as a panorama.
  82299. *
  82300. * More information on this format are available here:
  82301. * https://en.wikipedia.org/wiki/RGBE_image_format
  82302. *
  82303. * @param buffer The binary file stored in an array buffer.
  82304. * @param size The expected size of the extracted cubemap.
  82305. * @return The Cube Map information.
  82306. */
  82307. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  82308. var uint8array = new Uint8Array(buffer);
  82309. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  82310. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82311. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  82312. return cubeMapData;
  82313. };
  82314. /**
  82315. * Returns the pixels data extracted from an RGBE texture.
  82316. * This pixels will be stored left to right up to down in the R G B order in one array.
  82317. *
  82318. * More information on this format are available here:
  82319. * https://en.wikipedia.org/wiki/RGBE_image_format
  82320. *
  82321. * @param uint8array The binary file stored in an array buffer.
  82322. * @param hdrInfo The header information of the file.
  82323. * @return The pixels data in RGB right to left up to down order.
  82324. */
  82325. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82326. // Keep for multi format supports.
  82327. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82328. };
  82329. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82330. var num_scanlines = hdrInfo.height;
  82331. var scanline_width = hdrInfo.width;
  82332. var a, b, c, d, count;
  82333. var dataIndex = hdrInfo.dataPosition;
  82334. var index = 0, endIndex = 0, i = 0;
  82335. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82336. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82337. // 3 channels of 4 bytes per pixel in float.
  82338. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82339. var resultArray = new Float32Array(resultBuffer);
  82340. // read in each successive scanline
  82341. while (num_scanlines > 0) {
  82342. a = uint8array[dataIndex++];
  82343. b = uint8array[dataIndex++];
  82344. c = uint8array[dataIndex++];
  82345. d = uint8array[dataIndex++];
  82346. if (a != 2 || b != 2 || (c & 0x80)) {
  82347. // this file is not run length encoded
  82348. throw "HDR Bad header format, not RLE";
  82349. }
  82350. if (((c << 8) | d) != scanline_width) {
  82351. throw "HDR Bad header format, wrong scan line width";
  82352. }
  82353. index = 0;
  82354. // read each of the four channels for the scanline into the buffer
  82355. for (i = 0; i < 4; i++) {
  82356. endIndex = (i + 1) * scanline_width;
  82357. while (index < endIndex) {
  82358. a = uint8array[dataIndex++];
  82359. b = uint8array[dataIndex++];
  82360. if (a > 128) {
  82361. // a run of the same value
  82362. count = a - 128;
  82363. if ((count == 0) || (count > endIndex - index)) {
  82364. throw "HDR Bad Format, bad scanline data (run)";
  82365. }
  82366. while (count-- > 0) {
  82367. scanLineArray[index++] = b;
  82368. }
  82369. }
  82370. else {
  82371. // a non-run
  82372. count = a;
  82373. if ((count == 0) || (count > endIndex - index)) {
  82374. throw "HDR Bad Format, bad scanline data (non-run)";
  82375. }
  82376. scanLineArray[index++] = b;
  82377. if (--count > 0) {
  82378. for (var j = 0; j < count; j++) {
  82379. scanLineArray[index++] = uint8array[dataIndex++];
  82380. }
  82381. }
  82382. }
  82383. }
  82384. }
  82385. // now convert data from buffer into floats
  82386. for (i = 0; i < scanline_width; i++) {
  82387. a = scanLineArray[i];
  82388. b = scanLineArray[i + scanline_width];
  82389. c = scanLineArray[i + 2 * scanline_width];
  82390. d = scanLineArray[i + 3 * scanline_width];
  82391. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82392. }
  82393. num_scanlines--;
  82394. }
  82395. return resultArray;
  82396. };
  82397. return HDRTools;
  82398. }());
  82399. BABYLON.HDRTools = HDRTools;
  82400. })(BABYLON || (BABYLON = {}));
  82401. //# sourceMappingURL=babylon.hdr.js.map
  82402. var BABYLON;
  82403. (function (BABYLON) {
  82404. /**
  82405. * Sets of helpers addressing the serialization and deserialization of environment texture
  82406. * stored in a BabylonJS env file.
  82407. * Those files are usually stored as .env files.
  82408. */
  82409. var EnvironmentTextureTools = /** @class */ (function () {
  82410. function EnvironmentTextureTools() {
  82411. }
  82412. /**
  82413. * Gets the environment info from an env file.
  82414. * @param data The array buffer containing the .env bytes.
  82415. * @returns the environment file info (the json header) if successfully parsed.
  82416. */
  82417. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82418. var dataView = new DataView(data);
  82419. var pos = 0;
  82420. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82421. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82422. BABYLON.Tools.Error('Not a babylon environment map');
  82423. return null;
  82424. }
  82425. }
  82426. // Read json manifest - collect characters up to null terminator
  82427. var manifestString = '';
  82428. var charCode = 0x00;
  82429. while ((charCode = dataView.getUint8(pos++))) {
  82430. manifestString += String.fromCharCode(charCode);
  82431. }
  82432. var manifest = JSON.parse(manifestString);
  82433. if (manifest.specular) {
  82434. // Extend the header with the position of the payload.
  82435. manifest.specular.specularDataPosition = pos;
  82436. }
  82437. return manifest;
  82438. };
  82439. /**
  82440. * Creates an environment texture from a loaded cube texture.
  82441. * @param texture defines the cube texture to convert in env file
  82442. * @return a promise containing the environment data if succesfull.
  82443. */
  82444. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82445. var _this = this;
  82446. var internalTexture = texture.getInternalTexture();
  82447. if (!internalTexture) {
  82448. return Promise.reject("The cube texture is invalid.");
  82449. }
  82450. if (!texture._prefiltered) {
  82451. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82452. }
  82453. var engine = internalTexture.getEngine();
  82454. if (engine && engine.premultipliedAlpha) {
  82455. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82456. }
  82457. var canvas = engine.getRenderingCanvas();
  82458. if (!canvas) {
  82459. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82460. }
  82461. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82462. if (!engine.getCaps().textureFloatRender) {
  82463. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82464. if (!engine.getCaps().textureHalfFloatRender) {
  82465. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82466. }
  82467. }
  82468. var cubeWidth = internalTexture.width;
  82469. var hostingScene = new BABYLON.Scene(engine);
  82470. var specularTextures = {};
  82471. var promises = [];
  82472. // Read and collect all mipmaps data from the cube.
  82473. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82474. mipmapsCount = Math.round(mipmapsCount);
  82475. var _loop_1 = function (i) {
  82476. var faceWidth = Math.pow(2, mipmapsCount - i);
  82477. var _loop_2 = function (face) {
  82478. var data = texture.readPixels(face, i);
  82479. // Creates a temp texture with the face data.
  82480. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82481. // And rgbdEncode them.
  82482. var promise = new Promise(function (resolve, reject) {
  82483. 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);
  82484. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82485. rgbdPostProcess.onApply = function (effect) {
  82486. effect._bindTexture("textureSampler", tempTexture);
  82487. };
  82488. // As the process needs to happen on the main canvas, keep track of the current size
  82489. var currentW = engine.getRenderWidth();
  82490. var currentH = engine.getRenderHeight();
  82491. // Set the desired size for the texture
  82492. engine.setSize(faceWidth, faceWidth);
  82493. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82494. // Reading datas from WebGL
  82495. BABYLON.Tools.ToBlob(canvas, function (blob) {
  82496. var fileReader = new FileReader();
  82497. fileReader.onload = function (event) {
  82498. var arrayBuffer = event.target.result;
  82499. specularTextures[i * 6 + face] = arrayBuffer;
  82500. resolve();
  82501. };
  82502. fileReader.readAsArrayBuffer(blob);
  82503. });
  82504. // Reapply the previous canvas size
  82505. engine.setSize(currentW, currentH);
  82506. });
  82507. });
  82508. promises.push(promise);
  82509. };
  82510. // All faces of the cube.
  82511. for (var face = 0; face < 6; face++) {
  82512. _loop_2(face);
  82513. }
  82514. };
  82515. for (var i = 0; i <= mipmapsCount; i++) {
  82516. _loop_1(i);
  82517. }
  82518. // Once all the textures haves been collected as RGBD stored in PNGs
  82519. return Promise.all(promises).then(function () {
  82520. // We can delete the hosting scene keeping track of all the creation objects
  82521. hostingScene.dispose();
  82522. // Creates the json header for the env texture
  82523. var info = {
  82524. version: 1,
  82525. width: cubeWidth,
  82526. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82527. specular: {
  82528. mipmaps: []
  82529. }
  82530. };
  82531. // Sets the specular image data information
  82532. var position = 0;
  82533. for (var i = 0; i <= mipmapsCount; i++) {
  82534. for (var face = 0; face < 6; face++) {
  82535. var byteLength = specularTextures[i * 6 + face].byteLength;
  82536. info.specular.mipmaps.push({
  82537. length: byteLength,
  82538. position: position
  82539. });
  82540. position += byteLength;
  82541. }
  82542. }
  82543. // Encode the JSON as an array buffer
  82544. var infoString = JSON.stringify(info);
  82545. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82546. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82547. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82548. infoView[i] = infoString.charCodeAt(i);
  82549. }
  82550. // Ends up with a null terminator for easier parsing
  82551. infoView[infoString.length] = 0x00;
  82552. // Computes the final required size and creates the storage
  82553. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82554. var finalBuffer = new ArrayBuffer(totalSize);
  82555. var finalBufferView = new Uint8Array(finalBuffer);
  82556. var dataView = new DataView(finalBuffer);
  82557. // Copy the magic bytes identifying the file in
  82558. var pos = 0;
  82559. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82560. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82561. }
  82562. // Add the json info
  82563. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82564. pos += infoBuffer.byteLength;
  82565. // Finally inserts the texture data
  82566. for (var i = 0; i <= mipmapsCount; i++) {
  82567. for (var face = 0; face < 6; face++) {
  82568. var dataBuffer = specularTextures[i * 6 + face];
  82569. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82570. pos += dataBuffer.byteLength;
  82571. }
  82572. }
  82573. // Voila
  82574. return finalBuffer;
  82575. });
  82576. };
  82577. /**
  82578. * Creates a JSON representation of the spherical data.
  82579. * @param texture defines the texture containing the polynomials
  82580. * @return the JSON representation of the spherical info
  82581. */
  82582. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82583. var polynmials = texture.sphericalPolynomial;
  82584. if (polynmials == null) {
  82585. return null;
  82586. }
  82587. return {
  82588. polynomials: true,
  82589. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82590. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82591. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82592. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82593. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82594. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82595. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82596. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82597. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82598. };
  82599. };
  82600. /**
  82601. * Uploads the texture info contained in the env file to te GPU.
  82602. * @param texture defines the internal texture to upload to
  82603. * @param arrayBuffer defines the buffer cotaining the data to load
  82604. * @param info defines the texture info retrieved through the GetEnvInfo method
  82605. * @returns a promise
  82606. */
  82607. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  82608. if (info.version !== 1) {
  82609. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82610. }
  82611. var specularInfo = info.specular;
  82612. if (!specularInfo) {
  82613. // Nothing else parsed so far
  82614. return Promise.resolve();
  82615. }
  82616. // Double checks the enclosed info
  82617. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82618. mipmapsCount = Math.round(mipmapsCount) + 1;
  82619. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82620. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82621. }
  82622. // Gets everything ready.
  82623. var engine = texture.getEngine();
  82624. var expandTexture = false;
  82625. var generateNonLODTextures = false;
  82626. var rgbdPostProcess = null;
  82627. var cubeRtt = null;
  82628. var lodTextures = null;
  82629. var caps = engine.getCaps();
  82630. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82631. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82632. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82633. // Add extra process if texture lod is not supported
  82634. if (!caps.textureLOD) {
  82635. expandTexture = false;
  82636. generateNonLODTextures = true;
  82637. lodTextures = {};
  82638. }
  82639. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82640. else if (engine.webGLVersion < 2) {
  82641. expandTexture = false;
  82642. }
  82643. // If half float available we can uncompress the texture
  82644. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82645. expandTexture = true;
  82646. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82647. }
  82648. // If full float available we can uncompress the texture
  82649. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82650. expandTexture = true;
  82651. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82652. }
  82653. // Expand the texture if possible
  82654. if (expandTexture) {
  82655. // Simply run through the decode PP
  82656. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82657. texture._isRGBD = false;
  82658. texture.invertY = false;
  82659. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82660. generateDepthBuffer: false,
  82661. generateMipMaps: true,
  82662. generateStencilBuffer: false,
  82663. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82664. type: texture.type,
  82665. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82666. });
  82667. }
  82668. else {
  82669. texture._isRGBD = true;
  82670. texture.invertY = true;
  82671. // In case of missing support, applies the same patch than DDS files.
  82672. if (generateNonLODTextures) {
  82673. var mipSlices = 3;
  82674. var scale = texture._lodGenerationScale;
  82675. var offset = texture._lodGenerationOffset;
  82676. for (var i = 0; i < mipSlices; i++) {
  82677. //compute LOD from even spacing in smoothness (matching shader calculation)
  82678. var smoothness = i / (mipSlices - 1);
  82679. var roughness = 1 - smoothness;
  82680. var minLODIndex = offset; // roughness = 0
  82681. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  82682. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82683. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82684. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82685. glTextureFromLod.isCube = true;
  82686. glTextureFromLod.invertY = true;
  82687. glTextureFromLod.generateMipMaps = false;
  82688. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82689. // Wrap in a base texture for easy binding.
  82690. var lodTexture = new BABYLON.BaseTexture(null);
  82691. lodTexture.isCube = true;
  82692. lodTexture._texture = glTextureFromLod;
  82693. lodTextures[mipmapIndex] = lodTexture;
  82694. switch (i) {
  82695. case 0:
  82696. texture._lodTextureLow = lodTexture;
  82697. break;
  82698. case 1:
  82699. texture._lodTextureMid = lodTexture;
  82700. break;
  82701. case 2:
  82702. texture._lodTextureHigh = lodTexture;
  82703. break;
  82704. }
  82705. }
  82706. }
  82707. }
  82708. var promises = [];
  82709. var _loop_3 = function (i) {
  82710. var _loop_4 = function (face) {
  82711. // Retrieves the face data
  82712. var imageData = specularInfo.mipmaps[i * 6 + face];
  82713. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  82714. // Constructs an image element from bytes
  82715. var blob = new Blob([bytes], { type: 'image/png' });
  82716. var url = URL.createObjectURL(blob);
  82717. var image = new Image();
  82718. image.src = url;
  82719. // Enqueue promise to upload to the texture.
  82720. var promise = new Promise(function (resolve, reject) {
  82721. ;
  82722. image.onload = function () {
  82723. if (expandTexture) {
  82724. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82725. reject(message);
  82726. }, image);
  82727. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82728. // Uncompress the data to a RTT
  82729. rgbdPostProcess.onApply = function (effect) {
  82730. effect._bindTexture("textureSampler", tempTexture_1);
  82731. effect.setFloat2("scale", 1, 1);
  82732. };
  82733. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82734. // Cleanup
  82735. engine.restoreDefaultFramebuffer();
  82736. tempTexture_1.dispose();
  82737. window.URL.revokeObjectURL(url);
  82738. resolve();
  82739. });
  82740. }
  82741. else {
  82742. engine._uploadImageToTexture(texture, face, i, image);
  82743. // Upload the face to the none lod texture support
  82744. if (generateNonLODTextures) {
  82745. var lodTexture = lodTextures[i];
  82746. if (lodTexture) {
  82747. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  82748. }
  82749. }
  82750. resolve();
  82751. }
  82752. };
  82753. image.onerror = function (error) {
  82754. reject(error);
  82755. };
  82756. });
  82757. promises.push(promise);
  82758. };
  82759. // All faces
  82760. for (var face = 0; face < 6; face++) {
  82761. _loop_4(face);
  82762. }
  82763. };
  82764. // All mipmaps
  82765. for (var i = 0; i < mipmapsCount; i++) {
  82766. _loop_3(i);
  82767. }
  82768. // Once all done, finishes the cleanup and return
  82769. return Promise.all(promises).then(function () {
  82770. // Relase temp RTT.
  82771. if (cubeRtt) {
  82772. engine._releaseFramebufferObjects(cubeRtt);
  82773. cubeRtt._swapAndDie(texture);
  82774. }
  82775. // Relase temp Post Process.
  82776. if (rgbdPostProcess) {
  82777. rgbdPostProcess.dispose();
  82778. }
  82779. // Flag internal texture as ready in case they are in use.
  82780. if (generateNonLODTextures) {
  82781. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82782. texture._lodTextureHigh._texture.isReady = true;
  82783. }
  82784. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82785. texture._lodTextureMid._texture.isReady = true;
  82786. }
  82787. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82788. texture._lodTextureLow._texture.isReady = true;
  82789. }
  82790. }
  82791. });
  82792. };
  82793. /**
  82794. * Uploads spherical polynomials information to the texture.
  82795. * @param texture defines the texture we are trying to upload the information to
  82796. * @param arrayBuffer defines the array buffer holding the data
  82797. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82798. */
  82799. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  82800. if (info.version !== 1) {
  82801. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82802. }
  82803. var irradianceInfo = info.irradiance;
  82804. if (!irradianceInfo) {
  82805. return;
  82806. }
  82807. //harmonics now represent radiance
  82808. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  82809. if (irradianceInfo.polynomials) {
  82810. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  82811. }
  82812. else {
  82813. // convert From SH to SP.
  82814. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  82815. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  82816. }
  82817. };
  82818. /**
  82819. * Upload spherical polynomial coefficients to the texture
  82820. * @param polynmials Spherical polynmial coefficients (9)
  82821. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82822. */
  82823. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  82824. outPolynomialCoefficents.x.x = polynmials.x[0];
  82825. outPolynomialCoefficents.x.y = polynmials.x[1];
  82826. outPolynomialCoefficents.x.z = polynmials.x[2];
  82827. outPolynomialCoefficents.y.x = polynmials.y[0];
  82828. outPolynomialCoefficents.y.y = polynmials.y[1];
  82829. outPolynomialCoefficents.y.z = polynmials.y[2];
  82830. outPolynomialCoefficents.z.x = polynmials.z[0];
  82831. outPolynomialCoefficents.z.y = polynmials.z[1];
  82832. outPolynomialCoefficents.z.z = polynmials.z[2];
  82833. //xx
  82834. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  82835. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  82836. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  82837. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  82838. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  82839. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  82840. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  82841. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  82842. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  82843. //yz
  82844. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  82845. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  82846. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  82847. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  82848. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  82849. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  82850. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  82851. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  82852. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  82853. };
  82854. /**
  82855. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82856. * L = (1/pi) * E * rho
  82857. *
  82858. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82859. * @param harmonics Spherical harmonic coefficients (9)
  82860. */
  82861. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  82862. var scaleFactor = 1 / 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. harmonics.l00[0] *= scaleFactor;
  82866. harmonics.l00[1] *= scaleFactor;
  82867. harmonics.l00[2] *= scaleFactor;
  82868. harmonics.l1_1[0] *= scaleFactor;
  82869. harmonics.l1_1[1] *= scaleFactor;
  82870. harmonics.l1_1[2] *= scaleFactor;
  82871. harmonics.l10[0] *= scaleFactor;
  82872. harmonics.l10[1] *= scaleFactor;
  82873. harmonics.l10[2] *= scaleFactor;
  82874. harmonics.l11[0] *= scaleFactor;
  82875. harmonics.l11[1] *= scaleFactor;
  82876. harmonics.l11[2] *= scaleFactor;
  82877. harmonics.l2_2[0] *= scaleFactor;
  82878. harmonics.l2_2[1] *= scaleFactor;
  82879. harmonics.l2_2[2] *= scaleFactor;
  82880. harmonics.l2_1[0] *= scaleFactor;
  82881. harmonics.l2_1[1] *= scaleFactor;
  82882. harmonics.l2_1[2] *= scaleFactor;
  82883. harmonics.l20[0] *= scaleFactor;
  82884. harmonics.l20[1] *= scaleFactor;
  82885. harmonics.l20[2] *= scaleFactor;
  82886. harmonics.l21[0] *= scaleFactor;
  82887. harmonics.l21[1] *= scaleFactor;
  82888. harmonics.l21[2] *= scaleFactor;
  82889. harmonics.l22[0] *= scaleFactor;
  82890. harmonics.l22[1] *= scaleFactor;
  82891. harmonics.l22[2] *= scaleFactor;
  82892. };
  82893. /**
  82894. * Convert spherical harmonics to spherical polynomial coefficients
  82895. * @param harmonics Spherical harmonic coefficients (9)
  82896. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82897. */
  82898. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  82899. var rPi = 1 / Math.PI;
  82900. //x
  82901. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  82902. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  82903. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  82904. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  82905. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  82906. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  82907. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  82908. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  82909. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  82910. //xx
  82911. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82912. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82913. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82914. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82915. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82916. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82917. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82918. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82919. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82920. //yz
  82921. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82922. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82923. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82924. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82925. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82926. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82927. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82928. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82929. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82930. };
  82931. /**
  82932. * Magic number identifying the env file.
  82933. */
  82934. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82935. return EnvironmentTextureTools;
  82936. }());
  82937. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82938. })(BABYLON || (BABYLON = {}));
  82939. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82940. var BABYLON;
  82941. (function (BABYLON) {
  82942. /**
  82943. * This represents a texture coming from an HDR input.
  82944. *
  82945. * The only supported format is currently panorama picture stored in RGBE format.
  82946. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82947. */
  82948. var HDRCubeTexture = /** @class */ (function (_super) {
  82949. __extends(HDRCubeTexture, _super);
  82950. /**
  82951. * Instantiates an HDRTexture from the following parameters.
  82952. *
  82953. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82954. * @param scene The scene the texture will be used in
  82955. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82956. * @param noMipmap Forces to not generate the mipmap if true
  82957. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82958. * @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)
  82959. * @param reserved Reserved flag for internal use.
  82960. */
  82961. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82962. if (noMipmap === void 0) { noMipmap = false; }
  82963. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82964. if (gammaSpace === void 0) { gammaSpace = false; }
  82965. if (reserved === void 0) { reserved = false; }
  82966. if (onLoad === void 0) { onLoad = null; }
  82967. if (onError === void 0) { onError = null; }
  82968. var _this = _super.call(this, scene) || this;
  82969. _this._generateHarmonics = true;
  82970. _this._onLoad = null;
  82971. _this._onError = null;
  82972. /**
  82973. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82974. */
  82975. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82976. _this._isBlocking = true;
  82977. _this._rotationY = 0;
  82978. /**
  82979. * Gets or sets the center of the bounding box associated with the cube texture
  82980. * It must define where the camera used to render the texture was set
  82981. */
  82982. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82983. if (!url) {
  82984. return _this;
  82985. }
  82986. _this.name = url;
  82987. _this.url = url;
  82988. _this.hasAlpha = false;
  82989. _this.isCube = true;
  82990. _this._textureMatrix = BABYLON.Matrix.Identity();
  82991. _this._onLoad = onLoad;
  82992. _this._onError = onError;
  82993. _this.gammaSpace = gammaSpace;
  82994. _this._noMipmap = noMipmap;
  82995. _this._size = size;
  82996. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82997. if (!_this._texture) {
  82998. if (!scene.useDelayedTextureLoading) {
  82999. _this.loadTexture();
  83000. }
  83001. else {
  83002. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83003. }
  83004. }
  83005. return _this;
  83006. }
  83007. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83008. /**
  83009. * Gets wether or not the texture is blocking during loading.
  83010. */
  83011. get: function () {
  83012. return this._isBlocking;
  83013. },
  83014. /**
  83015. * Sets wether or not the texture is blocking during loading.
  83016. */
  83017. set: function (value) {
  83018. this._isBlocking = value;
  83019. },
  83020. enumerable: true,
  83021. configurable: true
  83022. });
  83023. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83024. /**
  83025. * Gets texture matrix rotation angle around Y axis radians.
  83026. */
  83027. get: function () {
  83028. return this._rotationY;
  83029. },
  83030. /**
  83031. * Sets texture matrix rotation angle around Y axis in radians.
  83032. */
  83033. set: function (value) {
  83034. this._rotationY = value;
  83035. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83036. },
  83037. enumerable: true,
  83038. configurable: true
  83039. });
  83040. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83041. get: function () {
  83042. return this._boundingBoxSize;
  83043. },
  83044. /**
  83045. * Gets or sets the size of the bounding box associated with the cube texture
  83046. * When defined, the cubemap will switch to local mode
  83047. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83048. * @example https://www.babylonjs-playground.com/#RNASML
  83049. */
  83050. set: function (value) {
  83051. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83052. return;
  83053. }
  83054. this._boundingBoxSize = value;
  83055. var scene = this.getScene();
  83056. if (scene) {
  83057. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83058. }
  83059. },
  83060. enumerable: true,
  83061. configurable: true
  83062. });
  83063. /**
  83064. * Occurs when the file is raw .hdr file.
  83065. */
  83066. HDRCubeTexture.prototype.loadTexture = function () {
  83067. var _this = this;
  83068. var callback = function (buffer) {
  83069. _this.lodGenerationOffset = 0.0;
  83070. _this.lodGenerationScale = 0.8;
  83071. var scene = _this.getScene();
  83072. if (!scene) {
  83073. return null;
  83074. }
  83075. // Extract the raw linear data.
  83076. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83077. // Generate harmonics if needed.
  83078. if (_this._generateHarmonics) {
  83079. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83080. _this.sphericalPolynomial = sphericalPolynomial;
  83081. }
  83082. var results = [];
  83083. var byteArray = null;
  83084. // Push each faces.
  83085. for (var j = 0; j < 6; j++) {
  83086. // Create uintarray fallback.
  83087. if (!scene.getEngine().getCaps().textureFloat) {
  83088. // 3 channels of 1 bytes per pixel in bytes.
  83089. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83090. byteArray = new Uint8Array(byteBuffer);
  83091. }
  83092. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83093. // If special cases.
  83094. if (_this.gammaSpace || byteArray) {
  83095. for (var i = 0; i < _this._size * _this._size; i++) {
  83096. // Put in gamma space if requested.
  83097. if (_this.gammaSpace) {
  83098. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83099. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83100. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83101. }
  83102. // Convert to int texture for fallback.
  83103. if (byteArray) {
  83104. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83105. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83106. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83107. // May use luminance instead if the result is not accurate.
  83108. var max = Math.max(Math.max(r, g), b);
  83109. if (max > 255) {
  83110. var scale = 255 / max;
  83111. r *= scale;
  83112. g *= scale;
  83113. b *= scale;
  83114. }
  83115. byteArray[(i * 3) + 0] = r;
  83116. byteArray[(i * 3) + 1] = g;
  83117. byteArray[(i * 3) + 2] = b;
  83118. }
  83119. }
  83120. }
  83121. if (byteArray) {
  83122. results.push(byteArray);
  83123. }
  83124. else {
  83125. results.push(dataFace);
  83126. }
  83127. }
  83128. return results;
  83129. };
  83130. var scene = this.getScene();
  83131. if (scene) {
  83132. 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);
  83133. }
  83134. };
  83135. HDRCubeTexture.prototype.clone = function () {
  83136. var scene = this.getScene();
  83137. if (!scene) {
  83138. return this;
  83139. }
  83140. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83141. // Base texture
  83142. newTexture.level = this.level;
  83143. newTexture.wrapU = this.wrapU;
  83144. newTexture.wrapV = this.wrapV;
  83145. newTexture.coordinatesIndex = this.coordinatesIndex;
  83146. newTexture.coordinatesMode = this.coordinatesMode;
  83147. return newTexture;
  83148. };
  83149. // Methods
  83150. HDRCubeTexture.prototype.delayLoad = function () {
  83151. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83152. return;
  83153. }
  83154. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83155. this._texture = this._getFromCache(this.url, this._noMipmap);
  83156. if (!this._texture) {
  83157. this.loadTexture();
  83158. }
  83159. };
  83160. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83161. return this._textureMatrix;
  83162. };
  83163. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83164. this._textureMatrix = value;
  83165. };
  83166. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83167. var texture = null;
  83168. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83169. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83170. texture.name = parsedTexture.name;
  83171. texture.hasAlpha = parsedTexture.hasAlpha;
  83172. texture.level = parsedTexture.level;
  83173. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83174. texture.isBlocking = parsedTexture.isBlocking;
  83175. }
  83176. if (texture) {
  83177. if (parsedTexture.boundingBoxPosition) {
  83178. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83179. }
  83180. if (parsedTexture.boundingBoxSize) {
  83181. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83182. }
  83183. if (parsedTexture.rotationY) {
  83184. texture.rotationY = parsedTexture.rotationY;
  83185. }
  83186. }
  83187. return texture;
  83188. };
  83189. HDRCubeTexture.prototype.serialize = function () {
  83190. if (!this.name) {
  83191. return null;
  83192. }
  83193. var serializationObject = {};
  83194. serializationObject.name = this.name;
  83195. serializationObject.hasAlpha = this.hasAlpha;
  83196. serializationObject.isCube = true;
  83197. serializationObject.level = this.level;
  83198. serializationObject.size = this._size;
  83199. serializationObject.coordinatesMode = this.coordinatesMode;
  83200. serializationObject.useInGammaSpace = this.gammaSpace;
  83201. serializationObject.generateHarmonics = this._generateHarmonics;
  83202. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83203. serializationObject.noMipmap = this._noMipmap;
  83204. serializationObject.isBlocking = this._isBlocking;
  83205. serializationObject.rotationY = this._rotationY;
  83206. return serializationObject;
  83207. };
  83208. HDRCubeTexture._facesMapping = [
  83209. "right",
  83210. "left",
  83211. "up",
  83212. "down",
  83213. "front",
  83214. "back"
  83215. ];
  83216. return HDRCubeTexture;
  83217. }(BABYLON.BaseTexture));
  83218. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83219. })(BABYLON || (BABYLON = {}));
  83220. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83221. var BABYLON;
  83222. (function (BABYLON) {
  83223. var IndexedVector2 = /** @class */ (function (_super) {
  83224. __extends(IndexedVector2, _super);
  83225. function IndexedVector2(original, index) {
  83226. var _this = _super.call(this, original.x, original.y) || this;
  83227. _this.index = index;
  83228. return _this;
  83229. }
  83230. return IndexedVector2;
  83231. }(BABYLON.Vector2));
  83232. var PolygonPoints = /** @class */ (function () {
  83233. function PolygonPoints() {
  83234. this.elements = new Array();
  83235. }
  83236. PolygonPoints.prototype.add = function (originalPoints) {
  83237. var _this = this;
  83238. var result = new Array();
  83239. originalPoints.forEach(function (point) {
  83240. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83241. var newPoint = new IndexedVector2(point, _this.elements.length);
  83242. result.push(newPoint);
  83243. _this.elements.push(newPoint);
  83244. }
  83245. });
  83246. return result;
  83247. };
  83248. PolygonPoints.prototype.computeBounds = function () {
  83249. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83250. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83251. this.elements.forEach(function (point) {
  83252. // x
  83253. if (point.x < lmin.x) {
  83254. lmin.x = point.x;
  83255. }
  83256. else if (point.x > lmax.x) {
  83257. lmax.x = point.x;
  83258. }
  83259. // y
  83260. if (point.y < lmin.y) {
  83261. lmin.y = point.y;
  83262. }
  83263. else if (point.y > lmax.y) {
  83264. lmax.y = point.y;
  83265. }
  83266. });
  83267. return {
  83268. min: lmin,
  83269. max: lmax,
  83270. width: lmax.x - lmin.x,
  83271. height: lmax.y - lmin.y
  83272. };
  83273. };
  83274. return PolygonPoints;
  83275. }());
  83276. var Polygon = /** @class */ (function () {
  83277. function Polygon() {
  83278. }
  83279. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83280. return [
  83281. new BABYLON.Vector2(xmin, ymin),
  83282. new BABYLON.Vector2(xmax, ymin),
  83283. new BABYLON.Vector2(xmax, ymax),
  83284. new BABYLON.Vector2(xmin, ymax)
  83285. ];
  83286. };
  83287. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83288. if (cx === void 0) { cx = 0; }
  83289. if (cy === void 0) { cy = 0; }
  83290. if (numberOfSides === void 0) { numberOfSides = 32; }
  83291. var result = new Array();
  83292. var angle = 0;
  83293. var increment = (Math.PI * 2) / numberOfSides;
  83294. for (var i = 0; i < numberOfSides; i++) {
  83295. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83296. angle -= increment;
  83297. }
  83298. return result;
  83299. };
  83300. Polygon.Parse = function (input) {
  83301. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83302. var i, result = [];
  83303. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83304. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83305. }
  83306. return result;
  83307. };
  83308. Polygon.StartingAt = function (x, y) {
  83309. return BABYLON.Path2.StartingAt(x, y);
  83310. };
  83311. return Polygon;
  83312. }());
  83313. BABYLON.Polygon = Polygon;
  83314. var PolygonMeshBuilder = /** @class */ (function () {
  83315. function PolygonMeshBuilder(name, contours, scene) {
  83316. this._points = new PolygonPoints();
  83317. this._outlinepoints = new PolygonPoints();
  83318. this._holes = new Array();
  83319. this._epoints = new Array();
  83320. this._eholes = new Array();
  83321. this._name = name;
  83322. this._scene = scene;
  83323. var points;
  83324. if (contours instanceof BABYLON.Path2) {
  83325. points = contours.getPoints();
  83326. }
  83327. else {
  83328. points = contours;
  83329. }
  83330. this._addToepoint(points);
  83331. this._points.add(points);
  83332. this._outlinepoints.add(points);
  83333. if (typeof earcut === 'undefined') {
  83334. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83335. }
  83336. }
  83337. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83338. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83339. var p = points_1[_i];
  83340. this._epoints.push(p.x, p.y);
  83341. }
  83342. };
  83343. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83344. this._points.add(hole);
  83345. var holepoints = new PolygonPoints();
  83346. holepoints.add(hole);
  83347. this._holes.push(holepoints);
  83348. this._eholes.push(this._epoints.length / 2);
  83349. this._addToepoint(hole);
  83350. return this;
  83351. };
  83352. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83353. var _this = this;
  83354. if (updatable === void 0) { updatable = false; }
  83355. if (depth === void 0) { depth = 0; }
  83356. var result = new BABYLON.Mesh(this._name, this._scene);
  83357. var normals = new Array();
  83358. var positions = new Array();
  83359. var uvs = new Array();
  83360. var bounds = this._points.computeBounds();
  83361. this._points.elements.forEach(function (p) {
  83362. normals.push(0, 1.0, 0);
  83363. positions.push(p.x, 0, p.y);
  83364. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83365. });
  83366. var indices = new Array();
  83367. var res = earcut(this._epoints, this._eholes, 2);
  83368. for (var i = 0; i < res.length; i++) {
  83369. indices.push(res[i]);
  83370. }
  83371. if (depth > 0) {
  83372. var positionscount = (positions.length / 3); //get the current pointcount
  83373. this._points.elements.forEach(function (p) {
  83374. normals.push(0, -1.0, 0);
  83375. positions.push(p.x, -depth, p.y);
  83376. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83377. });
  83378. var totalCount = indices.length;
  83379. for (var i = 0; i < totalCount; i += 3) {
  83380. var i0 = indices[i + 0];
  83381. var i1 = indices[i + 1];
  83382. var i2 = indices[i + 2];
  83383. indices.push(i2 + positionscount);
  83384. indices.push(i1 + positionscount);
  83385. indices.push(i0 + positionscount);
  83386. }
  83387. //Add the sides
  83388. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83389. this._holes.forEach(function (hole) {
  83390. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83391. });
  83392. }
  83393. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83394. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83395. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83396. result.setIndices(indices);
  83397. return result;
  83398. };
  83399. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83400. var StartIndex = positions.length / 3;
  83401. var ulength = 0;
  83402. for (var i = 0; i < points.elements.length; i++) {
  83403. var p = points.elements[i];
  83404. var p1;
  83405. if ((i + 1) > points.elements.length - 1) {
  83406. p1 = points.elements[0];
  83407. }
  83408. else {
  83409. p1 = points.elements[i + 1];
  83410. }
  83411. positions.push(p.x, 0, p.y);
  83412. positions.push(p.x, -depth, p.y);
  83413. positions.push(p1.x, 0, p1.y);
  83414. positions.push(p1.x, -depth, p1.y);
  83415. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83416. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83417. var v3 = v2.subtract(v1);
  83418. var v4 = new BABYLON.Vector3(0, 1, 0);
  83419. var vn = BABYLON.Vector3.Cross(v3, v4);
  83420. vn = vn.normalize();
  83421. uvs.push(ulength / bounds.width, 0);
  83422. uvs.push(ulength / bounds.width, 1);
  83423. ulength += v3.length();
  83424. uvs.push((ulength / bounds.width), 0);
  83425. uvs.push((ulength / bounds.width), 1);
  83426. if (!flip) {
  83427. normals.push(-vn.x, -vn.y, -vn.z);
  83428. normals.push(-vn.x, -vn.y, -vn.z);
  83429. normals.push(-vn.x, -vn.y, -vn.z);
  83430. normals.push(-vn.x, -vn.y, -vn.z);
  83431. indices.push(StartIndex);
  83432. indices.push(StartIndex + 1);
  83433. indices.push(StartIndex + 2);
  83434. indices.push(StartIndex + 1);
  83435. indices.push(StartIndex + 3);
  83436. indices.push(StartIndex + 2);
  83437. }
  83438. else {
  83439. normals.push(vn.x, vn.y, vn.z);
  83440. normals.push(vn.x, vn.y, vn.z);
  83441. normals.push(vn.x, vn.y, vn.z);
  83442. normals.push(vn.x, vn.y, vn.z);
  83443. indices.push(StartIndex);
  83444. indices.push(StartIndex + 2);
  83445. indices.push(StartIndex + 1);
  83446. indices.push(StartIndex + 1);
  83447. indices.push(StartIndex + 2);
  83448. indices.push(StartIndex + 3);
  83449. }
  83450. StartIndex += 4;
  83451. }
  83452. ;
  83453. };
  83454. return PolygonMeshBuilder;
  83455. }());
  83456. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83457. })(BABYLON || (BABYLON = {}));
  83458. //# sourceMappingURL=babylon.polygonMesh.js.map
  83459. var BABYLON;
  83460. (function (BABYLON) {
  83461. // Unique ID when we import meshes from Babylon to CSG
  83462. var currentCSGMeshId = 0;
  83463. // # class Vertex
  83464. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83465. // one to provide additional features like texture coordinates and vertex
  83466. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83467. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83468. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83469. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83470. // is not used anywhere else.
  83471. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83472. var Vertex = /** @class */ (function () {
  83473. function Vertex(pos, normal, uv) {
  83474. this.pos = pos;
  83475. this.normal = normal;
  83476. this.uv = uv;
  83477. }
  83478. Vertex.prototype.clone = function () {
  83479. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83480. };
  83481. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83482. // orientation of a polygon is flipped.
  83483. Vertex.prototype.flip = function () {
  83484. this.normal = this.normal.scale(-1);
  83485. };
  83486. // Create a new vertex between this vertex and `other` by linearly
  83487. // interpolating all properties using a parameter of `t`. Subclasses should
  83488. // override this to interpolate additional properties.
  83489. Vertex.prototype.interpolate = function (other, t) {
  83490. 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));
  83491. };
  83492. return Vertex;
  83493. }());
  83494. // # class Plane
  83495. // Represents a plane in 3D space.
  83496. var Plane = /** @class */ (function () {
  83497. function Plane(normal, w) {
  83498. this.normal = normal;
  83499. this.w = w;
  83500. }
  83501. Plane.FromPoints = function (a, b, c) {
  83502. var v0 = c.subtract(a);
  83503. var v1 = b.subtract(a);
  83504. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83505. return null;
  83506. }
  83507. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83508. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83509. };
  83510. Plane.prototype.clone = function () {
  83511. return new Plane(this.normal.clone(), this.w);
  83512. };
  83513. Plane.prototype.flip = function () {
  83514. this.normal.scaleInPlace(-1);
  83515. this.w = -this.w;
  83516. };
  83517. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83518. // fragments in the appropriate lists. Coplanar polygons go into either
  83519. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83520. // respect to this plane. Polygons in front or in back of this plane go into
  83521. // either `front` or `back`.
  83522. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83523. var COPLANAR = 0;
  83524. var FRONT = 1;
  83525. var BACK = 2;
  83526. var SPANNING = 3;
  83527. // Classify each point as well as the entire polygon into one of the above
  83528. // four classes.
  83529. var polygonType = 0;
  83530. var types = [];
  83531. var i;
  83532. var t;
  83533. for (i = 0; i < polygon.vertices.length; i++) {
  83534. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83535. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83536. polygonType |= type;
  83537. types.push(type);
  83538. }
  83539. // Put the polygon in the correct list, splitting it when necessary.
  83540. switch (polygonType) {
  83541. case COPLANAR:
  83542. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83543. break;
  83544. case FRONT:
  83545. front.push(polygon);
  83546. break;
  83547. case BACK:
  83548. back.push(polygon);
  83549. break;
  83550. case SPANNING:
  83551. var f = [], b = [];
  83552. for (i = 0; i < polygon.vertices.length; i++) {
  83553. var j = (i + 1) % polygon.vertices.length;
  83554. var ti = types[i], tj = types[j];
  83555. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83556. if (ti !== BACK)
  83557. f.push(vi);
  83558. if (ti !== FRONT)
  83559. b.push(ti !== BACK ? vi.clone() : vi);
  83560. if ((ti | tj) === SPANNING) {
  83561. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83562. var v = vi.interpolate(vj, t);
  83563. f.push(v);
  83564. b.push(v.clone());
  83565. }
  83566. }
  83567. var poly;
  83568. if (f.length >= 3) {
  83569. poly = new Polygon(f, polygon.shared);
  83570. if (poly.plane)
  83571. front.push(poly);
  83572. }
  83573. if (b.length >= 3) {
  83574. poly = new Polygon(b, polygon.shared);
  83575. if (poly.plane)
  83576. back.push(poly);
  83577. }
  83578. break;
  83579. }
  83580. };
  83581. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83582. // point is on the plane.
  83583. Plane.EPSILON = 1e-5;
  83584. return Plane;
  83585. }());
  83586. // # class Polygon
  83587. // Represents a convex polygon. The vertices used to initialize a polygon must
  83588. // be coplanar and form a convex loop.
  83589. //
  83590. // Each convex polygon has a `shared` property, which is shared between all
  83591. // polygons that are clones of each other or were split from the same polygon.
  83592. // This can be used to define per-polygon properties (such as surface color).
  83593. var Polygon = /** @class */ (function () {
  83594. function Polygon(vertices, shared) {
  83595. this.vertices = vertices;
  83596. this.shared = shared;
  83597. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83598. }
  83599. Polygon.prototype.clone = function () {
  83600. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83601. return new Polygon(vertices, this.shared);
  83602. };
  83603. Polygon.prototype.flip = function () {
  83604. this.vertices.reverse().map(function (v) { v.flip(); });
  83605. this.plane.flip();
  83606. };
  83607. return Polygon;
  83608. }());
  83609. // # class Node
  83610. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83611. // by picking a polygon to split along. That polygon (and all other coplanar
  83612. // polygons) are added directly to that node and the other polygons are added to
  83613. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83614. // no distinction between internal and leaf nodes.
  83615. var Node = /** @class */ (function () {
  83616. function Node(polygons) {
  83617. this.plane = null;
  83618. this.front = null;
  83619. this.back = null;
  83620. this.polygons = new Array();
  83621. if (polygons) {
  83622. this.build(polygons);
  83623. }
  83624. }
  83625. Node.prototype.clone = function () {
  83626. var node = new Node();
  83627. node.plane = this.plane && this.plane.clone();
  83628. node.front = this.front && this.front.clone();
  83629. node.back = this.back && this.back.clone();
  83630. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83631. return node;
  83632. };
  83633. // Convert solid space to empty space and empty space to solid space.
  83634. Node.prototype.invert = function () {
  83635. for (var i = 0; i < this.polygons.length; i++) {
  83636. this.polygons[i].flip();
  83637. }
  83638. if (this.plane) {
  83639. this.plane.flip();
  83640. }
  83641. if (this.front) {
  83642. this.front.invert();
  83643. }
  83644. if (this.back) {
  83645. this.back.invert();
  83646. }
  83647. var temp = this.front;
  83648. this.front = this.back;
  83649. this.back = temp;
  83650. };
  83651. // Recursively remove all polygons in `polygons` that are inside this BSP
  83652. // tree.
  83653. Node.prototype.clipPolygons = function (polygons) {
  83654. if (!this.plane)
  83655. return polygons.slice();
  83656. var front = new Array(), back = new Array();
  83657. for (var i = 0; i < polygons.length; i++) {
  83658. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83659. }
  83660. if (this.front) {
  83661. front = this.front.clipPolygons(front);
  83662. }
  83663. if (this.back) {
  83664. back = this.back.clipPolygons(back);
  83665. }
  83666. else {
  83667. back = [];
  83668. }
  83669. return front.concat(back);
  83670. };
  83671. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83672. // `bsp`.
  83673. Node.prototype.clipTo = function (bsp) {
  83674. this.polygons = bsp.clipPolygons(this.polygons);
  83675. if (this.front)
  83676. this.front.clipTo(bsp);
  83677. if (this.back)
  83678. this.back.clipTo(bsp);
  83679. };
  83680. // Return a list of all polygons in this BSP tree.
  83681. Node.prototype.allPolygons = function () {
  83682. var polygons = this.polygons.slice();
  83683. if (this.front)
  83684. polygons = polygons.concat(this.front.allPolygons());
  83685. if (this.back)
  83686. polygons = polygons.concat(this.back.allPolygons());
  83687. return polygons;
  83688. };
  83689. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83690. // new polygons are filtered down to the bottom of the tree and become new
  83691. // nodes there. Each set of polygons is partitioned using the first polygon
  83692. // (no heuristic is used to pick a good split).
  83693. Node.prototype.build = function (polygons) {
  83694. if (!polygons.length)
  83695. return;
  83696. if (!this.plane)
  83697. this.plane = polygons[0].plane.clone();
  83698. var front = new Array(), back = new Array();
  83699. for (var i = 0; i < polygons.length; i++) {
  83700. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83701. }
  83702. if (front.length) {
  83703. if (!this.front)
  83704. this.front = new Node();
  83705. this.front.build(front);
  83706. }
  83707. if (back.length) {
  83708. if (!this.back)
  83709. this.back = new Node();
  83710. this.back.build(back);
  83711. }
  83712. };
  83713. return Node;
  83714. }());
  83715. var CSG = /** @class */ (function () {
  83716. function CSG() {
  83717. this.polygons = new Array();
  83718. }
  83719. // Convert BABYLON.Mesh to BABYLON.CSG
  83720. CSG.FromMesh = function (mesh) {
  83721. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83722. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83723. if (mesh instanceof BABYLON.Mesh) {
  83724. mesh.computeWorldMatrix(true);
  83725. matrix = mesh.getWorldMatrix();
  83726. meshPosition = mesh.position.clone();
  83727. meshRotation = mesh.rotation.clone();
  83728. if (mesh.rotationQuaternion) {
  83729. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83730. }
  83731. meshScaling = mesh.scaling.clone();
  83732. }
  83733. else {
  83734. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83735. }
  83736. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83737. var subMeshes = mesh.subMeshes;
  83738. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83739. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83740. vertices = [];
  83741. for (var j = 0; j < 3; j++) {
  83742. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83743. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83744. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83745. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83746. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83747. vertex = new Vertex(position, normal, uv);
  83748. vertices.push(vertex);
  83749. }
  83750. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83751. // To handle the case of degenerated triangle
  83752. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83753. if (polygon.plane)
  83754. polygons.push(polygon);
  83755. }
  83756. }
  83757. var csg = CSG.FromPolygons(polygons);
  83758. csg.matrix = matrix;
  83759. csg.position = meshPosition;
  83760. csg.rotation = meshRotation;
  83761. csg.scaling = meshScaling;
  83762. csg.rotationQuaternion = meshRotationQuaternion;
  83763. currentCSGMeshId++;
  83764. return csg;
  83765. };
  83766. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83767. CSG.FromPolygons = function (polygons) {
  83768. var csg = new CSG();
  83769. csg.polygons = polygons;
  83770. return csg;
  83771. };
  83772. CSG.prototype.clone = function () {
  83773. var csg = new CSG();
  83774. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83775. csg.copyTransformAttributes(this);
  83776. return csg;
  83777. };
  83778. CSG.prototype.union = function (csg) {
  83779. var a = new Node(this.clone().polygons);
  83780. var b = new Node(csg.clone().polygons);
  83781. a.clipTo(b);
  83782. b.clipTo(a);
  83783. b.invert();
  83784. b.clipTo(a);
  83785. b.invert();
  83786. a.build(b.allPolygons());
  83787. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83788. };
  83789. CSG.prototype.unionInPlace = function (csg) {
  83790. var a = new Node(this.polygons);
  83791. var b = new Node(csg.polygons);
  83792. a.clipTo(b);
  83793. b.clipTo(a);
  83794. b.invert();
  83795. b.clipTo(a);
  83796. b.invert();
  83797. a.build(b.allPolygons());
  83798. this.polygons = a.allPolygons();
  83799. };
  83800. CSG.prototype.subtract = function (csg) {
  83801. var a = new Node(this.clone().polygons);
  83802. var b = new Node(csg.clone().polygons);
  83803. a.invert();
  83804. a.clipTo(b);
  83805. b.clipTo(a);
  83806. b.invert();
  83807. b.clipTo(a);
  83808. b.invert();
  83809. a.build(b.allPolygons());
  83810. a.invert();
  83811. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83812. };
  83813. CSG.prototype.subtractInPlace = function (csg) {
  83814. var a = new Node(this.polygons);
  83815. var b = new Node(csg.polygons);
  83816. a.invert();
  83817. a.clipTo(b);
  83818. b.clipTo(a);
  83819. b.invert();
  83820. b.clipTo(a);
  83821. b.invert();
  83822. a.build(b.allPolygons());
  83823. a.invert();
  83824. this.polygons = a.allPolygons();
  83825. };
  83826. CSG.prototype.intersect = function (csg) {
  83827. var a = new Node(this.clone().polygons);
  83828. var b = new Node(csg.clone().polygons);
  83829. a.invert();
  83830. b.clipTo(a);
  83831. b.invert();
  83832. a.clipTo(b);
  83833. b.clipTo(a);
  83834. a.build(b.allPolygons());
  83835. a.invert();
  83836. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83837. };
  83838. CSG.prototype.intersectInPlace = function (csg) {
  83839. var a = new Node(this.polygons);
  83840. var b = new Node(csg.polygons);
  83841. a.invert();
  83842. b.clipTo(a);
  83843. b.invert();
  83844. a.clipTo(b);
  83845. b.clipTo(a);
  83846. a.build(b.allPolygons());
  83847. a.invert();
  83848. this.polygons = a.allPolygons();
  83849. };
  83850. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83851. // not modified.
  83852. CSG.prototype.inverse = function () {
  83853. var csg = this.clone();
  83854. csg.inverseInPlace();
  83855. return csg;
  83856. };
  83857. CSG.prototype.inverseInPlace = function () {
  83858. this.polygons.map(function (p) { p.flip(); });
  83859. };
  83860. // This is used to keep meshes transformations so they can be restored
  83861. // when we build back a Babylon Mesh
  83862. // NB : All CSG operations are performed in world coordinates
  83863. CSG.prototype.copyTransformAttributes = function (csg) {
  83864. this.matrix = csg.matrix;
  83865. this.position = csg.position;
  83866. this.rotation = csg.rotation;
  83867. this.scaling = csg.scaling;
  83868. this.rotationQuaternion = csg.rotationQuaternion;
  83869. return this;
  83870. };
  83871. // Build Raw mesh from CSG
  83872. // Coordinates here are in world space
  83873. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83874. var matrix = this.matrix.clone();
  83875. matrix.invert();
  83876. 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;
  83877. if (keepSubMeshes) {
  83878. // Sort Polygons, since subMeshes are indices range
  83879. polygons.sort(function (a, b) {
  83880. if (a.shared.meshId === b.shared.meshId) {
  83881. return a.shared.subMeshId - b.shared.subMeshId;
  83882. }
  83883. else {
  83884. return a.shared.meshId - b.shared.meshId;
  83885. }
  83886. });
  83887. }
  83888. for (var i = 0, il = polygons.length; i < il; i++) {
  83889. polygon = polygons[i];
  83890. // Building SubMeshes
  83891. if (!subMesh_dict[polygon.shared.meshId]) {
  83892. subMesh_dict[polygon.shared.meshId] = {};
  83893. }
  83894. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83895. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83896. indexStart: +Infinity,
  83897. indexEnd: -Infinity,
  83898. materialIndex: polygon.shared.materialIndex
  83899. };
  83900. }
  83901. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83902. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83903. polygonIndices[0] = 0;
  83904. polygonIndices[1] = j - 1;
  83905. polygonIndices[2] = j;
  83906. for (var k = 0; k < 3; k++) {
  83907. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83908. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83909. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83910. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83911. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83912. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83913. // Check if 2 points can be merged
  83914. if (!(typeof vertex_idx !== 'undefined' &&
  83915. normals[vertex_idx * 3] === localNormal.x &&
  83916. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83917. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83918. uvs[vertex_idx * 2] === uv.x &&
  83919. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83920. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83921. uvs.push(uv.x, uv.y);
  83922. normals.push(normal.x, normal.y, normal.z);
  83923. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83924. }
  83925. indices.push(vertex_idx);
  83926. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83927. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83928. currentIndex++;
  83929. }
  83930. }
  83931. }
  83932. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83933. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83934. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83935. mesh.setIndices(indices, null);
  83936. if (keepSubMeshes) {
  83937. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83938. var materialIndexOffset = 0, materialMaxIndex;
  83939. mesh.subMeshes = new Array();
  83940. for (var m in subMesh_dict) {
  83941. materialMaxIndex = -1;
  83942. for (var sm in subMesh_dict[m]) {
  83943. subMesh_obj = subMesh_dict[m][sm];
  83944. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83945. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83946. }
  83947. materialIndexOffset += ++materialMaxIndex;
  83948. }
  83949. }
  83950. return mesh;
  83951. };
  83952. // Build Mesh from CSG taking material and transforms into account
  83953. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83954. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83955. mesh.material = material;
  83956. mesh.position.copyFrom(this.position);
  83957. mesh.rotation.copyFrom(this.rotation);
  83958. if (this.rotationQuaternion) {
  83959. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83960. }
  83961. mesh.scaling.copyFrom(this.scaling);
  83962. mesh.computeWorldMatrix(true);
  83963. return mesh;
  83964. };
  83965. return CSG;
  83966. }());
  83967. BABYLON.CSG = CSG;
  83968. })(BABYLON || (BABYLON = {}));
  83969. //# sourceMappingURL=babylon.csg.js.map
  83970. var BABYLON;
  83971. (function (BABYLON) {
  83972. var LensFlare = /** @class */ (function () {
  83973. function LensFlare(size, position, color, imgUrl, system) {
  83974. this.size = size;
  83975. this.position = position;
  83976. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83977. this.color = color || new BABYLON.Color3(1, 1, 1);
  83978. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83979. this._system = system;
  83980. system.lensFlares.push(this);
  83981. }
  83982. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83983. return new LensFlare(size, position, color, imgUrl, system);
  83984. };
  83985. LensFlare.prototype.dispose = function () {
  83986. if (this.texture) {
  83987. this.texture.dispose();
  83988. }
  83989. // Remove from scene
  83990. var index = this._system.lensFlares.indexOf(this);
  83991. this._system.lensFlares.splice(index, 1);
  83992. };
  83993. ;
  83994. return LensFlare;
  83995. }());
  83996. BABYLON.LensFlare = LensFlare;
  83997. })(BABYLON || (BABYLON = {}));
  83998. //# sourceMappingURL=babylon.lensFlare.js.map
  83999. var BABYLON;
  84000. (function (BABYLON) {
  84001. // Adds the parser to the scene parsers.
  84002. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84003. // Lens flares
  84004. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84005. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84006. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84007. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84008. container.lensFlareSystems.push(lf);
  84009. }
  84010. }
  84011. });
  84012. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84013. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84014. if (this.lensFlareSystems[index].name === name) {
  84015. return this.lensFlareSystems[index];
  84016. }
  84017. }
  84018. return null;
  84019. };
  84020. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84021. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84022. if (this.lensFlareSystems[index].id === id) {
  84023. return this.lensFlareSystems[index];
  84024. }
  84025. }
  84026. return null;
  84027. };
  84028. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84029. var index = this.lensFlareSystems.indexOf(toRemove);
  84030. if (index !== -1) {
  84031. this.lensFlareSystems.splice(index, 1);
  84032. }
  84033. return index;
  84034. };
  84035. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84036. this.lensFlareSystems.push(newLensFlareSystem);
  84037. };
  84038. /**
  84039. * Defines the layer scene component responsible to manage any layers
  84040. * in a given scene.
  84041. */
  84042. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84043. /**
  84044. * Creates a new instance of the component for the given scene
  84045. * @param scene Defines the scene to register the component in
  84046. */
  84047. function LensFlareSystemSceneComponent(scene) {
  84048. /**
  84049. * The component name helpfull to identify the component in the list of scene components.
  84050. */
  84051. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84052. this.scene = scene;
  84053. this._lensFlareSystems = scene.lensFlareSystems = new Array();
  84054. }
  84055. /**
  84056. * Registers the component in a given scene
  84057. */
  84058. LensFlareSystemSceneComponent.prototype.register = function () {
  84059. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84060. };
  84061. /**
  84062. * Rebuilds the elements related to this component in case of
  84063. * context lost for instance.
  84064. */
  84065. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84066. // Nothing to do for lens flare
  84067. };
  84068. /**
  84069. * Adds all the element from the container to the scene
  84070. * @param container the container holding the elements
  84071. */
  84072. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84073. var _this = this;
  84074. if (!container.lensFlareSystems) {
  84075. return;
  84076. }
  84077. container.lensFlareSystems.forEach(function (o) {
  84078. _this.scene.addLensFlareSystem(o);
  84079. });
  84080. };
  84081. /**
  84082. * Removes all the elements in the container from the scene
  84083. * @param container contains the elements to remove
  84084. */
  84085. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84086. var _this = this;
  84087. if (!container.lensFlareSystems) {
  84088. return;
  84089. }
  84090. container.lensFlareSystems.forEach(function (o) {
  84091. _this.scene.removeLensFlareSystem(o);
  84092. });
  84093. };
  84094. /**
  84095. * Serializes the component data to the specified json object
  84096. * @param serializationObject The object to serialize to
  84097. */
  84098. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84099. // Lens flares
  84100. serializationObject.lensFlareSystems = [];
  84101. for (var _i = 0, _a = this._lensFlareSystems; _i < _a.length; _i++) {
  84102. var lensFlareSystem = _a[_i];
  84103. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84104. }
  84105. };
  84106. /**
  84107. * Disposes the component and the associated ressources.
  84108. */
  84109. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84110. while (this._lensFlareSystems.length) {
  84111. this._lensFlareSystems[0].dispose();
  84112. }
  84113. };
  84114. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84115. // Lens flares
  84116. if (this.scene.lensFlaresEnabled) {
  84117. BABYLON.Tools.StartPerformanceCounter("Lens flares", this._lensFlareSystems.length > 0);
  84118. for (var _i = 0, _a = this._lensFlareSystems; _i < _a.length; _i++) {
  84119. var lensFlareSystem = _a[_i];
  84120. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84121. lensFlareSystem.render();
  84122. }
  84123. }
  84124. BABYLON.Tools.EndPerformanceCounter("Lens flares", this._lensFlareSystems.length > 0);
  84125. }
  84126. };
  84127. return LensFlareSystemSceneComponent;
  84128. }());
  84129. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84130. })(BABYLON || (BABYLON = {}));
  84131. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84132. var BABYLON;
  84133. (function (BABYLON) {
  84134. var LensFlareSystem = /** @class */ (function () {
  84135. function LensFlareSystem(name, emitter, scene) {
  84136. this.name = name;
  84137. this.lensFlares = new Array();
  84138. this.borderLimit = 300;
  84139. this.viewportBorder = 0;
  84140. this.layerMask = 0x0FFFFFFF;
  84141. this._vertexBuffers = {};
  84142. this._isEnabled = true;
  84143. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84144. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84145. if (!component) {
  84146. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84147. scene._addComponent(component);
  84148. }
  84149. this._emitter = emitter;
  84150. this.id = name;
  84151. scene.lensFlareSystems.push(this);
  84152. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84153. var engine = scene.getEngine();
  84154. // VBO
  84155. var vertices = [];
  84156. vertices.push(1, 1);
  84157. vertices.push(-1, 1);
  84158. vertices.push(-1, -1);
  84159. vertices.push(1, -1);
  84160. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84161. // Indices
  84162. var indices = [];
  84163. indices.push(0);
  84164. indices.push(1);
  84165. indices.push(2);
  84166. indices.push(0);
  84167. indices.push(2);
  84168. indices.push(3);
  84169. this._indexBuffer = engine.createIndexBuffer(indices);
  84170. // Effects
  84171. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84172. }
  84173. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84174. get: function () {
  84175. return this._isEnabled;
  84176. },
  84177. set: function (value) {
  84178. this._isEnabled = value;
  84179. },
  84180. enumerable: true,
  84181. configurable: true
  84182. });
  84183. LensFlareSystem.prototype.getScene = function () {
  84184. return this._scene;
  84185. };
  84186. LensFlareSystem.prototype.getEmitter = function () {
  84187. return this._emitter;
  84188. };
  84189. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84190. this._emitter = newEmitter;
  84191. };
  84192. LensFlareSystem.prototype.getEmitterPosition = function () {
  84193. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84194. };
  84195. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84196. var position = this.getEmitterPosition();
  84197. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84198. this._positionX = position.x;
  84199. this._positionY = position.y;
  84200. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84201. if (this.viewportBorder > 0) {
  84202. globalViewport.x -= this.viewportBorder;
  84203. globalViewport.y -= this.viewportBorder;
  84204. globalViewport.width += this.viewportBorder * 2;
  84205. globalViewport.height += this.viewportBorder * 2;
  84206. position.x += this.viewportBorder;
  84207. position.y += this.viewportBorder;
  84208. this._positionX += this.viewportBorder;
  84209. this._positionY += this.viewportBorder;
  84210. }
  84211. if (position.z > 0) {
  84212. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84213. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84214. return true;
  84215. }
  84216. return true;
  84217. }
  84218. return false;
  84219. };
  84220. LensFlareSystem.prototype._isVisible = function () {
  84221. if (!this._isEnabled || !this._scene.activeCamera) {
  84222. return false;
  84223. }
  84224. var emitterPosition = this.getEmitterPosition();
  84225. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84226. var distance = direction.length();
  84227. direction.normalize();
  84228. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84229. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84230. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84231. };
  84232. LensFlareSystem.prototype.render = function () {
  84233. if (!this._effect.isReady() || !this._scene.activeCamera)
  84234. return false;
  84235. var engine = this._scene.getEngine();
  84236. var viewport = this._scene.activeCamera.viewport;
  84237. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84238. // Position
  84239. if (!this.computeEffectivePosition(globalViewport)) {
  84240. return false;
  84241. }
  84242. // Visibility
  84243. if (!this._isVisible()) {
  84244. return false;
  84245. }
  84246. // Intensity
  84247. var awayX;
  84248. var awayY;
  84249. if (this._positionX < this.borderLimit + globalViewport.x) {
  84250. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84251. }
  84252. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84253. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84254. }
  84255. else {
  84256. awayX = 0;
  84257. }
  84258. if (this._positionY < this.borderLimit + globalViewport.y) {
  84259. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84260. }
  84261. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84262. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84263. }
  84264. else {
  84265. awayY = 0;
  84266. }
  84267. var away = (awayX > awayY) ? awayX : awayY;
  84268. away -= this.viewportBorder;
  84269. if (away > this.borderLimit) {
  84270. away = this.borderLimit;
  84271. }
  84272. var intensity = 1.0 - (away / this.borderLimit);
  84273. if (intensity < 0) {
  84274. return false;
  84275. }
  84276. if (intensity > 1.0) {
  84277. intensity = 1.0;
  84278. }
  84279. if (this.viewportBorder > 0) {
  84280. globalViewport.x += this.viewportBorder;
  84281. globalViewport.y += this.viewportBorder;
  84282. globalViewport.width -= this.viewportBorder * 2;
  84283. globalViewport.height -= this.viewportBorder * 2;
  84284. this._positionX -= this.viewportBorder;
  84285. this._positionY -= this.viewportBorder;
  84286. }
  84287. // Position
  84288. var centerX = globalViewport.x + globalViewport.width / 2;
  84289. var centerY = globalViewport.y + globalViewport.height / 2;
  84290. var distX = centerX - this._positionX;
  84291. var distY = centerY - this._positionY;
  84292. // Effects
  84293. engine.enableEffect(this._effect);
  84294. engine.setState(false);
  84295. engine.setDepthBuffer(false);
  84296. // VBOs
  84297. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84298. // Flares
  84299. for (var index = 0; index < this.lensFlares.length; index++) {
  84300. var flare = this.lensFlares[index];
  84301. engine.setAlphaMode(flare.alphaMode);
  84302. var x = centerX - (distX * flare.position);
  84303. var y = centerY - (distY * flare.position);
  84304. var cw = flare.size;
  84305. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84306. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84307. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84308. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84309. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84310. // Texture
  84311. this._effect.setTexture("textureSampler", flare.texture);
  84312. // Color
  84313. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84314. // Draw order
  84315. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84316. }
  84317. engine.setDepthBuffer(true);
  84318. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84319. return true;
  84320. };
  84321. LensFlareSystem.prototype.dispose = function () {
  84322. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84323. if (vertexBuffer) {
  84324. vertexBuffer.dispose();
  84325. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84326. }
  84327. if (this._indexBuffer) {
  84328. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84329. this._indexBuffer = null;
  84330. }
  84331. while (this.lensFlares.length) {
  84332. this.lensFlares[0].dispose();
  84333. }
  84334. // Remove from scene
  84335. var index = this._scene.lensFlareSystems.indexOf(this);
  84336. this._scene.lensFlareSystems.splice(index, 1);
  84337. };
  84338. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84339. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84340. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84341. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84342. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84343. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84344. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84345. var parsedFlare = parsedLensFlareSystem.flares[index];
  84346. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84347. }
  84348. return lensFlareSystem;
  84349. };
  84350. LensFlareSystem.prototype.serialize = function () {
  84351. var serializationObject = {};
  84352. serializationObject.id = this.id;
  84353. serializationObject.name = this.name;
  84354. serializationObject.emitterId = this.getEmitter().id;
  84355. serializationObject.borderLimit = this.borderLimit;
  84356. serializationObject.flares = [];
  84357. for (var index = 0; index < this.lensFlares.length; index++) {
  84358. var flare = this.lensFlares[index];
  84359. serializationObject.flares.push({
  84360. size: flare.size,
  84361. position: flare.position,
  84362. color: flare.color.asArray(),
  84363. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84364. });
  84365. }
  84366. return serializationObject;
  84367. };
  84368. return LensFlareSystem;
  84369. }());
  84370. BABYLON.LensFlareSystem = LensFlareSystem;
  84371. })(BABYLON || (BABYLON = {}));
  84372. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84373. var BABYLON;
  84374. (function (BABYLON) {
  84375. /**
  84376. * This is a holder class for the physics joint created by the physics plugin.
  84377. * It holds a set of functions to control the underlying joint.
  84378. */
  84379. var PhysicsJoint = /** @class */ (function () {
  84380. function PhysicsJoint(type, jointData) {
  84381. this.type = type;
  84382. this.jointData = jointData;
  84383. jointData.nativeParams = jointData.nativeParams || {};
  84384. }
  84385. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84386. get: function () {
  84387. return this._physicsJoint;
  84388. },
  84389. set: function (newJoint) {
  84390. if (this._physicsJoint) {
  84391. //remove from the wolrd
  84392. }
  84393. this._physicsJoint = newJoint;
  84394. },
  84395. enumerable: true,
  84396. configurable: true
  84397. });
  84398. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84399. set: function (physicsPlugin) {
  84400. this._physicsPlugin = physicsPlugin;
  84401. },
  84402. enumerable: true,
  84403. configurable: true
  84404. });
  84405. /**
  84406. * Execute a function that is physics-plugin specific.
  84407. * @param {Function} func the function that will be executed.
  84408. * It accepts two parameters: the physics world and the physics joint.
  84409. */
  84410. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84411. func(this._physicsPlugin.world, this._physicsJoint);
  84412. };
  84413. //TODO check if the native joints are the same
  84414. //Joint Types
  84415. PhysicsJoint.DistanceJoint = 0;
  84416. PhysicsJoint.HingeJoint = 1;
  84417. PhysicsJoint.BallAndSocketJoint = 2;
  84418. PhysicsJoint.WheelJoint = 3;
  84419. PhysicsJoint.SliderJoint = 4;
  84420. //OIMO
  84421. PhysicsJoint.PrismaticJoint = 5;
  84422. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84423. PhysicsJoint.UniversalJoint = 6;
  84424. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84425. //Cannon
  84426. //Similar to a Ball-Joint. Different in params
  84427. PhysicsJoint.PointToPointJoint = 8;
  84428. //Cannon only at the moment
  84429. PhysicsJoint.SpringJoint = 9;
  84430. PhysicsJoint.LockJoint = 10;
  84431. return PhysicsJoint;
  84432. }());
  84433. BABYLON.PhysicsJoint = PhysicsJoint;
  84434. /**
  84435. * A class representing a physics distance joint.
  84436. */
  84437. var DistanceJoint = /** @class */ (function (_super) {
  84438. __extends(DistanceJoint, _super);
  84439. function DistanceJoint(jointData) {
  84440. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84441. }
  84442. /**
  84443. * Update the predefined distance.
  84444. */
  84445. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84446. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84447. };
  84448. return DistanceJoint;
  84449. }(PhysicsJoint));
  84450. BABYLON.DistanceJoint = DistanceJoint;
  84451. var MotorEnabledJoint = /** @class */ (function (_super) {
  84452. __extends(MotorEnabledJoint, _super);
  84453. function MotorEnabledJoint(type, jointData) {
  84454. return _super.call(this, type, jointData) || this;
  84455. }
  84456. /**
  84457. * Set the motor values.
  84458. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84459. * @param {number} force the force to apply
  84460. * @param {number} maxForce max force for this motor.
  84461. */
  84462. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84463. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84464. };
  84465. /**
  84466. * Set the motor's limits.
  84467. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84468. */
  84469. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84470. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84471. };
  84472. return MotorEnabledJoint;
  84473. }(PhysicsJoint));
  84474. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84475. /**
  84476. * This class represents a single hinge physics joint
  84477. */
  84478. var HingeJoint = /** @class */ (function (_super) {
  84479. __extends(HingeJoint, _super);
  84480. function HingeJoint(jointData) {
  84481. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84482. }
  84483. /**
  84484. * Set the motor values.
  84485. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84486. * @param {number} force the force to apply
  84487. * @param {number} maxForce max force for this motor.
  84488. */
  84489. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84490. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84491. };
  84492. /**
  84493. * Set the motor's limits.
  84494. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84495. */
  84496. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84497. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84498. };
  84499. return HingeJoint;
  84500. }(MotorEnabledJoint));
  84501. BABYLON.HingeJoint = HingeJoint;
  84502. /**
  84503. * This class represents a dual hinge physics joint (same as wheel joint)
  84504. */
  84505. var Hinge2Joint = /** @class */ (function (_super) {
  84506. __extends(Hinge2Joint, _super);
  84507. function Hinge2Joint(jointData) {
  84508. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84509. }
  84510. /**
  84511. * Set the motor values.
  84512. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84513. * @param {number} force the force to apply
  84514. * @param {number} maxForce max force for this motor.
  84515. * @param {motorIndex} the motor's index, 0 or 1.
  84516. */
  84517. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84518. if (motorIndex === void 0) { motorIndex = 0; }
  84519. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84520. };
  84521. /**
  84522. * Set the motor limits.
  84523. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84524. * @param {number} upperLimit the upper limit
  84525. * @param {number} lowerLimit lower limit
  84526. * @param {motorIndex} the motor's index, 0 or 1.
  84527. */
  84528. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84529. if (motorIndex === void 0) { motorIndex = 0; }
  84530. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84531. };
  84532. return Hinge2Joint;
  84533. }(MotorEnabledJoint));
  84534. BABYLON.Hinge2Joint = Hinge2Joint;
  84535. })(BABYLON || (BABYLON = {}));
  84536. //# sourceMappingURL=babylon.physicsJoint.js.map
  84537. var BABYLON;
  84538. (function (BABYLON) {
  84539. var PhysicsImpostor = /** @class */ (function () {
  84540. function PhysicsImpostor(object, type, _options, _scene) {
  84541. if (_options === void 0) { _options = { mass: 0 }; }
  84542. var _this = this;
  84543. this.object = object;
  84544. this.type = type;
  84545. this._options = _options;
  84546. this._scene = _scene;
  84547. this._bodyUpdateRequired = false;
  84548. this._onBeforePhysicsStepCallbacks = new Array();
  84549. this._onAfterPhysicsStepCallbacks = new Array();
  84550. this._onPhysicsCollideCallbacks = [];
  84551. this._deltaPosition = BABYLON.Vector3.Zero();
  84552. this._isDisposed = false;
  84553. //temp variables for parent rotation calculations
  84554. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84555. this._tmpQuat = new BABYLON.Quaternion();
  84556. this._tmpQuat2 = new BABYLON.Quaternion();
  84557. /**
  84558. * this function is executed by the physics engine.
  84559. */
  84560. this.beforeStep = function () {
  84561. if (!_this._physicsEngine) {
  84562. return;
  84563. }
  84564. _this.object.translate(_this._deltaPosition, -1);
  84565. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84566. _this.object.computeWorldMatrix(false);
  84567. if (_this.object.parent && _this.object.rotationQuaternion) {
  84568. _this.getParentsRotation();
  84569. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84570. }
  84571. else {
  84572. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84573. }
  84574. if (!_this._options.disableBidirectionalTransformation) {
  84575. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84576. }
  84577. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84578. func(_this);
  84579. });
  84580. };
  84581. /**
  84582. * this function is executed by the physics engine.
  84583. */
  84584. this.afterStep = function () {
  84585. if (!_this._physicsEngine) {
  84586. return;
  84587. }
  84588. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84589. func(_this);
  84590. });
  84591. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84592. // object has now its world rotation. needs to be converted to local.
  84593. if (_this.object.parent && _this.object.rotationQuaternion) {
  84594. _this.getParentsRotation();
  84595. _this._tmpQuat.conjugateInPlace();
  84596. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84597. }
  84598. // take the position set and make it the absolute position of this object.
  84599. _this.object.setAbsolutePosition(_this.object.position);
  84600. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84601. _this.object.translate(_this._deltaPosition, 1);
  84602. };
  84603. /**
  84604. * Legacy collision detection event support
  84605. */
  84606. this.onCollideEvent = null;
  84607. //event and body object due to cannon's event-based architecture.
  84608. this.onCollide = function (e) {
  84609. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84610. return;
  84611. }
  84612. if (!_this._physicsEngine) {
  84613. return;
  84614. }
  84615. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84616. if (otherImpostor) {
  84617. // Legacy collision detection event support
  84618. if (_this.onCollideEvent) {
  84619. _this.onCollideEvent(_this, otherImpostor);
  84620. }
  84621. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84622. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84623. }).forEach(function (obj) {
  84624. obj.callback(_this, otherImpostor);
  84625. });
  84626. }
  84627. };
  84628. //sanity check!
  84629. if (!this.object) {
  84630. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84631. return;
  84632. }
  84633. //legacy support for old syntax.
  84634. if (!this._scene && object.getScene) {
  84635. this._scene = object.getScene();
  84636. }
  84637. if (!this._scene) {
  84638. return;
  84639. }
  84640. this._physicsEngine = this._scene.getPhysicsEngine();
  84641. if (!this._physicsEngine) {
  84642. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84643. }
  84644. else {
  84645. //set the object's quaternion, if not set
  84646. if (!this.object.rotationQuaternion) {
  84647. if (this.object.rotation) {
  84648. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84649. }
  84650. else {
  84651. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84652. }
  84653. }
  84654. //default options params
  84655. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84656. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84657. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84658. this._joints = [];
  84659. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84660. if (!this.object.parent || this._options.ignoreParent) {
  84661. this._init();
  84662. }
  84663. else if (this.object.parent.physicsImpostor) {
  84664. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84665. }
  84666. }
  84667. }
  84668. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84669. get: function () {
  84670. return this._isDisposed;
  84671. },
  84672. enumerable: true,
  84673. configurable: true
  84674. });
  84675. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84676. get: function () {
  84677. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84678. },
  84679. set: function (value) {
  84680. this.setMass(value);
  84681. },
  84682. enumerable: true,
  84683. configurable: true
  84684. });
  84685. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84686. get: function () {
  84687. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84688. },
  84689. set: function (value) {
  84690. if (!this._physicsEngine) {
  84691. return;
  84692. }
  84693. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84694. },
  84695. enumerable: true,
  84696. configurable: true
  84697. });
  84698. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84699. get: function () {
  84700. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84701. },
  84702. set: function (value) {
  84703. if (!this._physicsEngine) {
  84704. return;
  84705. }
  84706. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84707. },
  84708. enumerable: true,
  84709. configurable: true
  84710. });
  84711. /**
  84712. * This function will completly initialize this impostor.
  84713. * It will create a new body - but only if this mesh has no parent.
  84714. * If it has, this impostor will not be used other than to define the impostor
  84715. * of the child mesh.
  84716. */
  84717. PhysicsImpostor.prototype._init = function () {
  84718. if (!this._physicsEngine) {
  84719. return;
  84720. }
  84721. this._physicsEngine.removeImpostor(this);
  84722. this.physicsBody = null;
  84723. this._parent = this._parent || this._getPhysicsParent();
  84724. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84725. this._physicsEngine.addImpostor(this);
  84726. }
  84727. };
  84728. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84729. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84730. var parentMesh = this.object.parent;
  84731. return parentMesh.physicsImpostor;
  84732. }
  84733. return null;
  84734. };
  84735. /**
  84736. * Should a new body be generated.
  84737. */
  84738. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84739. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84740. };
  84741. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84742. this.forceUpdate();
  84743. };
  84744. /**
  84745. * Force a regeneration of this or the parent's impostor's body.
  84746. * Use under cautious - This will remove all joints already implemented.
  84747. */
  84748. PhysicsImpostor.prototype.forceUpdate = function () {
  84749. this._init();
  84750. if (this.parent && !this._options.ignoreParent) {
  84751. this.parent.forceUpdate();
  84752. }
  84753. };
  84754. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84755. /*public get mesh(): AbstractMesh {
  84756. return this._mesh;
  84757. }*/
  84758. /**
  84759. * Gets the body that holds this impostor. Either its own, or its parent.
  84760. */
  84761. get: function () {
  84762. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84763. },
  84764. /**
  84765. * Set the physics body. Used mainly by the physics engine/plugin
  84766. */
  84767. set: function (physicsBody) {
  84768. if (this._physicsBody && this._physicsEngine) {
  84769. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84770. }
  84771. this._physicsBody = physicsBody;
  84772. this.resetUpdateFlags();
  84773. },
  84774. enumerable: true,
  84775. configurable: true
  84776. });
  84777. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84778. get: function () {
  84779. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84780. },
  84781. set: function (value) {
  84782. this._parent = value;
  84783. },
  84784. enumerable: true,
  84785. configurable: true
  84786. });
  84787. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84788. this._bodyUpdateRequired = false;
  84789. };
  84790. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84791. if (this.object.getBoundingInfo) {
  84792. var q = this.object.rotationQuaternion;
  84793. //reset rotation
  84794. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84795. //calculate the world matrix with no rotation
  84796. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84797. var boundingInfo = this.object.getBoundingInfo();
  84798. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84799. //bring back the rotation
  84800. this.object.rotationQuaternion = q;
  84801. //calculate the world matrix with the new rotation
  84802. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84803. return size;
  84804. }
  84805. else {
  84806. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84807. }
  84808. };
  84809. PhysicsImpostor.prototype.getObjectCenter = function () {
  84810. if (this.object.getBoundingInfo) {
  84811. var boundingInfo = this.object.getBoundingInfo();
  84812. return boundingInfo.boundingBox.centerWorld;
  84813. }
  84814. else {
  84815. return this.object.position;
  84816. }
  84817. };
  84818. /**
  84819. * Get a specific parametes from the options parameter.
  84820. */
  84821. PhysicsImpostor.prototype.getParam = function (paramName) {
  84822. return this._options[paramName];
  84823. };
  84824. /**
  84825. * Sets a specific parameter in the options given to the physics plugin
  84826. */
  84827. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84828. this._options[paramName] = value;
  84829. this._bodyUpdateRequired = true;
  84830. };
  84831. /**
  84832. * Specifically change the body's mass option. Won't recreate the physics body object
  84833. */
  84834. PhysicsImpostor.prototype.setMass = function (mass) {
  84835. if (this.getParam("mass") !== mass) {
  84836. this.setParam("mass", mass);
  84837. }
  84838. if (this._physicsEngine) {
  84839. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84840. }
  84841. };
  84842. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84843. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84844. };
  84845. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84846. if (this._physicsEngine) {
  84847. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84848. }
  84849. };
  84850. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84851. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84852. };
  84853. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84854. if (this._physicsEngine) {
  84855. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84856. }
  84857. };
  84858. /**
  84859. * Execute a function with the physics plugin native code.
  84860. * Provide a function the will have two variables - the world object and the physics body object.
  84861. */
  84862. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84863. if (this._physicsEngine) {
  84864. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84865. }
  84866. };
  84867. /**
  84868. * Register a function that will be executed before the physics world is stepping forward.
  84869. */
  84870. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84871. this._onBeforePhysicsStepCallbacks.push(func);
  84872. };
  84873. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84874. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84875. if (index > -1) {
  84876. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84877. }
  84878. else {
  84879. BABYLON.Tools.Warn("Function to remove was not found");
  84880. }
  84881. };
  84882. /**
  84883. * Register a function that will be executed after the physics step
  84884. */
  84885. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84886. this._onAfterPhysicsStepCallbacks.push(func);
  84887. };
  84888. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84889. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84890. if (index > -1) {
  84891. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84892. }
  84893. else {
  84894. BABYLON.Tools.Warn("Function to remove was not found");
  84895. }
  84896. };
  84897. /**
  84898. * register a function that will be executed when this impostor collides against a different body.
  84899. */
  84900. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84901. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84902. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84903. };
  84904. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84905. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84906. var index = -1;
  84907. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84908. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84909. // chcek the arrays match
  84910. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84911. return collidedAgainstList.indexOf(impostor) > -1;
  84912. });
  84913. if (sameList) {
  84914. index = idx;
  84915. }
  84916. return sameList;
  84917. }
  84918. return false;
  84919. });
  84920. if (found) {
  84921. this._onPhysicsCollideCallbacks.splice(index, 1);
  84922. }
  84923. else {
  84924. BABYLON.Tools.Warn("Function to remove was not found");
  84925. }
  84926. };
  84927. PhysicsImpostor.prototype.getParentsRotation = function () {
  84928. var parent = this.object.parent;
  84929. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84930. while (parent) {
  84931. if (parent.rotationQuaternion) {
  84932. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84933. }
  84934. else {
  84935. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84936. }
  84937. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84938. parent = parent.parent;
  84939. }
  84940. return this._tmpQuat;
  84941. };
  84942. /**
  84943. * Apply a force
  84944. */
  84945. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84946. if (this._physicsEngine) {
  84947. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84948. }
  84949. return this;
  84950. };
  84951. /**
  84952. * Apply an impulse
  84953. */
  84954. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84955. if (this._physicsEngine) {
  84956. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84957. }
  84958. return this;
  84959. };
  84960. /**
  84961. * A help function to create a joint.
  84962. */
  84963. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84964. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84965. this.addJoint(otherImpostor, joint);
  84966. return this;
  84967. };
  84968. /**
  84969. * Add a joint to this impostor with a different impostor.
  84970. */
  84971. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84972. this._joints.push({
  84973. otherImpostor: otherImpostor,
  84974. joint: joint
  84975. });
  84976. if (this._physicsEngine) {
  84977. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84978. }
  84979. return this;
  84980. };
  84981. /**
  84982. * Will keep this body still, in a sleep mode.
  84983. */
  84984. PhysicsImpostor.prototype.sleep = function () {
  84985. if (this._physicsEngine) {
  84986. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84987. }
  84988. return this;
  84989. };
  84990. /**
  84991. * Wake the body up.
  84992. */
  84993. PhysicsImpostor.prototype.wakeUp = function () {
  84994. if (this._physicsEngine) {
  84995. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84996. }
  84997. return this;
  84998. };
  84999. PhysicsImpostor.prototype.clone = function (newObject) {
  85000. if (!newObject)
  85001. return null;
  85002. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85003. };
  85004. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85005. var _this = this;
  85006. //no dispose if no physics engine is available.
  85007. if (!this._physicsEngine) {
  85008. return;
  85009. }
  85010. this._joints.forEach(function (j) {
  85011. if (_this._physicsEngine) {
  85012. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85013. }
  85014. });
  85015. //dispose the physics body
  85016. this._physicsEngine.removeImpostor(this);
  85017. if (this.parent) {
  85018. this.parent.forceUpdate();
  85019. }
  85020. else {
  85021. /*this._object.getChildMeshes().forEach(function(mesh) {
  85022. if (mesh.physicsImpostor) {
  85023. if (disposeChildren) {
  85024. mesh.physicsImpostor.dispose();
  85025. mesh.physicsImpostor = null;
  85026. }
  85027. }
  85028. })*/
  85029. }
  85030. this._isDisposed = true;
  85031. };
  85032. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85033. this._deltaPosition.copyFrom(position);
  85034. };
  85035. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85036. if (!this._deltaRotation) {
  85037. this._deltaRotation = new BABYLON.Quaternion();
  85038. }
  85039. this._deltaRotation.copyFrom(rotation);
  85040. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85041. };
  85042. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85043. if (this._physicsEngine) {
  85044. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85045. }
  85046. return this;
  85047. };
  85048. PhysicsImpostor.prototype.getRadius = function () {
  85049. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85050. };
  85051. /**
  85052. * Sync a bone with this impostor
  85053. * @param bone The bone to sync to the impostor.
  85054. * @param boneMesh The mesh that the bone is influencing.
  85055. * @param jointPivot The pivot of the joint / bone in local space.
  85056. * @param distToJoint Optional distance from the impostor to the joint.
  85057. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85058. */
  85059. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85060. var tempVec = PhysicsImpostor._tmpVecs[0];
  85061. var mesh = this.object;
  85062. if (mesh.rotationQuaternion) {
  85063. if (adjustRotation) {
  85064. var tempQuat = PhysicsImpostor._tmpQuat;
  85065. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85066. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85067. }
  85068. else {
  85069. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85070. }
  85071. }
  85072. tempVec.x = 0;
  85073. tempVec.y = 0;
  85074. tempVec.z = 0;
  85075. if (jointPivot) {
  85076. tempVec.x = jointPivot.x;
  85077. tempVec.y = jointPivot.y;
  85078. tempVec.z = jointPivot.z;
  85079. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85080. if (distToJoint === undefined || distToJoint === null) {
  85081. distToJoint = jointPivot.length();
  85082. }
  85083. tempVec.x *= distToJoint;
  85084. tempVec.y *= distToJoint;
  85085. tempVec.z *= distToJoint;
  85086. }
  85087. if (bone.getParent()) {
  85088. tempVec.addInPlace(mesh.getAbsolutePosition());
  85089. bone.setAbsolutePosition(tempVec, boneMesh);
  85090. }
  85091. else {
  85092. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85093. boneMesh.position.x -= tempVec.x;
  85094. boneMesh.position.y -= tempVec.y;
  85095. boneMesh.position.z -= tempVec.z;
  85096. }
  85097. };
  85098. /**
  85099. * Sync impostor to a bone
  85100. * @param bone The bone that the impostor will be synced to.
  85101. * @param boneMesh The mesh that the bone is influencing.
  85102. * @param jointPivot The pivot of the joint / bone in local space.
  85103. * @param distToJoint Optional distance from the impostor to the joint.
  85104. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85105. * @param boneAxis Optional vector3 axis the bone is aligned with
  85106. */
  85107. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85108. var mesh = this.object;
  85109. if (mesh.rotationQuaternion) {
  85110. if (adjustRotation) {
  85111. var tempQuat = PhysicsImpostor._tmpQuat;
  85112. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85113. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85114. }
  85115. else {
  85116. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85117. }
  85118. }
  85119. var pos = PhysicsImpostor._tmpVecs[0];
  85120. var boneDir = PhysicsImpostor._tmpVecs[1];
  85121. if (!boneAxis) {
  85122. boneAxis = PhysicsImpostor._tmpVecs[2];
  85123. boneAxis.x = 0;
  85124. boneAxis.y = 1;
  85125. boneAxis.z = 0;
  85126. }
  85127. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85128. bone.getAbsolutePositionToRef(boneMesh, pos);
  85129. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85130. distToJoint = jointPivot.length();
  85131. }
  85132. if (distToJoint !== undefined && distToJoint !== null) {
  85133. pos.x += boneDir.x * distToJoint;
  85134. pos.y += boneDir.y * distToJoint;
  85135. pos.z += boneDir.z * distToJoint;
  85136. }
  85137. mesh.setAbsolutePosition(pos);
  85138. };
  85139. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85140. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85141. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85142. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85143. //Impostor types
  85144. PhysicsImpostor.NoImpostor = 0;
  85145. PhysicsImpostor.SphereImpostor = 1;
  85146. PhysicsImpostor.BoxImpostor = 2;
  85147. PhysicsImpostor.PlaneImpostor = 3;
  85148. PhysicsImpostor.MeshImpostor = 4;
  85149. PhysicsImpostor.CylinderImpostor = 7;
  85150. PhysicsImpostor.ParticleImpostor = 8;
  85151. PhysicsImpostor.HeightmapImpostor = 9;
  85152. return PhysicsImpostor;
  85153. }());
  85154. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85155. })(BABYLON || (BABYLON = {}));
  85156. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85157. var BABYLON;
  85158. (function (BABYLON) {
  85159. var PhysicsEngine = /** @class */ (function () {
  85160. function PhysicsEngine(gravity, _physicsPlugin) {
  85161. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85162. this._physicsPlugin = _physicsPlugin;
  85163. //new methods and parameters
  85164. this._impostors = [];
  85165. this._joints = [];
  85166. if (!this._physicsPlugin.isSupported()) {
  85167. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85168. + "Please make sure it is included.");
  85169. }
  85170. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85171. this.setGravity(gravity);
  85172. this.setTimeStep();
  85173. }
  85174. PhysicsEngine.prototype.setGravity = function (gravity) {
  85175. this.gravity = gravity;
  85176. this._physicsPlugin.setGravity(this.gravity);
  85177. };
  85178. /**
  85179. * Set the time step of the physics engine.
  85180. * default is 1/60.
  85181. * To slow it down, enter 1/600 for example.
  85182. * To speed it up, 1/30
  85183. * @param {number} newTimeStep the new timestep to apply to this world.
  85184. */
  85185. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85186. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85187. this._physicsPlugin.setTimeStep(newTimeStep);
  85188. };
  85189. /**
  85190. * Get the time step of the physics engine.
  85191. */
  85192. PhysicsEngine.prototype.getTimeStep = function () {
  85193. return this._physicsPlugin.getTimeStep();
  85194. };
  85195. PhysicsEngine.prototype.dispose = function () {
  85196. this._impostors.forEach(function (impostor) {
  85197. impostor.dispose();
  85198. });
  85199. this._physicsPlugin.dispose();
  85200. };
  85201. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85202. return this._physicsPlugin.name;
  85203. };
  85204. /**
  85205. * Adding a new impostor for the impostor tracking.
  85206. * This will be done by the impostor itself.
  85207. * @param {PhysicsImpostor} impostor the impostor to add
  85208. */
  85209. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85210. impostor.uniqueId = this._impostors.push(impostor);
  85211. //if no parent, generate the body
  85212. if (!impostor.parent) {
  85213. this._physicsPlugin.generatePhysicsBody(impostor);
  85214. }
  85215. };
  85216. /**
  85217. * Remove an impostor from the engine.
  85218. * This impostor and its mesh will not longer be updated by the physics engine.
  85219. * @param {PhysicsImpostor} impostor the impostor to remove
  85220. */
  85221. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85222. var index = this._impostors.indexOf(impostor);
  85223. if (index > -1) {
  85224. var removed = this._impostors.splice(index, 1);
  85225. //Is it needed?
  85226. if (removed.length) {
  85227. //this will also remove it from the world.
  85228. removed[0].physicsBody = null;
  85229. }
  85230. }
  85231. };
  85232. /**
  85233. * Add a joint to the physics engine
  85234. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85235. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85236. * @param {PhysicsJoint} the joint that will connect both impostors.
  85237. */
  85238. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85239. var impostorJoint = {
  85240. mainImpostor: mainImpostor,
  85241. connectedImpostor: connectedImpostor,
  85242. joint: joint
  85243. };
  85244. joint.physicsPlugin = this._physicsPlugin;
  85245. this._joints.push(impostorJoint);
  85246. this._physicsPlugin.generateJoint(impostorJoint);
  85247. };
  85248. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85249. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85250. return (impostorJoint.connectedImpostor === connectedImpostor
  85251. && impostorJoint.joint === joint
  85252. && impostorJoint.mainImpostor === mainImpostor);
  85253. });
  85254. if (matchingJoints.length) {
  85255. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85256. //TODO remove it from the list as well
  85257. }
  85258. };
  85259. /**
  85260. * Called by the scene. no need to call it.
  85261. */
  85262. PhysicsEngine.prototype._step = function (delta) {
  85263. var _this = this;
  85264. //check if any mesh has no body / requires an update
  85265. this._impostors.forEach(function (impostor) {
  85266. if (impostor.isBodyInitRequired()) {
  85267. _this._physicsPlugin.generatePhysicsBody(impostor);
  85268. }
  85269. });
  85270. if (delta > 0.1) {
  85271. delta = 0.1;
  85272. }
  85273. else if (delta <= 0) {
  85274. delta = 1.0 / 60.0;
  85275. }
  85276. this._physicsPlugin.executeStep(delta, this._impostors);
  85277. };
  85278. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85279. return this._physicsPlugin;
  85280. };
  85281. PhysicsEngine.prototype.getImpostors = function () {
  85282. return this._impostors;
  85283. };
  85284. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85285. for (var i = 0; i < this._impostors.length; ++i) {
  85286. if (this._impostors[i].object === object) {
  85287. return this._impostors[i];
  85288. }
  85289. }
  85290. return null;
  85291. };
  85292. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85293. for (var i = 0; i < this._impostors.length; ++i) {
  85294. if (this._impostors[i].physicsBody === body) {
  85295. return this._impostors[i];
  85296. }
  85297. }
  85298. return null;
  85299. };
  85300. // Statics
  85301. PhysicsEngine.Epsilon = 0.001;
  85302. return PhysicsEngine;
  85303. }());
  85304. BABYLON.PhysicsEngine = PhysicsEngine;
  85305. })(BABYLON || (BABYLON = {}));
  85306. //# sourceMappingURL=babylon.physicsEngine.js.map
  85307. var BABYLON;
  85308. (function (BABYLON) {
  85309. var PhysicsHelper = /** @class */ (function () {
  85310. function PhysicsHelper(scene) {
  85311. this._scene = scene;
  85312. this._physicsEngine = this._scene.getPhysicsEngine();
  85313. if (!this._physicsEngine) {
  85314. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85315. }
  85316. }
  85317. /**
  85318. * @param {Vector3} origin the origin of the explosion
  85319. * @param {number} radius the explosion radius
  85320. * @param {number} strength the explosion strength
  85321. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85322. */
  85323. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85324. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85325. if (!this._physicsEngine) {
  85326. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85327. return null;
  85328. }
  85329. var impostors = this._physicsEngine.getImpostors();
  85330. if (impostors.length === 0) {
  85331. return null;
  85332. }
  85333. var event = new PhysicsRadialExplosionEvent(this._scene);
  85334. impostors.forEach(function (impostor) {
  85335. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85336. if (!impostorForceAndContactPoint) {
  85337. return;
  85338. }
  85339. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85340. });
  85341. event.dispose(false);
  85342. return event;
  85343. };
  85344. /**
  85345. * @param {Vector3} origin the origin of the explosion
  85346. * @param {number} radius the explosion radius
  85347. * @param {number} strength the explosion strength
  85348. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85349. */
  85350. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85351. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85352. if (!this._physicsEngine) {
  85353. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85354. return null;
  85355. }
  85356. var impostors = this._physicsEngine.getImpostors();
  85357. if (impostors.length === 0) {
  85358. return null;
  85359. }
  85360. var event = new PhysicsRadialExplosionEvent(this._scene);
  85361. impostors.forEach(function (impostor) {
  85362. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85363. if (!impostorForceAndContactPoint) {
  85364. return;
  85365. }
  85366. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85367. });
  85368. event.dispose(false);
  85369. return event;
  85370. };
  85371. /**
  85372. * @param {Vector3} origin the origin of the explosion
  85373. * @param {number} radius the explosion radius
  85374. * @param {number} strength the explosion strength
  85375. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85376. */
  85377. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85378. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85379. if (!this._physicsEngine) {
  85380. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85381. return null;
  85382. }
  85383. var impostors = this._physicsEngine.getImpostors();
  85384. if (impostors.length === 0) {
  85385. return null;
  85386. }
  85387. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85388. event.dispose(false);
  85389. return event;
  85390. };
  85391. /**
  85392. * @param {Vector3} origin the origin of the updraft
  85393. * @param {number} radius the radius of the updraft
  85394. * @param {number} strength the strength of the updraft
  85395. * @param {number} height the height of the updraft
  85396. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85397. */
  85398. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85399. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85400. if (!this._physicsEngine) {
  85401. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85402. return null;
  85403. }
  85404. if (this._physicsEngine.getImpostors().length === 0) {
  85405. return null;
  85406. }
  85407. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85408. event.dispose(false);
  85409. return event;
  85410. };
  85411. /**
  85412. * @param {Vector3} origin the of the vortex
  85413. * @param {number} radius the radius of the vortex
  85414. * @param {number} strength the strength of the vortex
  85415. * @param {number} height the height of the vortex
  85416. */
  85417. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85418. if (!this._physicsEngine) {
  85419. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85420. return null;
  85421. }
  85422. if (this._physicsEngine.getImpostors().length === 0) {
  85423. return null;
  85424. }
  85425. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85426. event.dispose(false);
  85427. return event;
  85428. };
  85429. return PhysicsHelper;
  85430. }());
  85431. BABYLON.PhysicsHelper = PhysicsHelper;
  85432. /***** Radial explosion *****/
  85433. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85434. function PhysicsRadialExplosionEvent(scene) {
  85435. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85436. this._rays = [];
  85437. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85438. this._scene = scene;
  85439. }
  85440. /**
  85441. * Returns the data related to the radial explosion event (sphere & rays).
  85442. * @returns {PhysicsRadialExplosionEventData}
  85443. */
  85444. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85445. this._dataFetched = true;
  85446. return {
  85447. sphere: this._sphere,
  85448. rays: this._rays,
  85449. };
  85450. };
  85451. /**
  85452. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85453. * @param impostor
  85454. * @param {Vector3} origin the origin of the explosion
  85455. * @param {number} radius the explosion radius
  85456. * @param {number} strength the explosion strength
  85457. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85458. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85459. */
  85460. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85461. if (impostor.mass === 0) {
  85462. return null;
  85463. }
  85464. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85465. return null;
  85466. }
  85467. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85468. return null;
  85469. }
  85470. var impostorObjectCenter = impostor.getObjectCenter();
  85471. var direction = impostorObjectCenter.subtract(origin);
  85472. var ray = new BABYLON.Ray(origin, direction, radius);
  85473. this._rays.push(ray);
  85474. var hit = ray.intersectsMesh(impostor.object);
  85475. var contactPoint = hit.pickedPoint;
  85476. if (!contactPoint) {
  85477. return null;
  85478. }
  85479. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85480. if (distanceFromOrigin > radius) {
  85481. return null;
  85482. }
  85483. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85484. ? strength
  85485. : strength * (1 - (distanceFromOrigin / radius));
  85486. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85487. return { force: force, contactPoint: contactPoint };
  85488. };
  85489. /**
  85490. * Disposes the sphere.
  85491. * @param {bolean} force
  85492. */
  85493. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85494. var _this = this;
  85495. if (force === void 0) { force = true; }
  85496. if (force) {
  85497. this._sphere.dispose();
  85498. }
  85499. else {
  85500. setTimeout(function () {
  85501. if (!_this._dataFetched) {
  85502. _this._sphere.dispose();
  85503. }
  85504. }, 0);
  85505. }
  85506. };
  85507. /*** Helpers ***/
  85508. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85509. if (!this._sphere) {
  85510. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85511. this._sphere.isVisible = false;
  85512. }
  85513. };
  85514. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85515. var impostorObject = impostor.object;
  85516. this._prepareSphere();
  85517. this._sphere.position = origin;
  85518. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85519. this._sphere._updateBoundingInfo();
  85520. this._sphere.computeWorldMatrix(true);
  85521. return this._sphere.intersectsMesh(impostorObject, true);
  85522. };
  85523. return PhysicsRadialExplosionEvent;
  85524. }());
  85525. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85526. /***** Gravitational Field *****/
  85527. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85528. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85529. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85530. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85531. this._physicsHelper = physicsHelper;
  85532. this._scene = scene;
  85533. this._origin = origin;
  85534. this._radius = radius;
  85535. this._strength = strength;
  85536. this._falloff = falloff;
  85537. this._tickCallback = this._tick.bind(this);
  85538. }
  85539. /**
  85540. * Returns the data related to the gravitational field event (sphere).
  85541. * @returns {PhysicsGravitationalFieldEventData}
  85542. */
  85543. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85544. this._dataFetched = true;
  85545. return {
  85546. sphere: this._sphere,
  85547. };
  85548. };
  85549. /**
  85550. * Enables the gravitational field.
  85551. */
  85552. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85553. this._tickCallback.call(this);
  85554. this._scene.registerBeforeRender(this._tickCallback);
  85555. };
  85556. /**
  85557. * Disables the gravitational field.
  85558. */
  85559. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85560. this._scene.unregisterBeforeRender(this._tickCallback);
  85561. };
  85562. /**
  85563. * Disposes the sphere.
  85564. * @param {bolean} force
  85565. */
  85566. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85567. var _this = this;
  85568. if (force === void 0) { force = true; }
  85569. if (force) {
  85570. this._sphere.dispose();
  85571. }
  85572. else {
  85573. setTimeout(function () {
  85574. if (!_this._dataFetched) {
  85575. _this._sphere.dispose();
  85576. }
  85577. }, 0);
  85578. }
  85579. };
  85580. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85581. // Since the params won't change, we fetch the event only once
  85582. if (this._sphere) {
  85583. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85584. }
  85585. else {
  85586. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85587. if (radialExplosionEvent) {
  85588. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85589. }
  85590. }
  85591. };
  85592. return PhysicsGravitationalFieldEvent;
  85593. }());
  85594. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85595. /***** Updraft *****/
  85596. var PhysicsUpdraftEvent = /** @class */ (function () {
  85597. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85598. this._scene = _scene;
  85599. this._origin = _origin;
  85600. this._radius = _radius;
  85601. this._strength = _strength;
  85602. this._height = _height;
  85603. this._updraftMode = _updraftMode;
  85604. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85605. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85606. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85607. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85608. this._physicsEngine = this._scene.getPhysicsEngine();
  85609. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85610. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85611. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85612. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85613. }
  85614. this._tickCallback = this._tick.bind(this);
  85615. }
  85616. /**
  85617. * Returns the data related to the updraft event (cylinder).
  85618. * @returns {PhysicsUpdraftEventData}
  85619. */
  85620. PhysicsUpdraftEvent.prototype.getData = function () {
  85621. this._dataFetched = true;
  85622. return {
  85623. cylinder: this._cylinder,
  85624. };
  85625. };
  85626. /**
  85627. * Enables the updraft.
  85628. */
  85629. PhysicsUpdraftEvent.prototype.enable = function () {
  85630. this._tickCallback.call(this);
  85631. this._scene.registerBeforeRender(this._tickCallback);
  85632. };
  85633. /**
  85634. * Disables the cortex.
  85635. */
  85636. PhysicsUpdraftEvent.prototype.disable = function () {
  85637. this._scene.unregisterBeforeRender(this._tickCallback);
  85638. };
  85639. /**
  85640. * Disposes the sphere.
  85641. * @param {bolean} force
  85642. */
  85643. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85644. var _this = this;
  85645. if (force === void 0) { force = true; }
  85646. if (force) {
  85647. this._cylinder.dispose();
  85648. }
  85649. else {
  85650. setTimeout(function () {
  85651. if (!_this._dataFetched) {
  85652. _this._cylinder.dispose();
  85653. }
  85654. }, 0);
  85655. }
  85656. };
  85657. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85658. if (impostor.mass === 0) {
  85659. return null;
  85660. }
  85661. if (!this._intersectsWithCylinder(impostor)) {
  85662. return null;
  85663. }
  85664. var impostorObjectCenter = impostor.getObjectCenter();
  85665. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85666. var direction = this._originDirection;
  85667. }
  85668. else {
  85669. var direction = impostorObjectCenter.subtract(this._originTop);
  85670. }
  85671. var multiplier = this._strength * -1;
  85672. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85673. return { force: force, contactPoint: impostorObjectCenter };
  85674. };
  85675. PhysicsUpdraftEvent.prototype._tick = function () {
  85676. var _this = this;
  85677. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85678. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85679. if (!impostorForceAndContactPoint) {
  85680. return;
  85681. }
  85682. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85683. });
  85684. };
  85685. /*** Helpers ***/
  85686. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85687. if (!this._cylinder) {
  85688. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85689. height: this._height,
  85690. diameter: this._radius * 2,
  85691. }, this._scene);
  85692. this._cylinder.isVisible = false;
  85693. }
  85694. };
  85695. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85696. var impostorObject = impostor.object;
  85697. this._prepareCylinder();
  85698. this._cylinder.position = this._cylinderPosition;
  85699. return this._cylinder.intersectsMesh(impostorObject, true);
  85700. };
  85701. return PhysicsUpdraftEvent;
  85702. }());
  85703. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85704. /***** Vortex *****/
  85705. var PhysicsVortexEvent = /** @class */ (function () {
  85706. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85707. this._scene = _scene;
  85708. this._origin = _origin;
  85709. this._radius = _radius;
  85710. this._strength = _strength;
  85711. this._height = _height;
  85712. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85713. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85714. this._updraftMultiplier = 0.02;
  85715. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85716. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85717. this._physicsEngine = this._scene.getPhysicsEngine();
  85718. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85719. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85720. this._tickCallback = this._tick.bind(this);
  85721. }
  85722. /**
  85723. * Returns the data related to the vortex event (cylinder).
  85724. * @returns {PhysicsVortexEventData}
  85725. */
  85726. PhysicsVortexEvent.prototype.getData = function () {
  85727. this._dataFetched = true;
  85728. return {
  85729. cylinder: this._cylinder,
  85730. };
  85731. };
  85732. /**
  85733. * Enables the vortex.
  85734. */
  85735. PhysicsVortexEvent.prototype.enable = function () {
  85736. this._tickCallback.call(this);
  85737. this._scene.registerBeforeRender(this._tickCallback);
  85738. };
  85739. /**
  85740. * Disables the cortex.
  85741. */
  85742. PhysicsVortexEvent.prototype.disable = function () {
  85743. this._scene.unregisterBeforeRender(this._tickCallback);
  85744. };
  85745. /**
  85746. * Disposes the sphere.
  85747. * @param {bolean} force
  85748. */
  85749. PhysicsVortexEvent.prototype.dispose = function (force) {
  85750. var _this = this;
  85751. if (force === void 0) { force = true; }
  85752. if (force) {
  85753. this._cylinder.dispose();
  85754. }
  85755. else {
  85756. setTimeout(function () {
  85757. if (!_this._dataFetched) {
  85758. _this._cylinder.dispose();
  85759. }
  85760. }, 0);
  85761. }
  85762. };
  85763. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85764. if (impostor.mass === 0) {
  85765. return null;
  85766. }
  85767. if (!this._intersectsWithCylinder(impostor)) {
  85768. return null;
  85769. }
  85770. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85771. return null;
  85772. }
  85773. var impostorObjectCenter = impostor.getObjectCenter();
  85774. 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)
  85775. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85776. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85777. var hit = ray.intersectsMesh(impostor.object);
  85778. var contactPoint = hit.pickedPoint;
  85779. if (!contactPoint) {
  85780. return null;
  85781. }
  85782. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85783. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85784. var directionToOrigin = contactPoint.normalize();
  85785. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85786. directionToOrigin = directionToOrigin.negate();
  85787. }
  85788. // TODO: find a more physically based solution
  85789. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85790. var forceX = directionToOrigin.x * this._strength / 8;
  85791. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85792. var forceZ = directionToOrigin.z * this._strength / 8;
  85793. }
  85794. else {
  85795. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85796. var forceY = this._originTop.y * this._updraftMultiplier;
  85797. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85798. }
  85799. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85800. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85801. return { force: force, contactPoint: impostorObjectCenter };
  85802. };
  85803. PhysicsVortexEvent.prototype._tick = function () {
  85804. var _this = this;
  85805. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85806. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85807. if (!impostorForceAndContactPoint) {
  85808. return;
  85809. }
  85810. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85811. });
  85812. };
  85813. /*** Helpers ***/
  85814. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85815. if (!this._cylinder) {
  85816. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85817. height: this._height,
  85818. diameter: this._radius * 2,
  85819. }, this._scene);
  85820. this._cylinder.isVisible = false;
  85821. }
  85822. };
  85823. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85824. var impostorObject = impostor.object;
  85825. this._prepareCylinder();
  85826. this._cylinder.position = this._cylinderPosition;
  85827. return this._cylinder.intersectsMesh(impostorObject, true);
  85828. };
  85829. return PhysicsVortexEvent;
  85830. }());
  85831. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85832. /***** Enums *****/
  85833. /**
  85834. * The strenght of the force in correspondence to the distance of the affected object
  85835. */
  85836. var PhysicsRadialImpulseFalloff;
  85837. (function (PhysicsRadialImpulseFalloff) {
  85838. /** Defines that impulse is constant in strength across it's whole radius */
  85839. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85840. /** DEfines that impulse gets weaker if it's further from the origin */
  85841. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85842. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85843. /**
  85844. * The strenght of the force in correspondence to the distance of the affected object
  85845. */
  85846. var PhysicsUpdraftMode;
  85847. (function (PhysicsUpdraftMode) {
  85848. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85849. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85850. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85851. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85852. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85853. })(BABYLON || (BABYLON = {}));
  85854. //# sourceMappingURL=babylon.physicsHelper.js.map
  85855. var BABYLON;
  85856. (function (BABYLON) {
  85857. var CannonJSPlugin = /** @class */ (function () {
  85858. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85859. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85860. if (iterations === void 0) { iterations = 10; }
  85861. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85862. this.name = "CannonJSPlugin";
  85863. this._physicsMaterials = new Array();
  85864. this._fixedTimeStep = 1 / 60;
  85865. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85866. this.BJSCANNON = CANNON;
  85867. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85868. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85869. this._tmpPosition = BABYLON.Vector3.Zero();
  85870. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85871. this._tmpUnityRotation = new BABYLON.Quaternion();
  85872. if (!this.isSupported()) {
  85873. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85874. return;
  85875. }
  85876. this._extendNamespace();
  85877. this.world = new this.BJSCANNON.World();
  85878. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85879. this.world.solver.iterations = iterations;
  85880. }
  85881. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85882. this.world.gravity.copy(gravity);
  85883. };
  85884. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85885. this._fixedTimeStep = timeStep;
  85886. };
  85887. CannonJSPlugin.prototype.getTimeStep = function () {
  85888. return this._fixedTimeStep;
  85889. };
  85890. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85891. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85892. };
  85893. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85894. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85895. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85896. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85897. };
  85898. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85899. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85900. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85901. impostor.physicsBody.applyForce(impulse, worldPoint);
  85902. };
  85903. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85904. //parent-child relationship. Does this impostor has a parent impostor?
  85905. if (impostor.parent) {
  85906. if (impostor.physicsBody) {
  85907. this.removePhysicsBody(impostor);
  85908. //TODO is that needed?
  85909. impostor.forceUpdate();
  85910. }
  85911. return;
  85912. }
  85913. //should a new body be created for this impostor?
  85914. if (impostor.isBodyInitRequired()) {
  85915. var shape = this._createShape(impostor);
  85916. //unregister events, if body is being changed
  85917. var oldBody = impostor.physicsBody;
  85918. if (oldBody) {
  85919. this.removePhysicsBody(impostor);
  85920. }
  85921. //create the body and material
  85922. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85923. var bodyCreationObject = {
  85924. mass: impostor.getParam("mass"),
  85925. material: material
  85926. };
  85927. // A simple extend, in case native options were used.
  85928. var nativeOptions = impostor.getParam("nativeOptions");
  85929. for (var key in nativeOptions) {
  85930. if (nativeOptions.hasOwnProperty(key)) {
  85931. bodyCreationObject[key] = nativeOptions[key];
  85932. }
  85933. }
  85934. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85935. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85936. this.world.addEventListener("preStep", impostor.beforeStep);
  85937. this.world.addEventListener("postStep", impostor.afterStep);
  85938. impostor.physicsBody.addShape(shape);
  85939. this.world.add(impostor.physicsBody);
  85940. //try to keep the body moving in the right direction by taking old properties.
  85941. //Should be tested!
  85942. if (oldBody) {
  85943. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85944. impostor.physicsBody[param].copy(oldBody[param]);
  85945. });
  85946. }
  85947. this._processChildMeshes(impostor);
  85948. }
  85949. //now update the body's transformation
  85950. this._updatePhysicsBodyTransformation(impostor);
  85951. };
  85952. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85953. var _this = this;
  85954. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85955. var currentRotation = mainImpostor.object.rotationQuaternion;
  85956. if (meshChildren.length) {
  85957. var processMesh = function (localPosition, mesh) {
  85958. if (!currentRotation || !mesh.rotationQuaternion) {
  85959. return;
  85960. }
  85961. var childImpostor = mesh.getPhysicsImpostor();
  85962. if (childImpostor) {
  85963. var parent = childImpostor.parent;
  85964. if (parent !== mainImpostor) {
  85965. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85966. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85967. if (childImpostor.physicsBody) {
  85968. _this.removePhysicsBody(childImpostor);
  85969. childImpostor.physicsBody = null;
  85970. }
  85971. childImpostor.parent = mainImpostor;
  85972. childImpostor.resetUpdateFlags();
  85973. 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));
  85974. //Add the mass of the children.
  85975. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85976. }
  85977. }
  85978. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85979. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85980. };
  85981. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85982. }
  85983. };
  85984. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85985. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85986. this.world.removeEventListener("preStep", impostor.beforeStep);
  85987. this.world.removeEventListener("postStep", impostor.afterStep);
  85988. this.world.remove(impostor.physicsBody);
  85989. };
  85990. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85991. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85992. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85993. if (!mainBody || !connectedBody) {
  85994. return;
  85995. }
  85996. var constraint;
  85997. var jointData = impostorJoint.joint.jointData;
  85998. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85999. var constraintData = {
  86000. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86001. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86002. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86003. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86004. maxForce: jointData.nativeParams.maxForce,
  86005. collideConnected: !!jointData.collision
  86006. };
  86007. switch (impostorJoint.joint.type) {
  86008. case BABYLON.PhysicsJoint.HingeJoint:
  86009. case BABYLON.PhysicsJoint.Hinge2Joint:
  86010. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86011. break;
  86012. case BABYLON.PhysicsJoint.DistanceJoint:
  86013. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86014. break;
  86015. case BABYLON.PhysicsJoint.SpringJoint:
  86016. var springData = jointData;
  86017. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86018. restLength: springData.length,
  86019. stiffness: springData.stiffness,
  86020. damping: springData.damping,
  86021. localAnchorA: constraintData.pivotA,
  86022. localAnchorB: constraintData.pivotB
  86023. });
  86024. break;
  86025. case BABYLON.PhysicsJoint.LockJoint:
  86026. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86027. break;
  86028. case BABYLON.PhysicsJoint.PointToPointJoint:
  86029. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86030. default:
  86031. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86032. break;
  86033. }
  86034. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86035. constraint.collideConnected = !!jointData.collision;
  86036. impostorJoint.joint.physicsJoint = constraint;
  86037. //don't add spring as constraint, as it is not one.
  86038. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86039. this.world.addConstraint(constraint);
  86040. }
  86041. else {
  86042. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86043. constraint.applyForce();
  86044. });
  86045. }
  86046. };
  86047. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86048. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86049. };
  86050. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86051. var index;
  86052. var mat;
  86053. for (index = 0; index < this._physicsMaterials.length; index++) {
  86054. mat = this._physicsMaterials[index];
  86055. if (mat.friction === friction && mat.restitution === restitution) {
  86056. return mat;
  86057. }
  86058. }
  86059. var currentMat = new this.BJSCANNON.Material(name);
  86060. currentMat.friction = friction;
  86061. currentMat.restitution = restitution;
  86062. this._physicsMaterials.push(currentMat);
  86063. return currentMat;
  86064. };
  86065. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86066. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86067. };
  86068. CannonJSPlugin.prototype._createShape = function (impostor) {
  86069. var object = impostor.object;
  86070. var returnValue;
  86071. var extendSize = impostor.getObjectExtendSize();
  86072. switch (impostor.type) {
  86073. case BABYLON.PhysicsImpostor.SphereImpostor:
  86074. var radiusX = extendSize.x;
  86075. var radiusY = extendSize.y;
  86076. var radiusZ = extendSize.z;
  86077. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86078. break;
  86079. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86080. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86081. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86082. break;
  86083. case BABYLON.PhysicsImpostor.BoxImpostor:
  86084. var box = extendSize.scale(0.5);
  86085. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86086. break;
  86087. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86088. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86089. returnValue = new this.BJSCANNON.Plane();
  86090. break;
  86091. case BABYLON.PhysicsImpostor.MeshImpostor:
  86092. // should transform the vertex data to world coordinates!!
  86093. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86094. var rawFaces = object.getIndices ? object.getIndices() : [];
  86095. if (!rawVerts)
  86096. return;
  86097. // get only scale! so the object could transform correctly.
  86098. var oldPosition = object.position.clone();
  86099. var oldRotation = object.rotation && object.rotation.clone();
  86100. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86101. object.position.copyFromFloats(0, 0, 0);
  86102. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86103. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86104. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86105. var transform = object.computeWorldMatrix(true);
  86106. // convert rawVerts to object space
  86107. var temp = new Array();
  86108. var index;
  86109. for (index = 0; index < rawVerts.length; index += 3) {
  86110. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86111. }
  86112. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86113. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86114. //now set back the transformation!
  86115. object.position.copyFrom(oldPosition);
  86116. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86117. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86118. break;
  86119. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86120. var oldPosition2 = object.position.clone();
  86121. var oldRotation2 = object.rotation && object.rotation.clone();
  86122. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86123. object.position.copyFromFloats(0, 0, 0);
  86124. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86125. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86126. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86127. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86128. returnValue = this._createHeightmap(object);
  86129. object.position.copyFrom(oldPosition2);
  86130. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86131. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86132. object.computeWorldMatrix(true);
  86133. break;
  86134. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86135. returnValue = new this.BJSCANNON.Particle();
  86136. break;
  86137. }
  86138. return returnValue;
  86139. };
  86140. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86141. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86142. var transform = object.computeWorldMatrix(true);
  86143. // convert rawVerts to object space
  86144. var temp = new Array();
  86145. var index;
  86146. for (index = 0; index < pos.length; index += 3) {
  86147. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86148. }
  86149. pos = temp;
  86150. var matrix = new Array();
  86151. //For now pointDepth will not be used and will be automatically calculated.
  86152. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86153. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86154. var boundingInfo = object.getBoundingInfo();
  86155. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86156. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86157. var elementSize = dim * 2 / arraySize;
  86158. for (var i = 0; i < pos.length; i = i + 3) {
  86159. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86160. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86161. var y = -pos[i + 2] + minY;
  86162. if (!matrix[x]) {
  86163. matrix[x] = [];
  86164. }
  86165. if (!matrix[x][z]) {
  86166. matrix[x][z] = y;
  86167. }
  86168. matrix[x][z] = Math.max(y, matrix[x][z]);
  86169. }
  86170. for (var x = 0; x <= arraySize; ++x) {
  86171. if (!matrix[x]) {
  86172. var loc = 1;
  86173. while (!matrix[(x + loc) % arraySize]) {
  86174. loc++;
  86175. }
  86176. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86177. //console.log("missing x", x);
  86178. }
  86179. for (var z = 0; z <= arraySize; ++z) {
  86180. if (!matrix[x][z]) {
  86181. var loc = 1;
  86182. var newValue;
  86183. while (newValue === undefined) {
  86184. newValue = matrix[x][(z + loc++) % arraySize];
  86185. }
  86186. matrix[x][z] = newValue;
  86187. }
  86188. }
  86189. }
  86190. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86191. elementSize: elementSize
  86192. });
  86193. //For future reference, needed for body transformation
  86194. shape.minY = minY;
  86195. return shape;
  86196. };
  86197. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86198. var object = impostor.object;
  86199. //make sure it is updated...
  86200. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86201. // The delta between the mesh position and the mesh bounding box center
  86202. var bInfo = object.getBoundingInfo();
  86203. if (!bInfo)
  86204. return;
  86205. var center = impostor.getObjectCenter();
  86206. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86207. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86208. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86209. this._tmpPosition.copyFrom(center);
  86210. var quaternion = object.rotationQuaternion;
  86211. if (!quaternion) {
  86212. return;
  86213. }
  86214. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86215. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86216. //-90 DEG in X, precalculated
  86217. quaternion = quaternion.multiply(this._minus90X);
  86218. //Invert! (Precalculated, 90 deg in X)
  86219. //No need to clone. this will never change.
  86220. impostor.setDeltaRotation(this._plus90X);
  86221. }
  86222. //If it is a heightfield, if should be centered.
  86223. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86224. var mesh = object;
  86225. var boundingInfo = mesh.getBoundingInfo();
  86226. //calculate the correct body position:
  86227. var rotationQuaternion = mesh.rotationQuaternion;
  86228. mesh.rotationQuaternion = this._tmpUnityRotation;
  86229. mesh.computeWorldMatrix(true);
  86230. //get original center with no rotation
  86231. var c = center.clone();
  86232. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86233. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86234. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86235. mesh.setPreTransformMatrix(p);
  86236. mesh.computeWorldMatrix(true);
  86237. //calculate the translation
  86238. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86239. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86240. //add it inverted to the delta
  86241. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86242. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86243. //rotation is back
  86244. mesh.rotationQuaternion = rotationQuaternion;
  86245. mesh.setPreTransformMatrix(oldPivot);
  86246. mesh.computeWorldMatrix(true);
  86247. }
  86248. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86249. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86250. //this._tmpPosition.copyFrom(object.position);
  86251. }
  86252. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86253. //Now update the impostor object
  86254. impostor.physicsBody.position.copy(this._tmpPosition);
  86255. impostor.physicsBody.quaternion.copy(quaternion);
  86256. };
  86257. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86258. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86259. if (impostor.object.rotationQuaternion) {
  86260. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86261. }
  86262. };
  86263. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86264. impostor.physicsBody.position.copy(newPosition);
  86265. impostor.physicsBody.quaternion.copy(newRotation);
  86266. };
  86267. CannonJSPlugin.prototype.isSupported = function () {
  86268. return this.BJSCANNON !== undefined;
  86269. };
  86270. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86271. impostor.physicsBody.velocity.copy(velocity);
  86272. };
  86273. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86274. impostor.physicsBody.angularVelocity.copy(velocity);
  86275. };
  86276. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86277. var v = impostor.physicsBody.velocity;
  86278. if (!v) {
  86279. return null;
  86280. }
  86281. return new BABYLON.Vector3(v.x, v.y, v.z);
  86282. };
  86283. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86284. var v = impostor.physicsBody.angularVelocity;
  86285. if (!v) {
  86286. return null;
  86287. }
  86288. return new BABYLON.Vector3(v.x, v.y, v.z);
  86289. };
  86290. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86291. impostor.physicsBody.mass = mass;
  86292. impostor.physicsBody.updateMassProperties();
  86293. };
  86294. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86295. return impostor.physicsBody.mass;
  86296. };
  86297. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86298. return impostor.physicsBody.material.friction;
  86299. };
  86300. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86301. impostor.physicsBody.material.friction = friction;
  86302. };
  86303. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86304. return impostor.physicsBody.material.restitution;
  86305. };
  86306. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86307. impostor.physicsBody.material.restitution = restitution;
  86308. };
  86309. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86310. impostor.physicsBody.sleep();
  86311. };
  86312. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86313. impostor.physicsBody.wakeUp();
  86314. };
  86315. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86316. joint.physicsJoint.distance = maxDistance;
  86317. };
  86318. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86319. // if (!motorIndex) {
  86320. // joint.physicsJoint.enableMotor();
  86321. // }
  86322. // }
  86323. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86324. // if (!motorIndex) {
  86325. // joint.physicsJoint.disableMotor();
  86326. // }
  86327. // }
  86328. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86329. if (!motorIndex) {
  86330. joint.physicsJoint.enableMotor();
  86331. joint.physicsJoint.setMotorSpeed(speed);
  86332. if (maxForce) {
  86333. this.setLimit(joint, maxForce);
  86334. }
  86335. }
  86336. };
  86337. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86338. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86339. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86340. };
  86341. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86342. var body = impostor.physicsBody;
  86343. mesh.position.x = body.position.x;
  86344. mesh.position.y = body.position.y;
  86345. mesh.position.z = body.position.z;
  86346. if (mesh.rotationQuaternion) {
  86347. mesh.rotationQuaternion.x = body.quaternion.x;
  86348. mesh.rotationQuaternion.y = body.quaternion.y;
  86349. mesh.rotationQuaternion.z = body.quaternion.z;
  86350. mesh.rotationQuaternion.w = body.quaternion.w;
  86351. }
  86352. };
  86353. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86354. var shape = impostor.physicsBody.shapes[0];
  86355. return shape.boundingSphereRadius;
  86356. };
  86357. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86358. var shape = impostor.physicsBody.shapes[0];
  86359. result.x = shape.halfExtents.x * 2;
  86360. result.y = shape.halfExtents.y * 2;
  86361. result.z = shape.halfExtents.z * 2;
  86362. };
  86363. CannonJSPlugin.prototype.dispose = function () {
  86364. };
  86365. CannonJSPlugin.prototype._extendNamespace = function () {
  86366. //this will force cannon to execute at least one step when using interpolation
  86367. var step_tmp1 = new this.BJSCANNON.Vec3();
  86368. var Engine = this.BJSCANNON;
  86369. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86370. maxSubSteps = maxSubSteps || 10;
  86371. timeSinceLastCalled = timeSinceLastCalled || 0;
  86372. if (timeSinceLastCalled === 0) {
  86373. this.internalStep(dt);
  86374. this.time += dt;
  86375. }
  86376. else {
  86377. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86378. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86379. var t0 = performance.now();
  86380. for (var i = 0; i !== internalSteps; i++) {
  86381. this.internalStep(dt);
  86382. if (performance.now() - t0 > dt * 1000) {
  86383. break;
  86384. }
  86385. }
  86386. this.time += timeSinceLastCalled;
  86387. var h = this.time % dt;
  86388. var h_div_dt = h / dt;
  86389. var interpvelo = step_tmp1;
  86390. var bodies = this.bodies;
  86391. for (var j = 0; j !== bodies.length; j++) {
  86392. var b = bodies[j];
  86393. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86394. b.position.vsub(b.previousPosition, interpvelo);
  86395. interpvelo.scale(h_div_dt, interpvelo);
  86396. b.position.vadd(interpvelo, b.interpolatedPosition);
  86397. }
  86398. else {
  86399. b.interpolatedPosition.copy(b.position);
  86400. b.interpolatedQuaternion.copy(b.quaternion);
  86401. }
  86402. }
  86403. }
  86404. };
  86405. };
  86406. return CannonJSPlugin;
  86407. }());
  86408. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86409. })(BABYLON || (BABYLON = {}));
  86410. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86411. var BABYLON;
  86412. (function (BABYLON) {
  86413. var OimoJSPlugin = /** @class */ (function () {
  86414. function OimoJSPlugin(iterations) {
  86415. this.name = "OimoJSPlugin";
  86416. this._tmpImpostorsArray = [];
  86417. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86418. this.BJSOIMO = OIMO;
  86419. this.world = new this.BJSOIMO.World({
  86420. iterations: iterations
  86421. });
  86422. this.world.clear();
  86423. }
  86424. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86425. this.world.gravity.copy(gravity);
  86426. };
  86427. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86428. this.world.timeStep = timeStep;
  86429. };
  86430. OimoJSPlugin.prototype.getTimeStep = function () {
  86431. return this.world.timeStep;
  86432. };
  86433. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86434. var _this = this;
  86435. impostors.forEach(function (impostor) {
  86436. impostor.beforeStep();
  86437. });
  86438. this.world.step();
  86439. impostors.forEach(function (impostor) {
  86440. impostor.afterStep();
  86441. //update the ordered impostors array
  86442. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86443. });
  86444. //check for collisions
  86445. var contact = this.world.contacts;
  86446. while (contact !== null) {
  86447. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86448. contact = contact.next;
  86449. continue;
  86450. }
  86451. //is this body colliding with any other? get the impostor
  86452. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86453. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86454. if (!mainImpostor || !collidingImpostor) {
  86455. contact = contact.next;
  86456. continue;
  86457. }
  86458. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86459. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86460. contact = contact.next;
  86461. }
  86462. };
  86463. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86464. var mass = impostor.physicsBody.mass;
  86465. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86466. };
  86467. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86468. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86469. this.applyImpulse(impostor, force, contactPoint);
  86470. };
  86471. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86472. var _this = this;
  86473. //parent-child relationship. Does this impostor has a parent impostor?
  86474. if (impostor.parent) {
  86475. if (impostor.physicsBody) {
  86476. this.removePhysicsBody(impostor);
  86477. //TODO is that needed?
  86478. impostor.forceUpdate();
  86479. }
  86480. return;
  86481. }
  86482. if (impostor.isBodyInitRequired()) {
  86483. var bodyConfig = {
  86484. name: impostor.uniqueId,
  86485. //Oimo must have mass, also for static objects.
  86486. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86487. size: [],
  86488. type: [],
  86489. pos: [],
  86490. posShape: [],
  86491. rot: [],
  86492. rotShape: [],
  86493. move: impostor.getParam("mass") !== 0,
  86494. density: impostor.getParam("mass"),
  86495. friction: impostor.getParam("friction"),
  86496. restitution: impostor.getParam("restitution"),
  86497. //Supporting older versions of Oimo
  86498. world: this.world
  86499. };
  86500. var impostors = [impostor];
  86501. var addToArray = function (parent) {
  86502. if (!parent.getChildMeshes)
  86503. return;
  86504. parent.getChildMeshes().forEach(function (m) {
  86505. if (m.physicsImpostor) {
  86506. impostors.push(m.physicsImpostor);
  86507. //m.physicsImpostor._init();
  86508. }
  86509. });
  86510. };
  86511. addToArray(impostor.object);
  86512. var checkWithEpsilon_1 = function (value) {
  86513. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86514. };
  86515. impostors.forEach(function (i) {
  86516. if (!i.object.rotationQuaternion) {
  86517. return;
  86518. }
  86519. //get the correct bounding box
  86520. var oldQuaternion = i.object.rotationQuaternion;
  86521. var rot = oldQuaternion.toEulerAngles();
  86522. var extendSize = i.getObjectExtendSize();
  86523. var radToDeg = 57.295779513082320876;
  86524. if (i === impostor) {
  86525. var center = impostor.getObjectCenter();
  86526. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86527. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86528. //Can also use Array.prototype.push.apply
  86529. bodyConfig.pos.push(center.x);
  86530. bodyConfig.pos.push(center.y);
  86531. bodyConfig.pos.push(center.z);
  86532. bodyConfig.posShape.push(0, 0, 0);
  86533. //tmp solution
  86534. bodyConfig.rot.push(rot.x * radToDeg);
  86535. bodyConfig.rot.push(rot.y * radToDeg);
  86536. bodyConfig.rot.push(rot.z * radToDeg);
  86537. bodyConfig.rotShape.push(0, 0, 0);
  86538. }
  86539. else {
  86540. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86541. bodyConfig.posShape.push(localPosition.x);
  86542. bodyConfig.posShape.push(localPosition.y);
  86543. bodyConfig.posShape.push(localPosition.z);
  86544. bodyConfig.pos.push(0, 0, 0);
  86545. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86546. bodyConfig.rot.push(0);
  86547. bodyConfig.rot.push(0);
  86548. bodyConfig.rot.push(0);
  86549. bodyConfig.rotShape.push(rot.x * radToDeg);
  86550. bodyConfig.rotShape.push(rot.y * radToDeg);
  86551. bodyConfig.rotShape.push(rot.z * radToDeg);
  86552. }
  86553. // register mesh
  86554. switch (i.type) {
  86555. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86556. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86557. case BABYLON.PhysicsImpostor.SphereImpostor:
  86558. var radiusX = extendSize.x;
  86559. var radiusY = extendSize.y;
  86560. var radiusZ = extendSize.z;
  86561. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86562. bodyConfig.type.push('sphere');
  86563. //due to the way oimo works with compounds, add 3 times
  86564. bodyConfig.size.push(size);
  86565. bodyConfig.size.push(size);
  86566. bodyConfig.size.push(size);
  86567. break;
  86568. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86569. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86570. var sizeY = checkWithEpsilon_1(extendSize.y);
  86571. bodyConfig.type.push('cylinder');
  86572. bodyConfig.size.push(sizeX);
  86573. bodyConfig.size.push(sizeY);
  86574. //due to the way oimo works with compounds, add one more value.
  86575. bodyConfig.size.push(sizeY);
  86576. break;
  86577. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86578. case BABYLON.PhysicsImpostor.BoxImpostor:
  86579. default:
  86580. var sizeX = checkWithEpsilon_1(extendSize.x);
  86581. var sizeY = checkWithEpsilon_1(extendSize.y);
  86582. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86583. bodyConfig.type.push('box');
  86584. //if (i === impostor) {
  86585. bodyConfig.size.push(sizeX);
  86586. bodyConfig.size.push(sizeY);
  86587. bodyConfig.size.push(sizeZ);
  86588. //} else {
  86589. // bodyConfig.size.push(0,0,0);
  86590. //}
  86591. break;
  86592. }
  86593. //actually not needed, but hey...
  86594. i.object.rotationQuaternion = oldQuaternion;
  86595. });
  86596. impostor.physicsBody = this.world.add(bodyConfig);
  86597. }
  86598. else {
  86599. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86600. }
  86601. impostor.setDeltaPosition(this._tmpPositionVector);
  86602. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86603. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86604. };
  86605. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86606. //impostor.physicsBody.dispose();
  86607. //Same as : (older oimo versions)
  86608. this.world.removeRigidBody(impostor.physicsBody);
  86609. };
  86610. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86611. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86612. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86613. if (!mainBody || !connectedBody) {
  86614. return;
  86615. }
  86616. var jointData = impostorJoint.joint.jointData;
  86617. var options = jointData.nativeParams || {};
  86618. var type;
  86619. var nativeJointData = {
  86620. body1: mainBody,
  86621. body2: connectedBody,
  86622. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86623. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86624. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86625. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86626. min: options.min,
  86627. max: options.max,
  86628. collision: options.collision || jointData.collision,
  86629. spring: options.spring,
  86630. //supporting older version of Oimo
  86631. world: this.world
  86632. };
  86633. switch (impostorJoint.joint.type) {
  86634. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86635. type = "jointBall";
  86636. break;
  86637. case BABYLON.PhysicsJoint.SpringJoint:
  86638. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86639. var springData = jointData;
  86640. nativeJointData.min = springData.length || nativeJointData.min;
  86641. //Max should also be set, just make sure it is at least min
  86642. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86643. case BABYLON.PhysicsJoint.DistanceJoint:
  86644. type = "jointDistance";
  86645. nativeJointData.max = jointData.maxDistance;
  86646. break;
  86647. case BABYLON.PhysicsJoint.PrismaticJoint:
  86648. type = "jointPrisme";
  86649. break;
  86650. case BABYLON.PhysicsJoint.SliderJoint:
  86651. type = "jointSlide";
  86652. break;
  86653. case BABYLON.PhysicsJoint.WheelJoint:
  86654. type = "jointWheel";
  86655. break;
  86656. case BABYLON.PhysicsJoint.HingeJoint:
  86657. default:
  86658. type = "jointHinge";
  86659. break;
  86660. }
  86661. nativeJointData.type = type;
  86662. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86663. };
  86664. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86665. //Bug in Oimo prevents us from disposing a joint in the playground
  86666. //joint.joint.physicsJoint.dispose();
  86667. //So we will bruteforce it!
  86668. try {
  86669. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86670. }
  86671. catch (e) {
  86672. BABYLON.Tools.Warn(e);
  86673. }
  86674. };
  86675. OimoJSPlugin.prototype.isSupported = function () {
  86676. return this.BJSOIMO !== undefined;
  86677. };
  86678. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86679. if (!impostor.physicsBody.sleeping) {
  86680. //TODO check that
  86681. /*if (impostor.physicsBody.shapes.next) {
  86682. var parentShape = this._getLastShape(impostor.physicsBody);
  86683. impostor.object.position.copyFrom(parentShape.position);
  86684. console.log(parentShape.position);
  86685. } else {*/
  86686. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86687. //}
  86688. if (impostor.object.rotationQuaternion) {
  86689. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86690. }
  86691. }
  86692. };
  86693. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86694. var body = impostor.physicsBody;
  86695. body.position.copy(newPosition);
  86696. body.orientation.copy(newRotation);
  86697. body.syncShapes();
  86698. body.awake();
  86699. };
  86700. /*private _getLastShape(body: any): any {
  86701. var lastShape = body.shapes;
  86702. while (lastShape.next) {
  86703. lastShape = lastShape.next;
  86704. }
  86705. return lastShape;
  86706. }*/
  86707. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86708. impostor.physicsBody.linearVelocity.copy(velocity);
  86709. };
  86710. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86711. impostor.physicsBody.angularVelocity.copy(velocity);
  86712. };
  86713. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86714. var v = impostor.physicsBody.linearVelocity;
  86715. if (!v) {
  86716. return null;
  86717. }
  86718. return new BABYLON.Vector3(v.x, v.y, v.z);
  86719. };
  86720. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86721. var v = impostor.physicsBody.angularVelocity;
  86722. if (!v) {
  86723. return null;
  86724. }
  86725. return new BABYLON.Vector3(v.x, v.y, v.z);
  86726. };
  86727. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86728. var staticBody = mass === 0;
  86729. //this will actually set the body's density and not its mass.
  86730. //But this is how oimo treats the mass variable.
  86731. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86732. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86733. };
  86734. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86735. return impostor.physicsBody.shapes.density;
  86736. };
  86737. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86738. return impostor.physicsBody.shapes.friction;
  86739. };
  86740. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86741. impostor.physicsBody.shapes.friction = friction;
  86742. };
  86743. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86744. return impostor.physicsBody.shapes.restitution;
  86745. };
  86746. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86747. impostor.physicsBody.shapes.restitution = restitution;
  86748. };
  86749. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86750. impostor.physicsBody.sleep();
  86751. };
  86752. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86753. impostor.physicsBody.awake();
  86754. };
  86755. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86756. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86757. if (minDistance !== void 0) {
  86758. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86759. }
  86760. };
  86761. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86762. //TODO separate rotational and transational motors.
  86763. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86764. if (motor) {
  86765. motor.setMotor(speed, maxForce);
  86766. }
  86767. };
  86768. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86769. //TODO separate rotational and transational motors.
  86770. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86771. if (motor) {
  86772. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86773. }
  86774. };
  86775. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86776. var body = impostor.physicsBody;
  86777. mesh.position.x = body.position.x;
  86778. mesh.position.y = body.position.y;
  86779. mesh.position.z = body.position.z;
  86780. if (mesh.rotationQuaternion) {
  86781. mesh.rotationQuaternion.x = body.orientation.x;
  86782. mesh.rotationQuaternion.y = body.orientation.y;
  86783. mesh.rotationQuaternion.z = body.orientation.z;
  86784. mesh.rotationQuaternion.w = body.orientation.s;
  86785. }
  86786. };
  86787. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86788. return impostor.physicsBody.shapes.radius;
  86789. };
  86790. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86791. var shape = impostor.physicsBody.shapes;
  86792. result.x = shape.halfWidth * 2;
  86793. result.y = shape.halfHeight * 2;
  86794. result.z = shape.halfDepth * 2;
  86795. };
  86796. OimoJSPlugin.prototype.dispose = function () {
  86797. this.world.clear();
  86798. };
  86799. return OimoJSPlugin;
  86800. }());
  86801. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86802. })(BABYLON || (BABYLON = {}));
  86803. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86804. var BABYLON;
  86805. (function (BABYLON) {
  86806. /*
  86807. * Based on jsTGALoader - Javascript loader for TGA file
  86808. * By Vincent Thibault
  86809. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86810. */
  86811. var TGATools = /** @class */ (function () {
  86812. function TGATools() {
  86813. }
  86814. TGATools.GetTGAHeader = function (data) {
  86815. var offset = 0;
  86816. var header = {
  86817. id_length: data[offset++],
  86818. colormap_type: data[offset++],
  86819. image_type: data[offset++],
  86820. colormap_index: data[offset++] | data[offset++] << 8,
  86821. colormap_length: data[offset++] | data[offset++] << 8,
  86822. colormap_size: data[offset++],
  86823. origin: [
  86824. data[offset++] | data[offset++] << 8,
  86825. data[offset++] | data[offset++] << 8
  86826. ],
  86827. width: data[offset++] | data[offset++] << 8,
  86828. height: data[offset++] | data[offset++] << 8,
  86829. pixel_size: data[offset++],
  86830. flags: data[offset++]
  86831. };
  86832. return header;
  86833. };
  86834. TGATools.UploadContent = function (gl, data) {
  86835. // Not enough data to contain header ?
  86836. if (data.length < 19) {
  86837. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86838. return;
  86839. }
  86840. // Read Header
  86841. var offset = 18;
  86842. var header = TGATools.GetTGAHeader(data);
  86843. // Assume it's a valid Targa file.
  86844. if (header.id_length + offset > data.length) {
  86845. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86846. return;
  86847. }
  86848. // Skip not needed data
  86849. offset += header.id_length;
  86850. var use_rle = false;
  86851. var use_pal = false;
  86852. var use_grey = false;
  86853. // Get some informations.
  86854. switch (header.image_type) {
  86855. case TGATools._TYPE_RLE_INDEXED:
  86856. use_rle = true;
  86857. case TGATools._TYPE_INDEXED:
  86858. use_pal = true;
  86859. break;
  86860. case TGATools._TYPE_RLE_RGB:
  86861. use_rle = true;
  86862. case TGATools._TYPE_RGB:
  86863. // use_rgb = true;
  86864. break;
  86865. case TGATools._TYPE_RLE_GREY:
  86866. use_rle = true;
  86867. case TGATools._TYPE_GREY:
  86868. use_grey = true;
  86869. break;
  86870. }
  86871. var pixel_data;
  86872. // var numAlphaBits = header.flags & 0xf;
  86873. var pixel_size = header.pixel_size >> 3;
  86874. var pixel_total = header.width * header.height * pixel_size;
  86875. // Read palettes
  86876. var palettes;
  86877. if (use_pal) {
  86878. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86879. }
  86880. // Read LRE
  86881. if (use_rle) {
  86882. pixel_data = new Uint8Array(pixel_total);
  86883. var c, count, i;
  86884. var localOffset = 0;
  86885. var pixels = new Uint8Array(pixel_size);
  86886. while (offset < pixel_total && localOffset < pixel_total) {
  86887. c = data[offset++];
  86888. count = (c & 0x7f) + 1;
  86889. // RLE pixels
  86890. if (c & 0x80) {
  86891. // Bind pixel tmp array
  86892. for (i = 0; i < pixel_size; ++i) {
  86893. pixels[i] = data[offset++];
  86894. }
  86895. // Copy pixel array
  86896. for (i = 0; i < count; ++i) {
  86897. pixel_data.set(pixels, localOffset + i * pixel_size);
  86898. }
  86899. localOffset += pixel_size * count;
  86900. }
  86901. // Raw pixels
  86902. else {
  86903. count *= pixel_size;
  86904. for (i = 0; i < count; ++i) {
  86905. pixel_data[localOffset + i] = data[offset++];
  86906. }
  86907. localOffset += count;
  86908. }
  86909. }
  86910. }
  86911. // RAW Pixels
  86912. else {
  86913. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86914. }
  86915. // Load to texture
  86916. var x_start, y_start, x_step, y_step, y_end, x_end;
  86917. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86918. default:
  86919. case TGATools._ORIGIN_UL:
  86920. x_start = 0;
  86921. x_step = 1;
  86922. x_end = header.width;
  86923. y_start = 0;
  86924. y_step = 1;
  86925. y_end = header.height;
  86926. break;
  86927. case TGATools._ORIGIN_BL:
  86928. x_start = 0;
  86929. x_step = 1;
  86930. x_end = header.width;
  86931. y_start = header.height - 1;
  86932. y_step = -1;
  86933. y_end = -1;
  86934. break;
  86935. case TGATools._ORIGIN_UR:
  86936. x_start = header.width - 1;
  86937. x_step = -1;
  86938. x_end = -1;
  86939. y_start = 0;
  86940. y_step = 1;
  86941. y_end = header.height;
  86942. break;
  86943. case TGATools._ORIGIN_BR:
  86944. x_start = header.width - 1;
  86945. x_step = -1;
  86946. x_end = -1;
  86947. y_start = header.height - 1;
  86948. y_step = -1;
  86949. y_end = -1;
  86950. break;
  86951. }
  86952. // Load the specify method
  86953. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86954. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86955. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  86956. };
  86957. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86958. var image = pixel_data, colormap = palettes;
  86959. var width = header.width, height = header.height;
  86960. var color, i = 0, x, y;
  86961. var imageData = new Uint8Array(width * height * 4);
  86962. for (y = y_start; y !== y_end; y += y_step) {
  86963. for (x = x_start; x !== x_end; x += x_step, i++) {
  86964. color = image[i];
  86965. imageData[(x + width * y) * 4 + 3] = 255;
  86966. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86967. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86968. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86969. }
  86970. }
  86971. return imageData;
  86972. };
  86973. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86974. var image = pixel_data;
  86975. var width = header.width, height = header.height;
  86976. var color, i = 0, x, y;
  86977. var imageData = new Uint8Array(width * height * 4);
  86978. for (y = y_start; y !== y_end; y += y_step) {
  86979. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86980. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86981. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86982. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86983. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86984. imageData[(x + width * y) * 4 + 0] = r;
  86985. imageData[(x + width * y) * 4 + 1] = g;
  86986. imageData[(x + width * y) * 4 + 2] = b;
  86987. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86988. }
  86989. }
  86990. return imageData;
  86991. };
  86992. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86993. var image = pixel_data;
  86994. var width = header.width, height = header.height;
  86995. var i = 0, x, y;
  86996. var imageData = new Uint8Array(width * height * 4);
  86997. for (y = y_start; y !== y_end; y += y_step) {
  86998. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86999. imageData[(x + width * y) * 4 + 3] = 255;
  87000. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87001. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87002. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87003. }
  87004. }
  87005. return imageData;
  87006. };
  87007. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87008. var image = pixel_data;
  87009. var width = header.width, height = header.height;
  87010. var i = 0, x, y;
  87011. var imageData = new Uint8Array(width * height * 4);
  87012. for (y = y_start; y !== y_end; y += y_step) {
  87013. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  87014. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87015. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87016. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87017. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  87018. }
  87019. }
  87020. return imageData;
  87021. };
  87022. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87023. var image = pixel_data;
  87024. var width = header.width, height = header.height;
  87025. var color, i = 0, x, y;
  87026. var imageData = new Uint8Array(width * height * 4);
  87027. for (y = y_start; y !== y_end; y += y_step) {
  87028. for (x = x_start; x !== x_end; x += x_step, i++) {
  87029. color = image[i];
  87030. imageData[(x + width * y) * 4 + 0] = color;
  87031. imageData[(x + width * y) * 4 + 1] = color;
  87032. imageData[(x + width * y) * 4 + 2] = color;
  87033. imageData[(x + width * y) * 4 + 3] = 255;
  87034. }
  87035. }
  87036. return imageData;
  87037. };
  87038. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87039. var image = pixel_data;
  87040. var width = header.width, height = header.height;
  87041. var i = 0, x, y;
  87042. var imageData = new Uint8Array(width * height * 4);
  87043. for (y = y_start; y !== y_end; y += y_step) {
  87044. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87045. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  87046. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  87047. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87048. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  87049. }
  87050. }
  87051. return imageData;
  87052. };
  87053. //private static _TYPE_NO_DATA = 0;
  87054. TGATools._TYPE_INDEXED = 1;
  87055. TGATools._TYPE_RGB = 2;
  87056. TGATools._TYPE_GREY = 3;
  87057. TGATools._TYPE_RLE_INDEXED = 9;
  87058. TGATools._TYPE_RLE_RGB = 10;
  87059. TGATools._TYPE_RLE_GREY = 11;
  87060. TGATools._ORIGIN_MASK = 0x30;
  87061. TGATools._ORIGIN_SHIFT = 0x04;
  87062. TGATools._ORIGIN_BL = 0x00;
  87063. TGATools._ORIGIN_BR = 0x01;
  87064. TGATools._ORIGIN_UL = 0x02;
  87065. TGATools._ORIGIN_UR = 0x03;
  87066. return TGATools;
  87067. }());
  87068. BABYLON.TGATools = TGATools;
  87069. })(BABYLON || (BABYLON = {}));
  87070. //# sourceMappingURL=babylon.tga.js.map
  87071. var BABYLON;
  87072. (function (BABYLON) {
  87073. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87074. // All values and structures referenced from:
  87075. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87076. var DDS_MAGIC = 0x20534444;
  87077. var
  87078. //DDSD_CAPS = 0x1,
  87079. //DDSD_HEIGHT = 0x2,
  87080. //DDSD_WIDTH = 0x4,
  87081. //DDSD_PITCH = 0x8,
  87082. //DDSD_PIXELFORMAT = 0x1000,
  87083. DDSD_MIPMAPCOUNT = 0x20000;
  87084. //DDSD_LINEARSIZE = 0x80000,
  87085. //DDSD_DEPTH = 0x800000;
  87086. // var DDSCAPS_COMPLEX = 0x8,
  87087. // DDSCAPS_MIPMAP = 0x400000,
  87088. // DDSCAPS_TEXTURE = 0x1000;
  87089. var DDSCAPS2_CUBEMAP = 0x200;
  87090. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87091. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87092. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87093. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87094. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87095. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87096. // DDSCAPS2_VOLUME = 0x200000;
  87097. var
  87098. //DDPF_ALPHAPIXELS = 0x1,
  87099. //DDPF_ALPHA = 0x2,
  87100. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87101. //DDPF_YUV = 0x200,
  87102. DDPF_LUMINANCE = 0x20000;
  87103. function FourCCToInt32(value) {
  87104. return value.charCodeAt(0) +
  87105. (value.charCodeAt(1) << 8) +
  87106. (value.charCodeAt(2) << 16) +
  87107. (value.charCodeAt(3) << 24);
  87108. }
  87109. function Int32ToFourCC(value) {
  87110. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87111. }
  87112. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87113. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87114. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87115. var FOURCC_DX10 = FourCCToInt32("DX10");
  87116. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87117. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87118. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87119. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87120. var headerLengthInt = 31; // The header length in 32 bit ints
  87121. // Offsets into the header array
  87122. var off_magic = 0;
  87123. var off_size = 1;
  87124. var off_flags = 2;
  87125. var off_height = 3;
  87126. var off_width = 4;
  87127. var off_mipmapCount = 7;
  87128. var off_pfFlags = 20;
  87129. var off_pfFourCC = 21;
  87130. var off_RGBbpp = 22;
  87131. var off_RMask = 23;
  87132. var off_GMask = 24;
  87133. var off_BMask = 25;
  87134. var off_AMask = 26;
  87135. // var off_caps1 = 27;
  87136. var off_caps2 = 28;
  87137. // var off_caps3 = 29;
  87138. // var off_caps4 = 30;
  87139. var off_dxgiFormat = 32;
  87140. ;
  87141. var DDSTools = /** @class */ (function () {
  87142. function DDSTools() {
  87143. }
  87144. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87145. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87146. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87147. var mipmapCount = 1;
  87148. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87149. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87150. }
  87151. var fourCC = header[off_pfFourCC];
  87152. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87153. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87154. switch (fourCC) {
  87155. case FOURCC_D3DFMT_R16G16B16A16F:
  87156. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87157. break;
  87158. case FOURCC_D3DFMT_R32G32B32A32F:
  87159. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87160. break;
  87161. case FOURCC_DX10:
  87162. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87163. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87164. break;
  87165. }
  87166. }
  87167. return {
  87168. width: header[off_width],
  87169. height: header[off_height],
  87170. mipmapCount: mipmapCount,
  87171. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87172. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87173. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87174. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87175. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87176. dxgiFormat: dxgiFormat,
  87177. textureType: textureType
  87178. };
  87179. };
  87180. DDSTools._ToHalfFloat = function (value) {
  87181. if (!DDSTools._FloatView) {
  87182. DDSTools._FloatView = new Float32Array(1);
  87183. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87184. }
  87185. DDSTools._FloatView[0] = value;
  87186. var x = DDSTools._Int32View[0];
  87187. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87188. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87189. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87190. /* If zero, or denormal, or exponent underflows too much for a denormal
  87191. * half, return signed zero. */
  87192. if (e < 103) {
  87193. return bits;
  87194. }
  87195. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87196. if (e > 142) {
  87197. bits |= 0x7c00;
  87198. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87199. * not Inf, so make sure we set one mantissa bit too. */
  87200. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87201. return bits;
  87202. }
  87203. /* If exponent underflows but not too much, return a denormal */
  87204. if (e < 113) {
  87205. m |= 0x0800;
  87206. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87207. * to 1, which is OK. */
  87208. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87209. return bits;
  87210. }
  87211. bits |= ((e - 112) << 10) | (m >> 1);
  87212. bits += m & 1;
  87213. return bits;
  87214. };
  87215. DDSTools._FromHalfFloat = function (value) {
  87216. var s = (value & 0x8000) >> 15;
  87217. var e = (value & 0x7C00) >> 10;
  87218. var f = value & 0x03FF;
  87219. if (e === 0) {
  87220. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87221. }
  87222. else if (e == 0x1F) {
  87223. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87224. }
  87225. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87226. };
  87227. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87228. var destArray = new Float32Array(dataLength);
  87229. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87230. var index = 0;
  87231. for (var y = 0; y < height; y++) {
  87232. for (var x = 0; x < width; x++) {
  87233. var srcPos = (x + y * width) * 4;
  87234. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87235. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87236. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87237. if (DDSTools.StoreLODInAlphaChannel) {
  87238. destArray[index + 3] = lod;
  87239. }
  87240. else {
  87241. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87242. }
  87243. index += 4;
  87244. }
  87245. }
  87246. return destArray;
  87247. };
  87248. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87249. if (DDSTools.StoreLODInAlphaChannel) {
  87250. var destArray = new Uint16Array(dataLength);
  87251. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87252. var index = 0;
  87253. for (var y = 0; y < height; y++) {
  87254. for (var x = 0; x < width; x++) {
  87255. var srcPos = (x + y * width) * 4;
  87256. destArray[index] = srcData[srcPos];
  87257. destArray[index + 1] = srcData[srcPos + 1];
  87258. destArray[index + 2] = srcData[srcPos + 2];
  87259. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87260. index += 4;
  87261. }
  87262. }
  87263. return destArray;
  87264. }
  87265. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87266. };
  87267. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87268. if (DDSTools.StoreLODInAlphaChannel) {
  87269. var destArray = new Float32Array(dataLength);
  87270. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87271. var index = 0;
  87272. for (var y = 0; y < height; y++) {
  87273. for (var x = 0; x < width; x++) {
  87274. var srcPos = (x + y * width) * 4;
  87275. destArray[index] = srcData[srcPos];
  87276. destArray[index + 1] = srcData[srcPos + 1];
  87277. destArray[index + 2] = srcData[srcPos + 2];
  87278. destArray[index + 3] = lod;
  87279. index += 4;
  87280. }
  87281. }
  87282. return destArray;
  87283. }
  87284. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87285. };
  87286. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87287. var destArray = new Uint8Array(dataLength);
  87288. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87289. var index = 0;
  87290. for (var y = 0; y < height; y++) {
  87291. for (var x = 0; x < width; x++) {
  87292. var srcPos = (x + y * width) * 4;
  87293. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87294. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87295. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87296. if (DDSTools.StoreLODInAlphaChannel) {
  87297. destArray[index + 3] = lod;
  87298. }
  87299. else {
  87300. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87301. }
  87302. index += 4;
  87303. }
  87304. }
  87305. return destArray;
  87306. };
  87307. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87308. var destArray = new Uint8Array(dataLength);
  87309. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87310. var index = 0;
  87311. for (var y = 0; y < height; y++) {
  87312. for (var x = 0; x < width; x++) {
  87313. var srcPos = (x + y * width) * 4;
  87314. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87315. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87316. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87317. if (DDSTools.StoreLODInAlphaChannel) {
  87318. destArray[index + 3] = lod;
  87319. }
  87320. else {
  87321. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87322. }
  87323. index += 4;
  87324. }
  87325. }
  87326. return destArray;
  87327. };
  87328. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87329. var byteArray = new Uint8Array(dataLength);
  87330. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87331. var index = 0;
  87332. for (var y = 0; y < height; y++) {
  87333. for (var x = 0; x < width; x++) {
  87334. var srcPos = (x + y * width) * 4;
  87335. byteArray[index] = srcData[srcPos + rOffset];
  87336. byteArray[index + 1] = srcData[srcPos + gOffset];
  87337. byteArray[index + 2] = srcData[srcPos + bOffset];
  87338. byteArray[index + 3] = srcData[srcPos + aOffset];
  87339. index += 4;
  87340. }
  87341. }
  87342. return byteArray;
  87343. };
  87344. DDSTools._ExtractLongWordOrder = function (value) {
  87345. if (value === 0 || value === 255 || value === -16777216) {
  87346. return 0;
  87347. }
  87348. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87349. };
  87350. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87351. var byteArray = new Uint8Array(dataLength);
  87352. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87353. var index = 0;
  87354. for (var y = 0; y < height; y++) {
  87355. for (var x = 0; x < width; x++) {
  87356. var srcPos = (x + y * width) * 3;
  87357. byteArray[index] = srcData[srcPos + rOffset];
  87358. byteArray[index + 1] = srcData[srcPos + gOffset];
  87359. byteArray[index + 2] = srcData[srcPos + bOffset];
  87360. index += 3;
  87361. }
  87362. }
  87363. return byteArray;
  87364. };
  87365. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87366. var byteArray = new Uint8Array(dataLength);
  87367. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87368. var index = 0;
  87369. for (var y = 0; y < height; y++) {
  87370. for (var x = 0; x < width; x++) {
  87371. var srcPos = (x + y * width);
  87372. byteArray[index] = srcData[srcPos];
  87373. index++;
  87374. }
  87375. }
  87376. return byteArray;
  87377. };
  87378. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87379. if (lodIndex === void 0) { lodIndex = -1; }
  87380. var sphericalPolynomialFaces = null;
  87381. if (info.sphericalPolynomial) {
  87382. sphericalPolynomialFaces = new Array();
  87383. }
  87384. var ext = engine.getCaps().s3tc;
  87385. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87386. var fourCC, width, height, dataLength = 0, dataOffset;
  87387. var byteArray, mipmapCount, mip;
  87388. var internalFormat = 0;
  87389. var format = 0;
  87390. var blockBytes = 1;
  87391. if (header[off_magic] !== DDS_MAGIC) {
  87392. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87393. return;
  87394. }
  87395. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87396. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87397. return;
  87398. }
  87399. if (info.isCompressed && !ext) {
  87400. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87401. return;
  87402. }
  87403. var bpp = header[off_RGBbpp];
  87404. dataOffset = header[off_size] + 4;
  87405. var computeFormats = false;
  87406. if (info.isFourCC) {
  87407. fourCC = header[off_pfFourCC];
  87408. switch (fourCC) {
  87409. case FOURCC_DXT1:
  87410. blockBytes = 8;
  87411. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87412. break;
  87413. case FOURCC_DXT3:
  87414. blockBytes = 16;
  87415. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87416. break;
  87417. case FOURCC_DXT5:
  87418. blockBytes = 16;
  87419. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87420. break;
  87421. case FOURCC_D3DFMT_R16G16B16A16F:
  87422. computeFormats = true;
  87423. break;
  87424. case FOURCC_D3DFMT_R32G32B32A32F:
  87425. computeFormats = true;
  87426. break;
  87427. case FOURCC_DX10:
  87428. // There is an additionnal header so dataOffset need to be changed
  87429. dataOffset += 5 * 4; // 5 uints
  87430. var supported = false;
  87431. switch (info.dxgiFormat) {
  87432. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87433. computeFormats = true;
  87434. supported = true;
  87435. break;
  87436. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87437. info.isRGB = true;
  87438. info.isFourCC = false;
  87439. bpp = 32;
  87440. supported = true;
  87441. break;
  87442. }
  87443. if (supported) {
  87444. break;
  87445. }
  87446. default:
  87447. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87448. return;
  87449. }
  87450. }
  87451. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87452. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87453. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87454. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87455. if (computeFormats) {
  87456. format = engine._getWebGLTextureType(info.textureType);
  87457. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87458. }
  87459. mipmapCount = 1;
  87460. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87461. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87462. }
  87463. for (var face = 0; face < faces; face++) {
  87464. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  87465. width = header[off_width];
  87466. height = header[off_height];
  87467. for (mip = 0; mip < mipmapCount; ++mip) {
  87468. if (lodIndex === -1 || lodIndex === mip) {
  87469. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87470. var i = (lodIndex === -1) ? mip : 0;
  87471. if (!info.isCompressed && info.isFourCC) {
  87472. dataLength = width * height * 4;
  87473. var floatArray = null;
  87474. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87475. if (bpp === 128) {
  87476. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87477. if (sphericalPolynomialFaces && i == 0) {
  87478. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87479. }
  87480. }
  87481. else if (bpp === 64) {
  87482. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87483. if (sphericalPolynomialFaces && i == 0) {
  87484. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87485. }
  87486. }
  87487. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87488. format = engine._getWebGLTextureType(info.textureType);
  87489. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87490. }
  87491. else {
  87492. if (bpp === 128) {
  87493. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87494. if (sphericalPolynomialFaces && i == 0) {
  87495. sphericalPolynomialFaces.push(floatArray);
  87496. }
  87497. }
  87498. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87499. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87500. if (sphericalPolynomialFaces && i == 0) {
  87501. sphericalPolynomialFaces.push(floatArray);
  87502. }
  87503. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87504. format = engine._getWebGLTextureType(info.textureType);
  87505. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87506. }
  87507. else { // 64
  87508. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87509. if (sphericalPolynomialFaces && i == 0) {
  87510. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87511. }
  87512. }
  87513. }
  87514. if (floatArray) {
  87515. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  87516. }
  87517. }
  87518. else if (info.isRGB) {
  87519. if (bpp === 24) {
  87520. dataLength = width * height * 3;
  87521. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87522. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  87523. }
  87524. else { // 32
  87525. dataLength = width * height * 4;
  87526. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87527. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  87528. }
  87529. }
  87530. else if (info.isLuminance) {
  87531. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  87532. var unpaddedRowSize = width;
  87533. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87534. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87535. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87536. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  87537. }
  87538. else {
  87539. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87540. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87541. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  87542. }
  87543. }
  87544. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87545. width *= 0.5;
  87546. height *= 0.5;
  87547. width = Math.max(1.0, width);
  87548. height = Math.max(1.0, height);
  87549. }
  87550. if (currentFace !== undefined) {
  87551. // Loading a single face
  87552. break;
  87553. }
  87554. }
  87555. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87556. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87557. size: header[off_width],
  87558. right: sphericalPolynomialFaces[0],
  87559. left: sphericalPolynomialFaces[1],
  87560. up: sphericalPolynomialFaces[2],
  87561. down: sphericalPolynomialFaces[3],
  87562. front: sphericalPolynomialFaces[4],
  87563. back: sphericalPolynomialFaces[5],
  87564. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87565. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87566. gammaSpace: false,
  87567. });
  87568. }
  87569. else {
  87570. info.sphericalPolynomial = undefined;
  87571. }
  87572. };
  87573. DDSTools.StoreLODInAlphaChannel = false;
  87574. return DDSTools;
  87575. }());
  87576. BABYLON.DDSTools = DDSTools;
  87577. })(BABYLON || (BABYLON = {}));
  87578. //# sourceMappingURL=babylon.dds.js.map
  87579. var BABYLON;
  87580. (function (BABYLON) {
  87581. /**
  87582. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87583. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87584. */
  87585. var KhronosTextureContainer = /** @class */ (function () {
  87586. /**
  87587. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87588. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87589. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87590. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87591. */
  87592. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87593. this.arrayBuffer = arrayBuffer;
  87594. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87595. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87596. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87597. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87598. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87599. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87600. BABYLON.Tools.Error("texture missing KTX identifier");
  87601. return;
  87602. }
  87603. // load the reset of the header in native 32 bit int
  87604. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87605. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87606. var oppositeEndianess = header[0] === 0x01020304;
  87607. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87608. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87609. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87610. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87611. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87612. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87613. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87614. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87615. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87616. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87617. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87618. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87619. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87620. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87621. if (this.glType !== 0) {
  87622. BABYLON.Tools.Error("only compressed formats currently supported");
  87623. return;
  87624. }
  87625. else {
  87626. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87627. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87628. }
  87629. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87630. BABYLON.Tools.Error("only 2D textures currently supported");
  87631. return;
  87632. }
  87633. if (this.numberOfArrayElements !== 0) {
  87634. BABYLON.Tools.Error("texture arrays not currently supported");
  87635. return;
  87636. }
  87637. if (this.numberOfFaces !== facesExpected) {
  87638. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87639. return;
  87640. }
  87641. // we now have a completely validated file, so could use existence of loadType as success
  87642. // would need to make this more elaborate & adjust checks above to support more than one load type
  87643. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87644. }
  87645. // not as fast hardware based, but will probably never need to use
  87646. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87647. return ((val & 0xFF) << 24)
  87648. | ((val & 0xFF00) << 8)
  87649. | ((val >> 8) & 0xFF00)
  87650. | ((val >> 24) & 0xFF);
  87651. };
  87652. /**
  87653. * It is assumed that the texture has already been created & is currently bound
  87654. */
  87655. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  87656. switch (this.loadType) {
  87657. case KhronosTextureContainer.COMPRESSED_2D:
  87658. this._upload2DCompressedLevels(gl, loadMipmaps);
  87659. break;
  87660. case KhronosTextureContainer.TEX_2D:
  87661. case KhronosTextureContainer.COMPRESSED_3D:
  87662. case KhronosTextureContainer.TEX_3D:
  87663. }
  87664. };
  87665. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  87666. // initialize width & height for level 1
  87667. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87668. var width = this.pixelWidth;
  87669. var height = this.pixelHeight;
  87670. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87671. for (var level = 0; level < mipmapCount; level++) {
  87672. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87673. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87674. for (var face = 0; face < this.numberOfFaces; face++) {
  87675. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  87676. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87677. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  87678. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87679. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87680. }
  87681. width = Math.max(1.0, width * 0.5);
  87682. height = Math.max(1.0, height * 0.5);
  87683. }
  87684. };
  87685. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87686. // load types
  87687. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87688. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87689. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87690. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87691. return KhronosTextureContainer;
  87692. }());
  87693. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87694. })(BABYLON || (BABYLON = {}));
  87695. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87696. var BABYLON;
  87697. (function (BABYLON) {
  87698. var Debug;
  87699. (function (Debug) {
  87700. /**
  87701. * Class used to render a debug view of a given skeleton
  87702. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87703. */
  87704. var SkeletonViewer = /** @class */ (function () {
  87705. /**
  87706. * Creates a new SkeletonViewer
  87707. * @param skeleton defines the skeleton to render
  87708. * @param mesh defines the mesh attached to the skeleton
  87709. * @param scene defines the hosting scene
  87710. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87711. * @param renderingGroupId defines the rendering group id to use with the viewer
  87712. */
  87713. function SkeletonViewer(
  87714. /** defines the skeleton to render */
  87715. skeleton,
  87716. /** defines the mesh attached to the skeleton */
  87717. mesh, scene,
  87718. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87719. autoUpdateBonesMatrices,
  87720. /** defines the rendering group id to use with the viewer */
  87721. renderingGroupId) {
  87722. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87723. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87724. this.skeleton = skeleton;
  87725. this.mesh = mesh;
  87726. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87727. this.renderingGroupId = renderingGroupId;
  87728. /** Gets or sets the color used to render the skeleton */
  87729. this.color = BABYLON.Color3.White();
  87730. this._debugLines = new Array();
  87731. this._isEnabled = false;
  87732. this._scene = scene;
  87733. this.update();
  87734. this._renderFunction = this.update.bind(this);
  87735. }
  87736. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87737. get: function () {
  87738. return this._isEnabled;
  87739. },
  87740. /** Gets or sets a boolean indicating if the viewer is enabled */
  87741. set: function (value) {
  87742. if (this._isEnabled === value) {
  87743. return;
  87744. }
  87745. this._isEnabled = value;
  87746. if (value) {
  87747. this._scene.registerBeforeRender(this._renderFunction);
  87748. }
  87749. else {
  87750. this._scene.unregisterBeforeRender(this._renderFunction);
  87751. }
  87752. },
  87753. enumerable: true,
  87754. configurable: true
  87755. });
  87756. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87757. if (x === void 0) { x = 0; }
  87758. if (y === void 0) { y = 0; }
  87759. if (z === void 0) { z = 0; }
  87760. var tmat = BABYLON.Tmp.Matrix[0];
  87761. var parentBone = bone.getParent();
  87762. tmat.copyFrom(bone.getLocalMatrix());
  87763. if (x !== 0 || y !== 0 || z !== 0) {
  87764. var tmat2 = BABYLON.Tmp.Matrix[1];
  87765. BABYLON.Matrix.IdentityToRef(tmat2);
  87766. tmat2.m[12] = x;
  87767. tmat2.m[13] = y;
  87768. tmat2.m[14] = z;
  87769. tmat2.multiplyToRef(tmat, tmat);
  87770. }
  87771. if (parentBone) {
  87772. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87773. }
  87774. tmat.multiplyToRef(meshMat, tmat);
  87775. position.x = tmat.m[12];
  87776. position.y = tmat.m[13];
  87777. position.z = tmat.m[14];
  87778. };
  87779. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87780. var len = bones.length;
  87781. var meshPos = this.mesh.position;
  87782. for (var i = 0; i < len; i++) {
  87783. var bone = bones[i];
  87784. var points = this._debugLines[i];
  87785. if (!points) {
  87786. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87787. this._debugLines[i] = points;
  87788. }
  87789. this._getBonePosition(points[0], bone, meshMat);
  87790. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87791. points[0].subtractInPlace(meshPos);
  87792. points[1].subtractInPlace(meshPos);
  87793. }
  87794. };
  87795. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87796. var len = bones.length;
  87797. var boneNum = 0;
  87798. var meshPos = this.mesh.position;
  87799. for (var i = len - 1; i >= 0; i--) {
  87800. var childBone = bones[i];
  87801. var parentBone = childBone.getParent();
  87802. if (!parentBone) {
  87803. continue;
  87804. }
  87805. var points = this._debugLines[boneNum];
  87806. if (!points) {
  87807. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87808. this._debugLines[boneNum] = points;
  87809. }
  87810. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87811. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87812. points[0].subtractInPlace(meshPos);
  87813. points[1].subtractInPlace(meshPos);
  87814. boneNum++;
  87815. }
  87816. };
  87817. /** Update the viewer to sync with current skeleton state */
  87818. SkeletonViewer.prototype.update = function () {
  87819. if (this.autoUpdateBonesMatrices) {
  87820. this.skeleton.computeAbsoluteTransforms();
  87821. }
  87822. if (this.skeleton.bones[0].length === undefined) {
  87823. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87824. }
  87825. else {
  87826. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87827. }
  87828. if (!this._debugMesh) {
  87829. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87830. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87831. }
  87832. else {
  87833. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87834. }
  87835. this._debugMesh.position.copyFrom(this.mesh.position);
  87836. this._debugMesh.color = this.color;
  87837. };
  87838. /** Release associated resources */
  87839. SkeletonViewer.prototype.dispose = function () {
  87840. if (this._debugMesh) {
  87841. this.isEnabled = false;
  87842. this._debugMesh.dispose();
  87843. this._debugMesh = null;
  87844. }
  87845. };
  87846. return SkeletonViewer;
  87847. }());
  87848. Debug.SkeletonViewer = SkeletonViewer;
  87849. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87850. })(BABYLON || (BABYLON = {}));
  87851. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87852. /**
  87853. * Module Debug contains the (visual) components to debug a scene correctly
  87854. */
  87855. var BABYLON;
  87856. (function (BABYLON) {
  87857. var Debug;
  87858. (function (Debug) {
  87859. /**
  87860. * The Axes viewer will show 3 axes in a specific point in space
  87861. */
  87862. var AxesViewer = /** @class */ (function () {
  87863. /**
  87864. * Creates a new AxesViewer
  87865. * @param scene defines the hosting scene
  87866. * @param scaleLines defines a number used to scale line length (1 by default)
  87867. */
  87868. function AxesViewer(scene, scaleLines) {
  87869. if (scaleLines === void 0) { scaleLines = 1; }
  87870. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87871. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87872. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87873. /**
  87874. * Gets or sets a number used to scale line length
  87875. */
  87876. this.scaleLines = 1;
  87877. this.scaleLines = scaleLines;
  87878. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87879. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87880. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87881. this._xmesh.renderingGroupId = 2;
  87882. this._ymesh.renderingGroupId = 2;
  87883. this._zmesh.renderingGroupId = 2;
  87884. this._xmesh.material.checkReadyOnlyOnce = true;
  87885. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87886. this._ymesh.material.checkReadyOnlyOnce = true;
  87887. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87888. this._zmesh.material.checkReadyOnlyOnce = true;
  87889. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87890. this.scene = scene;
  87891. }
  87892. /**
  87893. * Force the viewer to update
  87894. * @param position defines the position of the viewer
  87895. * @param xaxis defines the x axis of the viewer
  87896. * @param yaxis defines the y axis of the viewer
  87897. * @param zaxis defines the z axis of the viewer
  87898. */
  87899. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87900. var scaleLines = this.scaleLines;
  87901. if (this._xmesh) {
  87902. this._xmesh.position.copyFrom(position);
  87903. }
  87904. if (this._ymesh) {
  87905. this._ymesh.position.copyFrom(position);
  87906. }
  87907. if (this._zmesh) {
  87908. this._zmesh.position.copyFrom(position);
  87909. }
  87910. var point2 = this._xline[1];
  87911. point2.x = xaxis.x * scaleLines;
  87912. point2.y = xaxis.y * scaleLines;
  87913. point2.z = xaxis.z * scaleLines;
  87914. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87915. point2 = this._yline[1];
  87916. point2.x = yaxis.x * scaleLines;
  87917. point2.y = yaxis.y * scaleLines;
  87918. point2.z = yaxis.z * scaleLines;
  87919. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87920. point2 = this._zline[1];
  87921. point2.x = zaxis.x * scaleLines;
  87922. point2.y = zaxis.y * scaleLines;
  87923. point2.z = zaxis.z * scaleLines;
  87924. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87925. };
  87926. /** Releases resources */
  87927. AxesViewer.prototype.dispose = function () {
  87928. if (this._xmesh) {
  87929. this._xmesh.dispose();
  87930. }
  87931. if (this._ymesh) {
  87932. this._ymesh.dispose();
  87933. }
  87934. if (this._zmesh) {
  87935. this._zmesh.dispose();
  87936. }
  87937. this._xmesh = null;
  87938. this._ymesh = null;
  87939. this._zmesh = null;
  87940. this.scene = null;
  87941. };
  87942. return AxesViewer;
  87943. }());
  87944. Debug.AxesViewer = AxesViewer;
  87945. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87946. })(BABYLON || (BABYLON = {}));
  87947. //# sourceMappingURL=babylon.axesViewer.js.map
  87948. var BABYLON;
  87949. (function (BABYLON) {
  87950. var Debug;
  87951. (function (Debug) {
  87952. /**
  87953. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87954. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87955. */
  87956. var BoneAxesViewer = /** @class */ (function (_super) {
  87957. __extends(BoneAxesViewer, _super);
  87958. /**
  87959. * Creates a new BoneAxesViewer
  87960. * @param scene defines the hosting scene
  87961. * @param bone defines the target bone
  87962. * @param mesh defines the target mesh
  87963. * @param scaleLines defines a scaling factor for line length (1 by default)
  87964. */
  87965. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87966. if (scaleLines === void 0) { scaleLines = 1; }
  87967. var _this = _super.call(this, scene, scaleLines) || this;
  87968. /** Gets current position */
  87969. _this.pos = BABYLON.Vector3.Zero();
  87970. /** Gets direction of X axis */
  87971. _this.xaxis = BABYLON.Vector3.Zero();
  87972. /** Gets direction of Y axis */
  87973. _this.yaxis = BABYLON.Vector3.Zero();
  87974. /** Gets direction of Z axis */
  87975. _this.zaxis = BABYLON.Vector3.Zero();
  87976. _this.mesh = mesh;
  87977. _this.bone = bone;
  87978. return _this;
  87979. }
  87980. /**
  87981. * Force the viewer to update
  87982. */
  87983. BoneAxesViewer.prototype.update = function () {
  87984. if (!this.mesh || !this.bone) {
  87985. return;
  87986. }
  87987. var bone = this.bone;
  87988. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87989. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87990. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87991. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87992. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87993. };
  87994. /** Releases resources */
  87995. BoneAxesViewer.prototype.dispose = function () {
  87996. if (this.mesh) {
  87997. this.mesh = null;
  87998. this.bone = null;
  87999. _super.prototype.dispose.call(this);
  88000. }
  88001. };
  88002. return BoneAxesViewer;
  88003. }(Debug.AxesViewer));
  88004. Debug.BoneAxesViewer = BoneAxesViewer;
  88005. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88006. })(BABYLON || (BABYLON = {}));
  88007. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  88008. var BABYLON;
  88009. (function (BABYLON) {
  88010. var RayHelper = /** @class */ (function () {
  88011. function RayHelper(ray) {
  88012. this.ray = ray;
  88013. }
  88014. RayHelper.CreateAndShow = function (ray, scene, color) {
  88015. var helper = new RayHelper(ray);
  88016. helper.show(scene, color);
  88017. return helper;
  88018. };
  88019. RayHelper.prototype.show = function (scene, color) {
  88020. if (!this._renderFunction && this.ray) {
  88021. var ray = this.ray;
  88022. this._renderFunction = this._render.bind(this);
  88023. this._scene = scene;
  88024. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  88025. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  88026. if (this._renderFunction) {
  88027. this._scene.registerBeforeRender(this._renderFunction);
  88028. }
  88029. }
  88030. if (color && this._renderLine) {
  88031. this._renderLine.color.copyFrom(color);
  88032. }
  88033. };
  88034. RayHelper.prototype.hide = function () {
  88035. if (this._renderFunction && this._scene) {
  88036. this._scene.unregisterBeforeRender(this._renderFunction);
  88037. this._scene = null;
  88038. this._renderFunction = null;
  88039. if (this._renderLine) {
  88040. this._renderLine.dispose();
  88041. this._renderLine = null;
  88042. }
  88043. this._renderPoints = [];
  88044. }
  88045. };
  88046. RayHelper.prototype._render = function () {
  88047. var ray = this.ray;
  88048. if (!ray) {
  88049. return;
  88050. }
  88051. var point = this._renderPoints[1];
  88052. var len = Math.min(ray.length, 1000000);
  88053. point.copyFrom(ray.direction);
  88054. point.scaleInPlace(len);
  88055. point.addInPlace(ray.origin);
  88056. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  88057. };
  88058. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  88059. this._attachedToMesh = mesh;
  88060. var ray = this.ray;
  88061. if (!ray) {
  88062. return;
  88063. }
  88064. if (!ray.direction) {
  88065. ray.direction = BABYLON.Vector3.Zero();
  88066. }
  88067. if (!ray.origin) {
  88068. ray.origin = BABYLON.Vector3.Zero();
  88069. }
  88070. if (length) {
  88071. ray.length = length;
  88072. }
  88073. if (!meshSpaceOrigin) {
  88074. meshSpaceOrigin = BABYLON.Vector3.Zero();
  88075. }
  88076. if (!meshSpaceDirection) {
  88077. // -1 so that this will work with Mesh.lookAt
  88078. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  88079. }
  88080. if (!this._meshSpaceDirection) {
  88081. this._meshSpaceDirection = meshSpaceDirection.clone();
  88082. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  88083. }
  88084. else {
  88085. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  88086. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  88087. }
  88088. if (!this._updateToMeshFunction) {
  88089. this._updateToMeshFunction = this._updateToMesh.bind(this);
  88090. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  88091. }
  88092. this._updateToMesh();
  88093. };
  88094. RayHelper.prototype.detachFromMesh = function () {
  88095. if (this._attachedToMesh) {
  88096. if (this._updateToMeshFunction) {
  88097. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  88098. }
  88099. this._attachedToMesh = null;
  88100. this._updateToMeshFunction = null;
  88101. }
  88102. };
  88103. RayHelper.prototype._updateToMesh = function () {
  88104. var ray = this.ray;
  88105. if (!this._attachedToMesh || !ray) {
  88106. return;
  88107. }
  88108. if (this._attachedToMesh._isDisposed) {
  88109. this.detachFromMesh();
  88110. return;
  88111. }
  88112. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  88113. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  88114. };
  88115. RayHelper.prototype.dispose = function () {
  88116. this.hide();
  88117. this.detachFromMesh();
  88118. this.ray = null;
  88119. };
  88120. return RayHelper;
  88121. }());
  88122. BABYLON.RayHelper = RayHelper;
  88123. })(BABYLON || (BABYLON = {}));
  88124. //# sourceMappingURL=babylon.rayHelper.js.map
  88125. var BABYLON;
  88126. (function (BABYLON) {
  88127. // load the inspector using require, if not present in the global namespace.
  88128. var DebugLayer = /** @class */ (function () {
  88129. function DebugLayer(scene) {
  88130. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88131. this._scene = scene;
  88132. // load inspector using require, if it doesn't exist on the global namespace.
  88133. }
  88134. /** Creates the inspector window. */
  88135. DebugLayer.prototype._createInspector = function (config) {
  88136. if (config === void 0) { config = {}; }
  88137. var popup = config.popup || false;
  88138. var initialTab = config.initialTab || 0;
  88139. var parentElement = config.parentElement || null;
  88140. if (!this._inspector) {
  88141. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88142. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  88143. } // else nothing to do,; instance is already existing
  88144. };
  88145. DebugLayer.prototype.isVisible = function () {
  88146. if (!this._inspector) {
  88147. return false;
  88148. }
  88149. return true;
  88150. };
  88151. DebugLayer.prototype.hide = function () {
  88152. if (this._inspector) {
  88153. try {
  88154. this._inspector.dispose();
  88155. }
  88156. catch (e) {
  88157. // If the inspector has been removed directly from the inspector tool
  88158. }
  88159. this.onPropertyChangedObservable.clear();
  88160. this._inspector = null;
  88161. }
  88162. };
  88163. /**
  88164. *
  88165. * Launch the debugLayer.
  88166. *
  88167. * initialTab:
  88168. * | Value | Tab Name |
  88169. * | --- | --- |
  88170. * | 0 | Scene |
  88171. * | 1 | Console |
  88172. * | 2 | Stats |
  88173. * | 3 | Textures |
  88174. * | 4 | Mesh |
  88175. * | 5 | Light |
  88176. * | 6 | Material |
  88177. * | 7 | GLTF |
  88178. * | 8 | GUI |
  88179. * | 9 | Physics |
  88180. * | 10 | Camera |
  88181. * | 11 | Audio |
  88182. *
  88183. */
  88184. DebugLayer.prototype.show = function (config) {
  88185. if (config === void 0) { config = {}; }
  88186. if (typeof this.BJSINSPECTOR == 'undefined') {
  88187. // Load inspector and add it to the DOM
  88188. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  88189. }
  88190. else {
  88191. // Otherwise creates the inspector
  88192. this._createInspector(config);
  88193. this.onPropertyChangedObservable = new BABYLON.Observable();
  88194. }
  88195. };
  88196. /**
  88197. * Gets the active tab
  88198. * @return the index of the active tab or -1 if the inspector is hidden
  88199. */
  88200. DebugLayer.prototype.getActiveTab = function () {
  88201. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  88202. };
  88203. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  88204. return DebugLayer;
  88205. }());
  88206. BABYLON.DebugLayer = DebugLayer;
  88207. })(BABYLON || (BABYLON = {}));
  88208. //# sourceMappingURL=babylon.debugLayer.js.map
  88209. var BABYLON;
  88210. (function (BABYLON) {
  88211. var Debug;
  88212. (function (Debug) {
  88213. /**
  88214. * Used to show the physics impostor around the specific mesh
  88215. */
  88216. var PhysicsViewer = /** @class */ (function () {
  88217. /**
  88218. * Creates a new PhysicsViewer
  88219. * @param scene defines the hosting scene
  88220. */
  88221. function PhysicsViewer(scene) {
  88222. /** @hidden */
  88223. this._impostors = [];
  88224. /** @hidden */
  88225. this._meshes = [];
  88226. /** @hidden */
  88227. this._numMeshes = 0;
  88228. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88229. var physicEngine = this._scene.getPhysicsEngine();
  88230. if (physicEngine) {
  88231. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  88232. }
  88233. }
  88234. /** @hidden */
  88235. PhysicsViewer.prototype._updateDebugMeshes = function () {
  88236. var plugin = this._physicsEnginePlugin;
  88237. for (var i = 0; i < this._numMeshes; i++) {
  88238. var impostor = this._impostors[i];
  88239. if (!impostor) {
  88240. continue;
  88241. }
  88242. if (impostor.isDisposed) {
  88243. this.hideImpostor(this._impostors[i--]);
  88244. }
  88245. else {
  88246. var mesh = this._meshes[i];
  88247. if (mesh && plugin) {
  88248. plugin.syncMeshWithImpostor(mesh, impostor);
  88249. }
  88250. }
  88251. }
  88252. };
  88253. /**
  88254. * Renders a specified physic impostor
  88255. * @param impostor defines the impostor to render
  88256. */
  88257. PhysicsViewer.prototype.showImpostor = function (impostor) {
  88258. if (!this._scene) {
  88259. return;
  88260. }
  88261. for (var i = 0; i < this._numMeshes; i++) {
  88262. if (this._impostors[i] == impostor) {
  88263. return;
  88264. }
  88265. }
  88266. var debugMesh = this._getDebugMesh(impostor, this._scene);
  88267. if (debugMesh) {
  88268. this._impostors[this._numMeshes] = impostor;
  88269. this._meshes[this._numMeshes] = debugMesh;
  88270. if (this._numMeshes === 0) {
  88271. this._renderFunction = this._updateDebugMeshes.bind(this);
  88272. this._scene.registerBeforeRender(this._renderFunction);
  88273. }
  88274. this._numMeshes++;
  88275. }
  88276. };
  88277. /**
  88278. * Hides a specified physic impostor
  88279. * @param impostor defines the impostor to hide
  88280. */
  88281. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  88282. if (!impostor || !this._scene) {
  88283. return;
  88284. }
  88285. var removed = false;
  88286. for (var i = 0; i < this._numMeshes; i++) {
  88287. if (this._impostors[i] == impostor) {
  88288. var mesh = this._meshes[i];
  88289. if (!mesh) {
  88290. continue;
  88291. }
  88292. this._scene.removeMesh(mesh);
  88293. mesh.dispose();
  88294. this._numMeshes--;
  88295. if (this._numMeshes > 0) {
  88296. this._meshes[i] = this._meshes[this._numMeshes];
  88297. this._impostors[i] = this._impostors[this._numMeshes];
  88298. this._meshes[this._numMeshes] = null;
  88299. this._impostors[this._numMeshes] = null;
  88300. }
  88301. else {
  88302. this._meshes[0] = null;
  88303. this._impostors[0] = null;
  88304. }
  88305. removed = true;
  88306. break;
  88307. }
  88308. }
  88309. if (removed && this._numMeshes === 0) {
  88310. this._scene.unregisterBeforeRender(this._renderFunction);
  88311. }
  88312. };
  88313. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  88314. if (!this._debugMaterial) {
  88315. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  88316. this._debugMaterial.wireframe = true;
  88317. }
  88318. return this._debugMaterial;
  88319. };
  88320. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  88321. if (!this._debugBoxMesh) {
  88322. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  88323. this._debugBoxMesh.renderingGroupId = 1;
  88324. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88325. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  88326. scene.removeMesh(this._debugBoxMesh);
  88327. }
  88328. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  88329. };
  88330. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  88331. if (!this._debugSphereMesh) {
  88332. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  88333. this._debugSphereMesh.renderingGroupId = 1;
  88334. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88335. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  88336. scene.removeMesh(this._debugSphereMesh);
  88337. }
  88338. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  88339. };
  88340. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  88341. var mesh = null;
  88342. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  88343. mesh = this._getDebugBoxMesh(scene);
  88344. impostor.getBoxSizeToRef(mesh.scaling);
  88345. }
  88346. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  88347. mesh = this._getDebugSphereMesh(scene);
  88348. var radius = impostor.getRadius();
  88349. mesh.scaling.x = radius * 2;
  88350. mesh.scaling.y = radius * 2;
  88351. mesh.scaling.z = radius * 2;
  88352. }
  88353. return mesh;
  88354. };
  88355. /** Releases all resources */
  88356. PhysicsViewer.prototype.dispose = function () {
  88357. for (var i = 0; i < this._numMeshes; i++) {
  88358. this.hideImpostor(this._impostors[i]);
  88359. }
  88360. if (this._debugBoxMesh) {
  88361. this._debugBoxMesh.dispose();
  88362. }
  88363. if (this._debugSphereMesh) {
  88364. this._debugSphereMesh.dispose();
  88365. }
  88366. if (this._debugMaterial) {
  88367. this._debugMaterial.dispose();
  88368. }
  88369. this._impostors.length = 0;
  88370. this._scene = null;
  88371. this._physicsEnginePlugin = null;
  88372. };
  88373. return PhysicsViewer;
  88374. }());
  88375. Debug.PhysicsViewer = PhysicsViewer;
  88376. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88377. })(BABYLON || (BABYLON = {}));
  88378. //# sourceMappingURL=babylon.physicsViewer.js.map
  88379. var BABYLON;
  88380. (function (BABYLON) {
  88381. var BoundingBoxRenderer = /** @class */ (function () {
  88382. function BoundingBoxRenderer(scene) {
  88383. this.frontColor = new BABYLON.Color3(1, 1, 1);
  88384. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  88385. this.showBackLines = true;
  88386. this.renderList = new BABYLON.SmartArray(32);
  88387. this._vertexBuffers = {};
  88388. this._scene = scene;
  88389. }
  88390. BoundingBoxRenderer.prototype._prepareRessources = function () {
  88391. if (this._colorShader) {
  88392. return;
  88393. }
  88394. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  88395. attributes: [BABYLON.VertexBuffer.PositionKind],
  88396. uniforms: ["world", "viewProjection", "color"]
  88397. });
  88398. var engine = this._scene.getEngine();
  88399. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  88400. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  88401. this._createIndexBuffer();
  88402. };
  88403. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  88404. var engine = this._scene.getEngine();
  88405. 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]);
  88406. };
  88407. BoundingBoxRenderer.prototype._rebuild = function () {
  88408. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88409. if (vb) {
  88410. vb._rebuild();
  88411. }
  88412. this._createIndexBuffer();
  88413. };
  88414. BoundingBoxRenderer.prototype.reset = function () {
  88415. this.renderList.reset();
  88416. };
  88417. BoundingBoxRenderer.prototype.render = function () {
  88418. if (this.renderList.length === 0) {
  88419. return;
  88420. }
  88421. this._prepareRessources();
  88422. if (!this._colorShader.isReady()) {
  88423. return;
  88424. }
  88425. var engine = this._scene.getEngine();
  88426. engine.setDepthWrite(false);
  88427. this._colorShader._preBind();
  88428. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  88429. var boundingBox = this.renderList.data[boundingBoxIndex];
  88430. var min = boundingBox.minimum;
  88431. var max = boundingBox.maximum;
  88432. var diff = max.subtract(min);
  88433. var median = min.add(diff.scale(0.5));
  88434. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88435. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88436. .multiply(boundingBox.getWorldMatrix());
  88437. // VBOs
  88438. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88439. if (this.showBackLines) {
  88440. // Back
  88441. engine.setDepthFunctionToGreaterOrEqual();
  88442. this._scene.resetCachedMaterial();
  88443. this._colorShader.setColor4("color", this.backColor.toColor4());
  88444. this._colorShader.bind(worldMatrix);
  88445. // Draw order
  88446. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88447. }
  88448. // Front
  88449. engine.setDepthFunctionToLess();
  88450. this._scene.resetCachedMaterial();
  88451. this._colorShader.setColor4("color", this.frontColor.toColor4());
  88452. this._colorShader.bind(worldMatrix);
  88453. // Draw order
  88454. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88455. }
  88456. this._colorShader.unbind();
  88457. engine.setDepthFunctionToLessOrEqual();
  88458. engine.setDepthWrite(true);
  88459. };
  88460. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88461. this._prepareRessources();
  88462. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88463. return;
  88464. }
  88465. var engine = this._scene.getEngine();
  88466. engine.setDepthWrite(false);
  88467. engine.setColorWrite(false);
  88468. this._colorShader._preBind();
  88469. var boundingBox = mesh._boundingInfo.boundingBox;
  88470. var min = boundingBox.minimum;
  88471. var max = boundingBox.maximum;
  88472. var diff = max.subtract(min);
  88473. var median = min.add(diff.scale(0.5));
  88474. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88475. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88476. .multiply(boundingBox.getWorldMatrix());
  88477. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88478. engine.setDepthFunctionToLess();
  88479. this._scene.resetCachedMaterial();
  88480. this._colorShader.bind(worldMatrix);
  88481. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88482. this._colorShader.unbind();
  88483. engine.setDepthFunctionToLessOrEqual();
  88484. engine.setDepthWrite(true);
  88485. engine.setColorWrite(true);
  88486. };
  88487. BoundingBoxRenderer.prototype.dispose = function () {
  88488. if (!this._colorShader) {
  88489. return;
  88490. }
  88491. this.renderList.dispose();
  88492. this._colorShader.dispose();
  88493. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88494. if (buffer) {
  88495. buffer.dispose();
  88496. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88497. }
  88498. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88499. };
  88500. return BoundingBoxRenderer;
  88501. }());
  88502. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88503. })(BABYLON || (BABYLON = {}));
  88504. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88505. var BABYLON;
  88506. (function (BABYLON) {
  88507. /**
  88508. * Renders a layer on top of an existing scene
  88509. */
  88510. var UtilityLayerRenderer = /** @class */ (function () {
  88511. /**
  88512. * Instantiates a UtilityLayerRenderer
  88513. * @param originalScene the original scene that will be rendered on top of
  88514. */
  88515. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88516. var _this = this;
  88517. this.originalScene = originalScene;
  88518. this._pointerCaptures = {};
  88519. this._lastPointerEvents = {};
  88520. /**
  88521. * If the utility layer should automatically be rendered on top of existing scene
  88522. */
  88523. this.shouldRender = true;
  88524. /**
  88525. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88526. */
  88527. this.onlyCheckPointerDownEvents = true;
  88528. /**
  88529. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88530. */
  88531. this.processAllEvents = false;
  88532. /**
  88533. * Observable raised when the pointer move from the utility layer scene to the main scene
  88534. */
  88535. this.onPointerOutObservable = new BABYLON.Observable();
  88536. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88537. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88538. originalScene.getEngine().scenes.pop();
  88539. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88540. this.utilityLayerScene.detachControl();
  88541. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88542. if (!_this.processAllEvents) {
  88543. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88544. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88545. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88546. return;
  88547. }
  88548. }
  88549. var pointerEvent = (prePointerInfo.event);
  88550. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88551. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88552. return;
  88553. }
  88554. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88555. if (!prePointerInfo.ray && utilityScenePick) {
  88556. prePointerInfo.ray = utilityScenePick.ray;
  88557. }
  88558. // always fire the prepointer oversvable
  88559. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88560. // allow every non pointer down event to flow to the utility layer
  88561. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88562. if (!prePointerInfo.skipOnPointerObservable) {
  88563. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88564. }
  88565. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88566. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88567. }
  88568. return;
  88569. }
  88570. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88571. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88572. if (utilityScenePick && utilityScenePick.hit) {
  88573. if (!prePointerInfo.skipOnPointerObservable) {
  88574. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88575. }
  88576. prePointerInfo.skipOnPointerObservable = true;
  88577. }
  88578. }
  88579. else {
  88580. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88581. var pointerEvent_1 = (prePointerInfo.event);
  88582. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88583. if (originalScenePick && utilityScenePick) {
  88584. // No pick in utility scene
  88585. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88586. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88587. // We touched an utility mesh present in the main scene
  88588. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88589. prePointerInfo.skipOnPointerObservable = true;
  88590. }
  88591. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88592. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88593. }
  88594. }
  88595. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88596. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88597. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88598. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88599. }
  88600. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88601. // We have a pick in both scenes but main is closer than utility
  88602. // We touched an utility mesh present in the main scene
  88603. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88604. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88605. prePointerInfo.skipOnPointerObservable = true;
  88606. }
  88607. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88608. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88609. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88610. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88611. }
  88612. }
  88613. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88614. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88615. }
  88616. }
  88617. }
  88618. });
  88619. // Render directly on top of existing scene without clearing
  88620. this.utilityLayerScene.autoClear = false;
  88621. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88622. if (_this.shouldRender) {
  88623. _this.render();
  88624. }
  88625. });
  88626. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88627. _this.dispose();
  88628. });
  88629. this._updateCamera();
  88630. }
  88631. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88632. get: function () {
  88633. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88634. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88635. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88636. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88637. });
  88638. }
  88639. return UtilityLayerRenderer._DefaultUtilityLayer;
  88640. },
  88641. enumerable: true,
  88642. configurable: true
  88643. });
  88644. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88645. if (!prePointerInfo.skipOnPointerObservable) {
  88646. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88647. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88648. }
  88649. };
  88650. /**
  88651. * Renders the utility layers scene on top of the original scene
  88652. */
  88653. UtilityLayerRenderer.prototype.render = function () {
  88654. this._updateCamera();
  88655. this.utilityLayerScene.render(false);
  88656. };
  88657. /**
  88658. * Disposes of the renderer
  88659. */
  88660. UtilityLayerRenderer.prototype.dispose = function () {
  88661. this.onPointerOutObservable.clear();
  88662. if (this._afterRenderObserver) {
  88663. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88664. }
  88665. if (this._sceneDisposeObserver) {
  88666. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88667. }
  88668. if (this._originalPointerObserver) {
  88669. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88670. }
  88671. this.utilityLayerScene.dispose();
  88672. };
  88673. UtilityLayerRenderer.prototype._updateCamera = function () {
  88674. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88675. };
  88676. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88677. return UtilityLayerRenderer;
  88678. }());
  88679. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88680. })(BABYLON || (BABYLON = {}));
  88681. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88682. //# sourceMappingURL=babylon.behavior.js.map
  88683. var BABYLON;
  88684. (function (BABYLON) {
  88685. /**
  88686. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88687. */
  88688. var PointerDragBehavior = /** @class */ (function () {
  88689. /**
  88690. * Creates a pointer drag behavior that can be attached to a mesh
  88691. * @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)
  88692. */
  88693. function PointerDragBehavior(options) {
  88694. this.options = options;
  88695. /**
  88696. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88697. */
  88698. this.currentDraggingPointerID = -1;
  88699. /**
  88700. * If the behavior is currently in a dragging state
  88701. */
  88702. this.dragging = false;
  88703. /**
  88704. * 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)
  88705. */
  88706. this.dragDeltaRatio = 0.2;
  88707. /**
  88708. * If the drag plane orientation should be updated during the dragging (Default: true)
  88709. */
  88710. this.updateDragPlane = true;
  88711. // Debug mode will display drag planes to help visualize behavior
  88712. this._debugMode = false;
  88713. this._moving = false;
  88714. /**
  88715. * Fires each time the attached mesh is dragged with the pointer
  88716. * * delta between last drag position and current drag position in world space
  88717. * * dragDistance along the drag axis
  88718. * * dragPlaneNormal normal of the current drag plane used during the drag
  88719. * * dragPlanePoint in world space where the drag intersects the drag plane
  88720. */
  88721. this.onDragObservable = new BABYLON.Observable();
  88722. /**
  88723. * Fires each time a drag begins (eg. mouse down on mesh)
  88724. */
  88725. this.onDragStartObservable = new BABYLON.Observable();
  88726. /**
  88727. * Fires each time a drag ends (eg. mouse release after drag)
  88728. */
  88729. this.onDragEndObservable = new BABYLON.Observable();
  88730. /**
  88731. * If the attached mesh should be moved when dragged
  88732. */
  88733. this.moveAttached = true;
  88734. /**
  88735. * If the drag behavior will react to drag events (Default: true)
  88736. */
  88737. this.enabled = true;
  88738. /**
  88739. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88740. */
  88741. this.useObjectOrienationForDragging = true;
  88742. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88743. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88744. // Variables to avoid instantiation in the below method
  88745. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88746. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88747. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88748. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88749. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88750. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88751. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88752. var optionCount = 0;
  88753. if (options === undefined) {
  88754. options = {};
  88755. }
  88756. if (options.dragAxis) {
  88757. optionCount++;
  88758. }
  88759. if (options.dragPlaneNormal) {
  88760. optionCount++;
  88761. }
  88762. if (optionCount > 1) {
  88763. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88764. }
  88765. }
  88766. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88767. /**
  88768. * The name of the behavior
  88769. */
  88770. get: function () {
  88771. return "PointerDrag";
  88772. },
  88773. enumerable: true,
  88774. configurable: true
  88775. });
  88776. /**
  88777. * Initializes the behavior
  88778. */
  88779. PointerDragBehavior.prototype.init = function () { };
  88780. /**
  88781. * Attaches the drag behavior the passed in mesh
  88782. * @param ownerNode The mesh that will be dragged around once attached
  88783. */
  88784. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88785. var _this = this;
  88786. this._scene = ownerNode.getScene();
  88787. this._attachedNode = ownerNode;
  88788. // Initialize drag plane to not interfere with existing scene
  88789. if (!PointerDragBehavior._planeScene) {
  88790. if (this._debugMode) {
  88791. PointerDragBehavior._planeScene = this._scene;
  88792. }
  88793. else {
  88794. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88795. this._scene.getEngine().scenes.pop();
  88796. }
  88797. }
  88798. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88799. // State of the drag
  88800. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88801. var delta = new BABYLON.Vector3(0, 0, 0);
  88802. var dragLength = 0;
  88803. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88804. var pickPredicate = function (m) {
  88805. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88806. };
  88807. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88808. if (!_this.enabled) {
  88809. return;
  88810. }
  88811. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88812. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88813. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88814. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88815. if (pickedPoint) {
  88816. _this.dragging = true;
  88817. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88818. _this.lastDragPosition.copyFrom(pickedPoint);
  88819. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88820. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88821. }
  88822. }
  88823. }
  88824. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88825. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88826. _this.releaseDrag();
  88827. }
  88828. }
  88829. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88830. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88831. _this._moving = true;
  88832. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88833. if (pickedPoint) {
  88834. if (_this.updateDragPlane) {
  88835. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88836. }
  88837. // depending on the drag mode option drag accordingly
  88838. if (_this.options.dragAxis) {
  88839. // Convert local drag axis to world
  88840. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88841. // Project delta drag from the drag plane onto the drag axis
  88842. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88843. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88844. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88845. }
  88846. else {
  88847. dragLength = delta.length();
  88848. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88849. }
  88850. targetPosition.addInPlace(delta);
  88851. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88852. _this.lastDragPosition.copyFrom(pickedPoint);
  88853. }
  88854. }
  88855. }
  88856. });
  88857. this._scene.onBeforeRenderObservable.add(function () {
  88858. if (_this._moving && _this.moveAttached) {
  88859. // Slowly move mesh to avoid jitter
  88860. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88861. _this._tmpVector.scaleInPlace(0.2);
  88862. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88863. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88864. }
  88865. });
  88866. };
  88867. PointerDragBehavior.prototype.releaseDrag = function () {
  88868. this.dragging = false;
  88869. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88870. this.currentDraggingPointerID = -1;
  88871. this._moving = false;
  88872. };
  88873. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88874. var _this = this;
  88875. if (!ray) {
  88876. return null;
  88877. }
  88878. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88879. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88880. return pickResult.pickedPoint;
  88881. }
  88882. else {
  88883. return null;
  88884. }
  88885. };
  88886. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88887. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88888. this._pointA.copyFrom(dragPlanePosition);
  88889. if (this.options.dragAxis) {
  88890. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  88891. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88892. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88893. ray.origin.subtractToRef(this._pointA, this._pointC);
  88894. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88895. // Get perpendicular line from direction to camera and drag axis
  88896. this._pointB.subtractToRef(this._pointA, this._lineA);
  88897. this._pointC.subtractToRef(this._pointA, this._lineB);
  88898. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88899. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88900. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88901. this._lookAt.normalize();
  88902. this._dragPlane.position.copyFrom(this._pointA);
  88903. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88904. this._dragPlane.lookAt(this._lookAt);
  88905. }
  88906. else if (this.options.dragPlaneNormal) {
  88907. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  88908. this._dragPlane.position.copyFrom(this._pointA);
  88909. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88910. this._dragPlane.lookAt(this._lookAt);
  88911. }
  88912. else {
  88913. this._dragPlane.position.copyFrom(this._pointA);
  88914. this._dragPlane.lookAt(ray.origin);
  88915. }
  88916. this._dragPlane.computeWorldMatrix(true);
  88917. };
  88918. /**
  88919. * Detaches the behavior from the mesh
  88920. */
  88921. PointerDragBehavior.prototype.detach = function () {
  88922. if (this._pointerObserver) {
  88923. this._scene.onPointerObservable.remove(this._pointerObserver);
  88924. }
  88925. };
  88926. return PointerDragBehavior;
  88927. }());
  88928. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88929. })(BABYLON || (BABYLON = {}));
  88930. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88931. var BABYLON;
  88932. (function (BABYLON) {
  88933. /**
  88934. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88935. */
  88936. var MultiPointerScaleBehavior = /** @class */ (function () {
  88937. function MultiPointerScaleBehavior() {
  88938. this._startDistance = 0;
  88939. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88940. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  88941. this._sceneRenderObserver = null;
  88942. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  88943. this._dragBehaviorA.moveAttached = false;
  88944. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  88945. this._dragBehaviorB.moveAttached = false;
  88946. }
  88947. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  88948. /**
  88949. * The name of the behavior
  88950. */
  88951. get: function () {
  88952. return "MultiPointerScale";
  88953. },
  88954. enumerable: true,
  88955. configurable: true
  88956. });
  88957. /**
  88958. * Initializes the behavior
  88959. */
  88960. MultiPointerScaleBehavior.prototype.init = function () { };
  88961. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  88962. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  88963. };
  88964. /**
  88965. * Attaches the scale behavior the passed in mesh
  88966. * @param ownerNode The mesh that will be scaled around once attached
  88967. */
  88968. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  88969. var _this = this;
  88970. this._ownerNode = ownerNode;
  88971. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  88972. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  88973. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88974. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88975. _this._dragBehaviorA.releaseDrag();
  88976. }
  88977. else {
  88978. _this._initialScale.copyFrom(ownerNode.scaling);
  88979. _this._startDistance = _this._getCurrentDistance();
  88980. }
  88981. }
  88982. });
  88983. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  88984. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88985. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88986. _this._dragBehaviorB.releaseDrag();
  88987. }
  88988. else {
  88989. _this._initialScale.copyFrom(ownerNode.scaling);
  88990. _this._startDistance = _this._getCurrentDistance();
  88991. }
  88992. }
  88993. });
  88994. // Once both drag behaviors are active scale based on the distance between the two pointers
  88995. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88996. behavior.onDragObservable.add(function () {
  88997. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88998. var ratio = _this._getCurrentDistance() / _this._startDistance;
  88999. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89000. }
  89001. });
  89002. });
  89003. ownerNode.addBehavior(this._dragBehaviorA);
  89004. ownerNode.addBehavior(this._dragBehaviorB);
  89005. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89006. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89007. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89008. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89009. if (change.length() > 0.01) {
  89010. ownerNode.scaling.addInPlace(change);
  89011. }
  89012. }
  89013. });
  89014. };
  89015. /**
  89016. * Detaches the behavior from the mesh
  89017. */
  89018. MultiPointerScaleBehavior.prototype.detach = function () {
  89019. var _this = this;
  89020. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89021. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89022. behavior.onDragStartObservable.clear();
  89023. behavior.onDragObservable.clear();
  89024. _this._ownerNode.removeBehavior(behavior);
  89025. });
  89026. };
  89027. return MultiPointerScaleBehavior;
  89028. }());
  89029. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89030. })(BABYLON || (BABYLON = {}));
  89031. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89032. var BABYLON;
  89033. (function (BABYLON) {
  89034. /**
  89035. * 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
  89036. */
  89037. var SixDofDragBehavior = /** @class */ (function () {
  89038. function SixDofDragBehavior() {
  89039. this._sceneRenderObserver = null;
  89040. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89041. this._moving = false;
  89042. this._startingOrientation = new BABYLON.Quaternion();
  89043. /**
  89044. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 5)
  89045. */
  89046. this.zDragFactor = 5;
  89047. /**
  89048. * If the behavior is currently in a dragging state
  89049. */
  89050. this.dragging = false;
  89051. /**
  89052. * 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)
  89053. */
  89054. this.dragDeltaRatio = 0.2;
  89055. /**
  89056. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89057. */
  89058. this.currentDraggingPointerID = -1;
  89059. }
  89060. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89061. /**
  89062. * The name of the behavior
  89063. */
  89064. get: function () {
  89065. return "SixDofDrag";
  89066. },
  89067. enumerable: true,
  89068. configurable: true
  89069. });
  89070. /**
  89071. * Initializes the behavior
  89072. */
  89073. SixDofDragBehavior.prototype.init = function () { };
  89074. /**
  89075. * Attaches the scale behavior the passed in mesh
  89076. * @param ownerNode The mesh that will be scaled around once attached
  89077. */
  89078. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89079. var _this = this;
  89080. this._ownerNode = ownerNode;
  89081. this._scene = this._ownerNode.getScene();
  89082. if (!SixDofDragBehavior._virtualScene) {
  89083. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89084. this._scene.getEngine().scenes.pop();
  89085. }
  89086. var pickedMesh = null;
  89087. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89088. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89089. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89090. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89091. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89092. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89093. var pickPredicate = function (m) {
  89094. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89095. };
  89096. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89097. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89098. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89099. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  89100. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89101. // Set position and orientation of the controller
  89102. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89103. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89104. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89105. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89106. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89107. if (!pickedMesh.rotationQuaternion) {
  89108. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89109. }
  89110. var oldParent = pickedMesh.parent;
  89111. pickedMesh.setParent(null);
  89112. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89113. pickedMesh.setParent(oldParent);
  89114. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89115. // Update state
  89116. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89117. _this.dragging = true;
  89118. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89119. }
  89120. }
  89121. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89122. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89123. _this.dragging = false;
  89124. _this._moving = false;
  89125. _this.currentDraggingPointerID = -1;
  89126. pickedMesh = null;
  89127. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89128. }
  89129. }
  89130. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89131. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89132. // Calculate controller drag distance in controller space
  89133. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89134. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89135. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  89136. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89137. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89138. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  89139. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  89140. if (_this._virtualDragMesh.position.z < 0) {
  89141. _this._virtualDragMesh.position.z = 0;
  89142. }
  89143. // Update the controller position
  89144. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89145. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89146. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89147. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89148. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89149. if (pickedMesh.parent) {
  89150. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89151. }
  89152. if (!_this._moving) {
  89153. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89154. }
  89155. _this._moving = true;
  89156. }
  89157. }
  89158. });
  89159. var tmpQuaternion = new BABYLON.Quaternion();
  89160. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89161. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89162. if (_this.dragging && _this._moving && pickedMesh) {
  89163. // Slowly move mesh to avoid jitter
  89164. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89165. // Get change in rotation
  89166. tmpQuaternion.copyFrom(_this._startingOrientation);
  89167. tmpQuaternion.x = -tmpQuaternion.x;
  89168. tmpQuaternion.y = -tmpQuaternion.y;
  89169. tmpQuaternion.z = -tmpQuaternion.z;
  89170. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89171. // Convert change in rotation to only y axis rotation
  89172. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89173. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89174. // Slowly move mesh to avoid jitter
  89175. var oldParent = pickedMesh.parent;
  89176. pickedMesh.setParent(null);
  89177. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89178. pickedMesh.setParent(oldParent);
  89179. }
  89180. });
  89181. };
  89182. /**
  89183. * Detaches the behavior from the mesh
  89184. */
  89185. SixDofDragBehavior.prototype.detach = function () {
  89186. this._scene.onPointerObservable.remove(this._pointerObserver);
  89187. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89188. this._virtualOriginMesh.dispose();
  89189. this._virtualDragMesh.dispose();
  89190. };
  89191. return SixDofDragBehavior;
  89192. }());
  89193. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89194. })(BABYLON || (BABYLON = {}));
  89195. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89196. var BABYLON;
  89197. (function (BABYLON) {
  89198. /**
  89199. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89200. */
  89201. var Gizmo = /** @class */ (function () {
  89202. /**
  89203. * Creates a gizmo
  89204. * @param gizmoLayer The utility layer the gizmo will be added to
  89205. */
  89206. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89207. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89208. var _this = this;
  89209. this.gizmoLayer = gizmoLayer;
  89210. this._scaleFactor = 3;
  89211. /**
  89212. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89213. */
  89214. this.updateGizmoRotationToMatchAttachedMesh = true;
  89215. /**
  89216. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89217. */
  89218. this.updateGizmoPositionToMatchAttachedMesh = true;
  89219. /**
  89220. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89221. */
  89222. this._updateScale = true;
  89223. this._interactionsEnabled = true;
  89224. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89225. var tempVector = new BABYLON.Vector3();
  89226. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89227. if (_this.attachedMesh) {
  89228. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89229. if (!_this._rootMesh.rotationQuaternion) {
  89230. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  89231. }
  89232. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  89233. }
  89234. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89235. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89236. }
  89237. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89238. _this._rootMesh.position.subtractToRef(_this.gizmoLayer.utilityLayerScene.activeCamera.position, tempVector);
  89239. var dist = tempVector.length() / _this._scaleFactor;
  89240. _this._rootMesh.scaling.set(dist, dist, dist);
  89241. }
  89242. }
  89243. });
  89244. this.attachedMesh = null;
  89245. }
  89246. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89247. /**
  89248. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89249. * * When set, interactions will be enabled
  89250. */
  89251. get: function () {
  89252. return this._attachedMesh;
  89253. },
  89254. set: function (value) {
  89255. this._attachedMesh = value;
  89256. this._rootMesh.setEnabled(value ? true : false);
  89257. this._attachedMeshChanged(value);
  89258. },
  89259. enumerable: true,
  89260. configurable: true
  89261. });
  89262. Gizmo.prototype._attachedMeshChanged = function (value) {
  89263. };
  89264. /**
  89265. * Disposes of the gizmo
  89266. */
  89267. Gizmo.prototype.dispose = function () {
  89268. this._rootMesh.dispose();
  89269. if (this._beforeRenderObserver) {
  89270. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89271. }
  89272. };
  89273. return Gizmo;
  89274. }());
  89275. BABYLON.Gizmo = Gizmo;
  89276. })(BABYLON || (BABYLON = {}));
  89277. //# sourceMappingURL=babylon.gizmo.js.map
  89278. var BABYLON;
  89279. (function (BABYLON) {
  89280. /**
  89281. * Single axis drag gizmo
  89282. */
  89283. var AxisDragGizmo = /** @class */ (function (_super) {
  89284. __extends(AxisDragGizmo, _super);
  89285. /**
  89286. * Creates an AxisDragGizmo
  89287. * @param gizmoLayer The utility layer the gizmo will be added to
  89288. * @param dragAxis The axis which the gizmo will be able to drag on
  89289. * @param color The color of the gizmo
  89290. */
  89291. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89292. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89293. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89294. var _this = _super.call(this, gizmoLayer) || this;
  89295. _this._pointerObserver = null;
  89296. /**
  89297. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89298. */
  89299. _this.snapDistance = 0;
  89300. /**
  89301. * Event that fires each time the gizmo snaps to a new location.
  89302. * * snapDistance is the the change in distance
  89303. */
  89304. _this.onSnapObservable = new BABYLON.Observable();
  89305. // Create Material
  89306. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89307. coloredMaterial.disableLighting = true;
  89308. coloredMaterial.emissiveColor = color;
  89309. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89310. hoverMaterial.disableLighting = true;
  89311. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89312. // Build mesh on root node
  89313. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89314. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89315. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89316. arrow.addChild(arrowMesh);
  89317. arrow.addChild(arrowTail);
  89318. // Position arrow pointing in its drag axis
  89319. arrowMesh.scaling.scaleInPlace(0.05);
  89320. arrowMesh.material = coloredMaterial;
  89321. arrowMesh.rotation.x = Math.PI / 2;
  89322. arrowMesh.position.z += 0.3;
  89323. arrowTail.rotation.x = Math.PI / 2;
  89324. arrowTail.material = coloredMaterial;
  89325. arrowTail.position.z += 0.15;
  89326. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89327. _this._rootMesh.addChild(arrow);
  89328. var currentSnapDragDistance = 0;
  89329. var tmpVector = new BABYLON.Vector3();
  89330. var tmpSnapEvent = { snapDistance: 0 };
  89331. // Add drag behavior to handle events when the gizmo is dragged
  89332. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89333. _this.dragBehavior.moveAttached = false;
  89334. _this._rootMesh.addBehavior(_this.dragBehavior);
  89335. _this.dragBehavior.onDragObservable.add(function (event) {
  89336. if (_this.attachedMesh) {
  89337. // Snapping logic
  89338. if (_this.snapDistance == 0) {
  89339. _this.attachedMesh.position.addInPlace(event.delta);
  89340. }
  89341. else {
  89342. currentSnapDragDistance += event.dragDistance;
  89343. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89344. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89345. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89346. event.delta.normalizeToRef(tmpVector);
  89347. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89348. _this.attachedMesh.position.addInPlace(tmpVector);
  89349. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89350. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89351. }
  89352. }
  89353. }
  89354. });
  89355. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89356. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89357. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89358. m.material = hoverMaterial;
  89359. });
  89360. }
  89361. else {
  89362. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89363. m.material = coloredMaterial;
  89364. });
  89365. }
  89366. });
  89367. return _this;
  89368. }
  89369. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89370. if (this.dragBehavior) {
  89371. this.dragBehavior.enabled = value ? true : false;
  89372. }
  89373. };
  89374. /**
  89375. * Disposes of the gizmo
  89376. */
  89377. AxisDragGizmo.prototype.dispose = function () {
  89378. this.onSnapObservable.clear();
  89379. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89380. this.dragBehavior.detach();
  89381. _super.prototype.dispose.call(this);
  89382. };
  89383. return AxisDragGizmo;
  89384. }(BABYLON.Gizmo));
  89385. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89386. })(BABYLON || (BABYLON = {}));
  89387. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89388. var BABYLON;
  89389. (function (BABYLON) {
  89390. /**
  89391. * Single axis scale gizmo
  89392. */
  89393. var AxisScaleGizmo = /** @class */ (function (_super) {
  89394. __extends(AxisScaleGizmo, _super);
  89395. /**
  89396. * Creates an AxisScaleGizmo
  89397. * @param gizmoLayer The utility layer the gizmo will be added to
  89398. * @param dragAxis The axis which the gizmo will be able to scale on
  89399. * @param color The color of the gizmo
  89400. */
  89401. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89402. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89403. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89404. var _this = _super.call(this, gizmoLayer) || this;
  89405. _this._pointerObserver = null;
  89406. /**
  89407. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89408. */
  89409. _this.snapDistance = 0;
  89410. /**
  89411. * Event that fires each time the gizmo snaps to a new location.
  89412. * * snapDistance is the the change in distance
  89413. */
  89414. _this.onSnapObservable = new BABYLON.Observable();
  89415. // Create Material
  89416. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89417. coloredMaterial.disableLighting = true;
  89418. coloredMaterial.emissiveColor = color;
  89419. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89420. hoverMaterial.disableLighting = true;
  89421. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89422. // Build mesh on root node
  89423. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89424. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89425. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89426. arrow.addChild(arrowMesh);
  89427. arrow.addChild(arrowTail);
  89428. // Position arrow pointing in its drag axis
  89429. arrowMesh.scaling.scaleInPlace(0.1);
  89430. arrowMesh.material = coloredMaterial;
  89431. arrowMesh.rotation.x = Math.PI / 2;
  89432. arrowMesh.position.z += 0.3;
  89433. arrowTail.rotation.x = Math.PI / 2;
  89434. arrowTail.material = coloredMaterial;
  89435. arrowTail.position.z += 0.15;
  89436. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89437. _this._rootMesh.addChild(arrow);
  89438. // Add drag behavior to handle events when the gizmo is dragged
  89439. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89440. _this.dragBehavior.moveAttached = false;
  89441. _this._rootMesh.addBehavior(_this.dragBehavior);
  89442. var currentSnapDragDistance = 0;
  89443. var tmpVector = new BABYLON.Vector3();
  89444. var tmpSnapEvent = { snapDistance: 0 };
  89445. _this.dragBehavior.onDragObservable.add(function (event) {
  89446. if (_this.attachedMesh) {
  89447. // Snapping logic
  89448. var snapped = false;
  89449. var dragSteps = 0;
  89450. if (_this.snapDistance == 0) {
  89451. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89452. }
  89453. else {
  89454. currentSnapDragDistance += event.dragDistance;
  89455. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89456. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89457. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89458. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89459. snapped = true;
  89460. }
  89461. else {
  89462. tmpVector.scaleInPlace(0);
  89463. }
  89464. }
  89465. var invertCount = 0;
  89466. if (_this.attachedMesh.scaling["x"] < 0) {
  89467. invertCount++;
  89468. }
  89469. if (_this.attachedMesh.scaling["y"] < 0) {
  89470. invertCount++;
  89471. }
  89472. if (_this.attachedMesh.scaling["z"] < 0) {
  89473. invertCount++;
  89474. }
  89475. if (invertCount % 2 == 0) {
  89476. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89477. }
  89478. else {
  89479. _this.attachedMesh.scaling.subtractInPlace(tmpVector);
  89480. }
  89481. if (snapped) {
  89482. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89483. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89484. }
  89485. }
  89486. });
  89487. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89488. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89489. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89490. m.material = hoverMaterial;
  89491. });
  89492. }
  89493. else {
  89494. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89495. m.material = coloredMaterial;
  89496. });
  89497. }
  89498. });
  89499. return _this;
  89500. }
  89501. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89502. if (this.dragBehavior) {
  89503. this.dragBehavior.enabled = value ? true : false;
  89504. }
  89505. };
  89506. /**
  89507. * Disposes of the gizmo
  89508. */
  89509. AxisScaleGizmo.prototype.dispose = function () {
  89510. this.onSnapObservable.clear();
  89511. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89512. this.dragBehavior.detach();
  89513. _super.prototype.dispose.call(this);
  89514. };
  89515. return AxisScaleGizmo;
  89516. }(BABYLON.Gizmo));
  89517. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89518. })(BABYLON || (BABYLON = {}));
  89519. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89520. var BABYLON;
  89521. (function (BABYLON) {
  89522. /**
  89523. * Single plane rotation gizmo
  89524. */
  89525. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89526. __extends(PlaneRotationGizmo, _super);
  89527. /**
  89528. * Creates a PlaneRotationGizmo
  89529. * @param gizmoLayer The utility layer the gizmo will be added to
  89530. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89531. * @param color The color of the gizmo
  89532. */
  89533. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89534. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89535. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89536. var _this = _super.call(this, gizmoLayer) || this;
  89537. _this._pointerObserver = null;
  89538. /**
  89539. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89540. */
  89541. _this.snapDistance = 0;
  89542. /**
  89543. * Event that fires each time the gizmo snaps to a new location.
  89544. * * snapDistance is the the change in distance
  89545. */
  89546. _this.onSnapObservable = new BABYLON.Observable();
  89547. // Create Material
  89548. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89549. coloredMaterial.disableLighting = true;
  89550. coloredMaterial.emissiveColor = color;
  89551. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89552. hoverMaterial.disableLighting = true;
  89553. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89554. // Build mesh on root node
  89555. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89556. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89557. // Position arrow pointing in its drag axis
  89558. rotationMesh.scaling.scaleInPlace(0.1);
  89559. rotationMesh.material = coloredMaterial;
  89560. rotationMesh.rotation.x = Math.PI / 2;
  89561. parentMesh.addChild(rotationMesh);
  89562. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89563. _this._rootMesh.addChild(parentMesh);
  89564. // Add drag behavior to handle events when the gizmo is dragged
  89565. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89566. _this.dragBehavior.moveAttached = false;
  89567. _this._rootMesh.addBehavior(_this.dragBehavior);
  89568. var lastDragPosition = null;
  89569. _this.dragBehavior.onDragStartObservable.add(function (e) {
  89570. if (_this.attachedMesh) {
  89571. lastDragPosition = e.dragPlanePoint;
  89572. }
  89573. });
  89574. var rotationMatrix = new BABYLON.Matrix();
  89575. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89576. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89577. var tmpSnapEvent = { snapDistance: 0 };
  89578. var currentSnapDragDistance = 0;
  89579. _this.dragBehavior.onDragObservable.add(function (event) {
  89580. if (_this.attachedMesh && lastDragPosition) {
  89581. if (!_this.attachedMesh.rotationQuaternion) {
  89582. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  89583. }
  89584. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89585. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89586. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89587. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89588. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89589. var angle = Math.atan2(cross.length(), dot);
  89590. planeNormalTowardsCamera.copyFrom(planeNormal);
  89591. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89592. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89593. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89594. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89595. }
  89596. // Flip up vector depending on which side the camera is on
  89597. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89598. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89599. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89600. planeNormalTowardsCamera.scaleInPlace(-1);
  89601. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89602. }
  89603. }
  89604. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89605. if (halfCircleSide)
  89606. angle = -angle;
  89607. // Snapping logic
  89608. var snapped = false;
  89609. if (_this.snapDistance != 0) {
  89610. currentSnapDragDistance += angle;
  89611. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89612. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89613. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89614. angle = _this.snapDistance * dragSteps;
  89615. snapped = true;
  89616. }
  89617. else {
  89618. angle = 0;
  89619. }
  89620. }
  89621. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89622. var quaternionCoefficient = Math.sin(angle / 2);
  89623. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89624. // Rotate selected mesh quaternion over fixed axis
  89625. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89626. lastDragPosition = event.dragPlanePoint;
  89627. if (snapped) {
  89628. tmpSnapEvent.snapDistance = angle;
  89629. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89630. }
  89631. }
  89632. });
  89633. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89634. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89635. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89636. m.material = hoverMaterial;
  89637. });
  89638. }
  89639. else {
  89640. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89641. m.material = coloredMaterial;
  89642. });
  89643. }
  89644. });
  89645. return _this;
  89646. }
  89647. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89648. if (this.dragBehavior) {
  89649. this.dragBehavior.enabled = value ? true : false;
  89650. }
  89651. };
  89652. /**
  89653. * Disposes of the gizmo
  89654. */
  89655. PlaneRotationGizmo.prototype.dispose = function () {
  89656. this.onSnapObservable.clear();
  89657. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89658. this.dragBehavior.detach();
  89659. _super.prototype.dispose.call(this);
  89660. };
  89661. return PlaneRotationGizmo;
  89662. }(BABYLON.Gizmo));
  89663. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89664. })(BABYLON || (BABYLON = {}));
  89665. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89666. var BABYLON;
  89667. (function (BABYLON) {
  89668. /**
  89669. * Gizmo that enables dragging a mesh along 3 axis
  89670. */
  89671. var PositionGizmo = /** @class */ (function (_super) {
  89672. __extends(PositionGizmo, _super);
  89673. /**
  89674. * Creates a PositionGizmo
  89675. * @param gizmoLayer The utility layer the gizmo will be added to
  89676. */
  89677. function PositionGizmo(gizmoLayer) {
  89678. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89679. var _this = _super.call(this, gizmoLayer) || this;
  89680. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89681. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89682. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89683. _this.attachedMesh = null;
  89684. return _this;
  89685. }
  89686. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89687. set: function (mesh) {
  89688. if (this.xGizmo) {
  89689. this.xGizmo.attachedMesh = mesh;
  89690. this.yGizmo.attachedMesh = mesh;
  89691. this.zGizmo.attachedMesh = mesh;
  89692. }
  89693. },
  89694. enumerable: true,
  89695. configurable: true
  89696. });
  89697. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89698. get: function () {
  89699. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89700. },
  89701. set: function (value) {
  89702. if (this.xGizmo) {
  89703. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89704. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89705. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89706. }
  89707. },
  89708. enumerable: true,
  89709. configurable: true
  89710. });
  89711. /**
  89712. * Disposes of the gizmo
  89713. */
  89714. PositionGizmo.prototype.dispose = function () {
  89715. this.xGizmo.dispose();
  89716. this.yGizmo.dispose();
  89717. this.zGizmo.dispose();
  89718. };
  89719. return PositionGizmo;
  89720. }(BABYLON.Gizmo));
  89721. BABYLON.PositionGizmo = PositionGizmo;
  89722. })(BABYLON || (BABYLON = {}));
  89723. //# sourceMappingURL=babylon.positionGizmo.js.map
  89724. var BABYLON;
  89725. (function (BABYLON) {
  89726. /**
  89727. * Gizmo that enables rotating a mesh along 3 axis
  89728. */
  89729. var RotationGizmo = /** @class */ (function (_super) {
  89730. __extends(RotationGizmo, _super);
  89731. /**
  89732. * Creates a RotationGizmo
  89733. * @param gizmoLayer The utility layer the gizmo will be added to
  89734. */
  89735. function RotationGizmo(gizmoLayer) {
  89736. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89737. var _this = _super.call(this, gizmoLayer) || this;
  89738. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89739. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89740. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89741. _this.attachedMesh = null;
  89742. return _this;
  89743. }
  89744. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  89745. set: function (mesh) {
  89746. if (this.xGizmo) {
  89747. this.xGizmo.attachedMesh = mesh;
  89748. this.yGizmo.attachedMesh = mesh;
  89749. this.zGizmo.attachedMesh = mesh;
  89750. }
  89751. },
  89752. enumerable: true,
  89753. configurable: true
  89754. });
  89755. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89756. get: function () {
  89757. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89758. },
  89759. set: function (value) {
  89760. if (this.xGizmo) {
  89761. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89762. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89763. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89764. }
  89765. },
  89766. enumerable: true,
  89767. configurable: true
  89768. });
  89769. /**
  89770. * Disposes of the gizmo
  89771. */
  89772. RotationGizmo.prototype.dispose = function () {
  89773. this.xGizmo.dispose();
  89774. this.yGizmo.dispose();
  89775. this.zGizmo.dispose();
  89776. };
  89777. return RotationGizmo;
  89778. }(BABYLON.Gizmo));
  89779. BABYLON.RotationGizmo = RotationGizmo;
  89780. })(BABYLON || (BABYLON = {}));
  89781. //# sourceMappingURL=babylon.rotationGizmo.js.map
  89782. var BABYLON;
  89783. (function (BABYLON) {
  89784. /**
  89785. * Gizmo that enables scaling a mesh along 3 axis
  89786. */
  89787. var ScaleGizmo = /** @class */ (function (_super) {
  89788. __extends(ScaleGizmo, _super);
  89789. /**
  89790. * Creates a ScaleGizmo
  89791. * @param gizmoLayer The utility layer the gizmo will be added to
  89792. */
  89793. function ScaleGizmo(gizmoLayer) {
  89794. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89795. var _this = _super.call(this, gizmoLayer) || this;
  89796. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89797. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89798. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89799. _this.attachedMesh = null;
  89800. return _this;
  89801. }
  89802. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  89803. set: function (mesh) {
  89804. if (this.xGizmo) {
  89805. this.xGizmo.attachedMesh = mesh;
  89806. this.yGizmo.attachedMesh = mesh;
  89807. this.zGizmo.attachedMesh = mesh;
  89808. }
  89809. },
  89810. enumerable: true,
  89811. configurable: true
  89812. });
  89813. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89814. get: function () {
  89815. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89816. },
  89817. set: function (value) {
  89818. if (this.xGizmo) {
  89819. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89820. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89821. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89822. }
  89823. },
  89824. enumerable: true,
  89825. configurable: true
  89826. });
  89827. /**
  89828. * Disposes of the gizmo
  89829. */
  89830. ScaleGizmo.prototype.dispose = function () {
  89831. this.xGizmo.dispose();
  89832. this.yGizmo.dispose();
  89833. this.zGizmo.dispose();
  89834. };
  89835. return ScaleGizmo;
  89836. }(BABYLON.Gizmo));
  89837. BABYLON.ScaleGizmo = ScaleGizmo;
  89838. })(BABYLON || (BABYLON = {}));
  89839. //# sourceMappingURL=babylon.scaleGizmo.js.map
  89840. var BABYLON;
  89841. (function (BABYLON) {
  89842. /**
  89843. * Bounding box gizmo
  89844. */
  89845. var BoundingBoxGizmo = /** @class */ (function (_super) {
  89846. __extends(BoundingBoxGizmo, _super);
  89847. /**
  89848. * Creates an BoundingBoxGizmo
  89849. * @param gizmoLayer The utility layer the gizmo will be added to
  89850. * @param color The color of the gizmo
  89851. */
  89852. function BoundingBoxGizmo(color, gizmoLayer) {
  89853. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89854. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89855. var _this = _super.call(this, gizmoLayer) || this;
  89856. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  89857. _this._renderObserver = null;
  89858. _this._pointerObserver = null;
  89859. _this._scaleDragSpeed = 0.2;
  89860. _this._tmpQuaternion = new BABYLON.Quaternion();
  89861. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89862. /**
  89863. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  89864. */
  89865. _this.rotationSphereSize = 0.1;
  89866. /**
  89867. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  89868. */
  89869. _this.scaleBoxSize = 0.1;
  89870. /**
  89871. * 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)
  89872. */
  89873. _this.fixedDragMeshScreenSize = false;
  89874. /**
  89875. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  89876. */
  89877. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  89878. /**
  89879. * Fired when a rotation sphere or scale box is dragged
  89880. */
  89881. _this.onDragStartObservable = new BABYLON.Observable();
  89882. /**
  89883. * Fired when a rotation sphere or scale box drag is started
  89884. */
  89885. _this.onDragObservable = new BABYLON.Observable();
  89886. /**
  89887. * Fired when a rotation sphere or scale box drag is needed
  89888. */
  89889. _this.onDragEndObservable = new BABYLON.Observable();
  89890. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  89891. _this._updateScale = false;
  89892. // Create Materials
  89893. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89894. coloredMaterial.disableLighting = true;
  89895. coloredMaterial.emissiveColor = color;
  89896. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89897. hoverColoredMaterial.disableLighting = true;
  89898. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89899. // Build bounding box out of lines
  89900. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89901. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  89902. var lines = [];
  89903. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  89904. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89905. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89906. 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));
  89907. 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));
  89908. 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));
  89909. 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));
  89910. 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));
  89911. 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));
  89912. 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));
  89913. 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));
  89914. 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));
  89915. lines.forEach(function (l) {
  89916. l.color = color;
  89917. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  89918. l.isPickable = false;
  89919. _this._lineBoundingBox.addChild(l);
  89920. });
  89921. _this._rootMesh.addChild(_this._lineBoundingBox);
  89922. // Create rotation spheres
  89923. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89924. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  89925. var _loop_1 = function (i_1) {
  89926. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  89927. sphere.rotationQuaternion = new BABYLON.Quaternion();
  89928. sphere.material = coloredMaterial;
  89929. // Drag behavior
  89930. _dragBehavior = new BABYLON.PointerDragBehavior({});
  89931. _dragBehavior.moveAttached = false;
  89932. _dragBehavior.updateDragPlane = false;
  89933. sphere.addBehavior(_dragBehavior);
  89934. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  89935. var totalTurnAmountOfDrag = 0;
  89936. _dragBehavior.onDragStartObservable.add(function (event) {
  89937. startingTurnDirection.copyFrom(sphere.forward);
  89938. totalTurnAmountOfDrag = 0;
  89939. });
  89940. _dragBehavior.onDragObservable.add(function (event) {
  89941. _this.onDragObservable.notifyObservers({});
  89942. if (_this.attachedMesh) {
  89943. var worldDragDirection = startingTurnDirection;
  89944. // Project the world right on to the drag plane
  89945. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  89946. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  89947. // project drag delta on to the resulting drag axis and rotate based on that
  89948. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  89949. // Rotate based on axis
  89950. if (!_this.attachedMesh.rotationQuaternion) {
  89951. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89952. }
  89953. // Do not allow the object to turn more than a full circle
  89954. totalTurnAmountOfDrag += projectDist;
  89955. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  89956. if (i_1 >= 8) {
  89957. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  89958. }
  89959. else if (i_1 >= 4) {
  89960. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  89961. }
  89962. else {
  89963. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  89964. }
  89965. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  89966. }
  89967. }
  89968. });
  89969. // Selection/deselection
  89970. _dragBehavior.onDragStartObservable.add(function () {
  89971. _this.onDragStartObservable.notifyObservers({});
  89972. _this._selectNode(sphere);
  89973. });
  89974. _dragBehavior.onDragEndObservable.add(function () {
  89975. _this.onDragEndObservable.notifyObservers({});
  89976. _this._selectNode(null);
  89977. });
  89978. this_1._rotateSpheresParent.addChild(sphere);
  89979. };
  89980. var this_1 = this, _dragBehavior;
  89981. for (var i_1 = 0; i_1 < 12; i_1++) {
  89982. _loop_1(i_1);
  89983. }
  89984. _this._rootMesh.addChild(_this._rotateSpheresParent);
  89985. // Create scale cubes
  89986. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89987. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  89988. for (var i = 0; i < 2; i++) {
  89989. for (var j = 0; j < 2; j++) {
  89990. var _loop_2 = function () {
  89991. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  89992. box.material = coloredMaterial;
  89993. // Dragging logic
  89994. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  89995. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89996. _dragBehavior.moveAttached = false;
  89997. box.addBehavior(_dragBehavior);
  89998. _dragBehavior.onDragObservable.add(function (event) {
  89999. _this.onDragObservable.notifyObservers({});
  90000. if (_this.attachedMesh) {
  90001. // Current boudning box dimensions
  90002. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  90003. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  90004. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  90005. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90006. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90007. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  90008. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  90009. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  90010. // Update scale and position
  90011. _this.attachedMesh.scaling.addInPlace(deltaScale);
  90012. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  90013. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  90014. }
  90015. });
  90016. // Selection/deselection
  90017. _dragBehavior.onDragStartObservable.add(function () {
  90018. _this.onDragStartObservable.notifyObservers({});
  90019. _this._selectNode(box);
  90020. });
  90021. _dragBehavior.onDragEndObservable.add(function () {
  90022. _this.onDragEndObservable.notifyObservers({});
  90023. _this._selectNode(null);
  90024. });
  90025. this_2._scaleBoxesParent.addChild(box);
  90026. };
  90027. var this_2 = this, _dragBehavior;
  90028. for (var k = 0; k < 2; k++) {
  90029. _loop_2();
  90030. }
  90031. }
  90032. }
  90033. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90034. // Hover color change
  90035. var pointerIds = new Array();
  90036. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90037. if (!pointerIds[pointerInfo.event.pointerId]) {
  90038. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90039. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90040. pointerIds[pointerInfo.event.pointerId] = mesh;
  90041. mesh.material = hoverColoredMaterial;
  90042. }
  90043. });
  90044. }
  90045. else {
  90046. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90047. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90048. delete pointerIds[pointerInfo.event.pointerId];
  90049. }
  90050. }
  90051. });
  90052. // Update bounding box positions
  90053. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90054. _this._updateBoundingBox();
  90055. });
  90056. _this._updateBoundingBox();
  90057. return _this;
  90058. }
  90059. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90060. this._rotateSpheresParent.getChildMeshes()
  90061. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90062. m.isVisible = (!selectedMesh || m == selectedMesh);
  90063. });
  90064. };
  90065. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  90066. if (this.attachedMesh) {
  90067. // Update bounding dimensions/positions
  90068. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  90069. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  90070. this._boundingDimensions.copyFrom(boundBoxDimensions);
  90071. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90072. }
  90073. // Update rotation sphere locations
  90074. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90075. for (var i = 0; i < 3; i++) {
  90076. for (var j = 0; j < 2; j++) {
  90077. for (var k = 0; k < 2; k++) {
  90078. var index = ((i * 4) + (j * 2)) + k;
  90079. if (i == 0) {
  90080. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90081. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90082. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90083. }
  90084. if (i == 1) {
  90085. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90086. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90087. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90088. }
  90089. if (i == 2) {
  90090. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90091. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90092. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90093. }
  90094. if (this.fixedDragMeshScreenSize) {
  90095. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90096. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90097. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90098. }
  90099. else {
  90100. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90101. }
  90102. }
  90103. }
  90104. }
  90105. // Update scale box locations
  90106. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90107. for (var i = 0; i < 2; i++) {
  90108. for (var j = 0; j < 2; j++) {
  90109. for (var k = 0; k < 2; k++) {
  90110. var index = ((i * 4) + (j * 2)) + k;
  90111. if (scaleBoxes[index]) {
  90112. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90113. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90114. if (this.fixedDragMeshScreenSize) {
  90115. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90116. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90117. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90118. }
  90119. else {
  90120. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90121. }
  90122. }
  90123. }
  90124. }
  90125. }
  90126. };
  90127. /**
  90128. * Enables rotation on the specified axis and disables rotation on the others
  90129. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90130. */
  90131. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90132. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90133. if (i < 4) {
  90134. m.setEnabled(axis.indexOf("x") != -1);
  90135. }
  90136. else if (i < 8) {
  90137. m.setEnabled(axis.indexOf("y") != -1);
  90138. }
  90139. else {
  90140. m.setEnabled(axis.indexOf("z") != -1);
  90141. }
  90142. });
  90143. };
  90144. /**
  90145. * Disposes of the gizmo
  90146. */
  90147. BoundingBoxGizmo.prototype.dispose = function () {
  90148. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90149. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90150. this._lineBoundingBox.dispose();
  90151. this._rotateSpheresParent.dispose();
  90152. this._scaleBoxesParent.dispose();
  90153. _super.prototype.dispose.call(this);
  90154. };
  90155. return BoundingBoxGizmo;
  90156. }(BABYLON.Gizmo));
  90157. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  90158. })(BABYLON || (BABYLON = {}));
  90159. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  90160. var BABYLON;
  90161. (function (BABYLON) {
  90162. /**
  90163. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  90164. */
  90165. var GizmoManager = /** @class */ (function () {
  90166. /**
  90167. * Instatiates a gizmo manager
  90168. * @param scene the scene to overlay the gizmos on top of
  90169. * @param options If only a single gizmo should exist at one time
  90170. */
  90171. function GizmoManager(scene, options) {
  90172. var _this = this;
  90173. this.scene = scene;
  90174. // Set of gizmos that are currently in the scene for each mesh
  90175. this._gizmoSet = {};
  90176. this._pointerObserver = null;
  90177. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  90178. // Options parsing
  90179. if (!options) {
  90180. options = {};
  90181. }
  90182. if (options.singleGizmo === undefined) {
  90183. options.singleGizmo = true;
  90184. }
  90185. // Instatiate/dispose gizmos based on pointer actions
  90186. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  90187. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90188. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  90189. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  90190. if (options.singleGizmo) {
  90191. _this._clearGizmos();
  90192. }
  90193. // Enable gizmo when mesh is selected
  90194. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  90195. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90196. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90197. }
  90198. else {
  90199. if (!options.singleGizmo) {
  90200. // Disable gizmo when clicked again
  90201. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  90202. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  90203. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  90204. }
  90205. }
  90206. }
  90207. else {
  90208. if (options.singleGizmo) {
  90209. // Disable gizmo when clicked away
  90210. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  90211. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  90212. if (gizmoPick && !gizmoPick.hit) {
  90213. _this._clearGizmos();
  90214. }
  90215. }
  90216. }
  90217. }
  90218. }
  90219. });
  90220. }
  90221. /**
  90222. * Disposes of the gizmo manager
  90223. */
  90224. GizmoManager.prototype.dispose = function () {
  90225. this.scene.onPointerObservable.remove(this._pointerObserver);
  90226. this._clearGizmos();
  90227. this._gizmoLayer.dispose();
  90228. };
  90229. GizmoManager.prototype._clearGizmos = function () {
  90230. for (var key in this._gizmoSet) {
  90231. if (this._gizmoSet.hasOwnProperty(key)) {
  90232. this._gizmoSet[key].positionGizmo.dispose();
  90233. this._gizmoSet[key].rotationGizmo.dispose();
  90234. delete this._gizmoSet[key];
  90235. }
  90236. }
  90237. };
  90238. return GizmoManager;
  90239. }());
  90240. BABYLON.GizmoManager = GizmoManager;
  90241. })(BABYLON || (BABYLON = {}));
  90242. //# sourceMappingURL=babylon.gizmoManager.js.map
  90243. var BABYLON;
  90244. (function (BABYLON) {
  90245. /**
  90246. * Defines a target to use with MorphTargetManager
  90247. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90248. */
  90249. var MorphTarget = /** @class */ (function () {
  90250. /**
  90251. * Creates a new MorphTarget
  90252. * @param name defines the name of the target
  90253. * @param influence defines the influence to use
  90254. */
  90255. function MorphTarget(
  90256. /** defines the name of the target */
  90257. name, influence, scene) {
  90258. if (influence === void 0) { influence = 0; }
  90259. if (scene === void 0) { scene = null; }
  90260. this.name = name;
  90261. /**
  90262. * Gets or sets the list of animations
  90263. */
  90264. this.animations = new Array();
  90265. this._positions = null;
  90266. this._normals = null;
  90267. this._tangents = null;
  90268. /**
  90269. * Observable raised when the influence changes
  90270. */
  90271. this.onInfluenceChanged = new BABYLON.Observable();
  90272. this._animationPropertiesOverride = null;
  90273. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90274. this.influence = influence;
  90275. }
  90276. Object.defineProperty(MorphTarget.prototype, "influence", {
  90277. /**
  90278. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90279. */
  90280. get: function () {
  90281. return this._influence;
  90282. },
  90283. set: function (influence) {
  90284. if (this._influence === influence) {
  90285. return;
  90286. }
  90287. var previous = this._influence;
  90288. this._influence = influence;
  90289. if (this.onInfluenceChanged.hasObservers) {
  90290. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90291. }
  90292. },
  90293. enumerable: true,
  90294. configurable: true
  90295. });
  90296. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90297. /**
  90298. * Gets or sets the animation properties override
  90299. */
  90300. get: function () {
  90301. if (!this._animationPropertiesOverride && this._scene) {
  90302. return this._scene.animationPropertiesOverride;
  90303. }
  90304. return this._animationPropertiesOverride;
  90305. },
  90306. set: function (value) {
  90307. this._animationPropertiesOverride = value;
  90308. },
  90309. enumerable: true,
  90310. configurable: true
  90311. });
  90312. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90313. /**
  90314. * Gets a boolean defining if the target contains position data
  90315. */
  90316. get: function () {
  90317. return !!this._positions;
  90318. },
  90319. enumerable: true,
  90320. configurable: true
  90321. });
  90322. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90323. /**
  90324. * Gets a boolean defining if the target contains normal data
  90325. */
  90326. get: function () {
  90327. return !!this._normals;
  90328. },
  90329. enumerable: true,
  90330. configurable: true
  90331. });
  90332. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90333. /**
  90334. * Gets a boolean defining if the target contains tangent data
  90335. */
  90336. get: function () {
  90337. return !!this._tangents;
  90338. },
  90339. enumerable: true,
  90340. configurable: true
  90341. });
  90342. /**
  90343. * Affects position data to this target
  90344. * @param data defines the position data to use
  90345. */
  90346. MorphTarget.prototype.setPositions = function (data) {
  90347. this._positions = data;
  90348. };
  90349. /**
  90350. * Gets the position data stored in this target
  90351. * @returns a FloatArray containing the position data (or null if not present)
  90352. */
  90353. MorphTarget.prototype.getPositions = function () {
  90354. return this._positions;
  90355. };
  90356. /**
  90357. * Affects normal data to this target
  90358. * @param data defines the normal data to use
  90359. */
  90360. MorphTarget.prototype.setNormals = function (data) {
  90361. this._normals = data;
  90362. };
  90363. /**
  90364. * Gets the normal data stored in this target
  90365. * @returns a FloatArray containing the normal data (or null if not present)
  90366. */
  90367. MorphTarget.prototype.getNormals = function () {
  90368. return this._normals;
  90369. };
  90370. /**
  90371. * Affects tangent data to this target
  90372. * @param data defines the tangent data to use
  90373. */
  90374. MorphTarget.prototype.setTangents = function (data) {
  90375. this._tangents = data;
  90376. };
  90377. /**
  90378. * Gets the tangent data stored in this target
  90379. * @returns a FloatArray containing the tangent data (or null if not present)
  90380. */
  90381. MorphTarget.prototype.getTangents = function () {
  90382. return this._tangents;
  90383. };
  90384. /**
  90385. * Serializes the current target into a Serialization object
  90386. * @returns the serialized object
  90387. */
  90388. MorphTarget.prototype.serialize = function () {
  90389. var serializationObject = {};
  90390. serializationObject.name = this.name;
  90391. serializationObject.influence = this.influence;
  90392. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90393. if (this.hasNormals) {
  90394. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90395. }
  90396. if (this.hasTangents) {
  90397. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90398. }
  90399. // Animations
  90400. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90401. return serializationObject;
  90402. };
  90403. // Statics
  90404. /**
  90405. * Creates a new target from serialized data
  90406. * @param serializationObject defines the serialized data to use
  90407. * @returns a new MorphTarget
  90408. */
  90409. MorphTarget.Parse = function (serializationObject) {
  90410. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90411. result.setPositions(serializationObject.positions);
  90412. if (serializationObject.normals) {
  90413. result.setNormals(serializationObject.normals);
  90414. }
  90415. if (serializationObject.tangents) {
  90416. result.setTangents(serializationObject.tangents);
  90417. }
  90418. // Animations
  90419. if (serializationObject.animations) {
  90420. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90421. var parsedAnimation = serializationObject.animations[animationIndex];
  90422. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90423. }
  90424. }
  90425. return result;
  90426. };
  90427. /**
  90428. * Creates a MorphTarget from mesh data
  90429. * @param mesh defines the source mesh
  90430. * @param name defines the name to use for the new target
  90431. * @param influence defines the influence to attach to the target
  90432. * @returns a new MorphTarget
  90433. */
  90434. MorphTarget.FromMesh = function (mesh, name, influence) {
  90435. if (!name) {
  90436. name = mesh.name;
  90437. }
  90438. var result = new MorphTarget(name, influence, mesh.getScene());
  90439. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90440. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90441. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90442. }
  90443. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90444. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90445. }
  90446. return result;
  90447. };
  90448. return MorphTarget;
  90449. }());
  90450. BABYLON.MorphTarget = MorphTarget;
  90451. })(BABYLON || (BABYLON = {}));
  90452. //# sourceMappingURL=babylon.morphTarget.js.map
  90453. var BABYLON;
  90454. (function (BABYLON) {
  90455. /**
  90456. * This class is used to deform meshes using morphing between different targets
  90457. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90458. */
  90459. var MorphTargetManager = /** @class */ (function () {
  90460. /**
  90461. * Creates a new MorphTargetManager
  90462. * @param scene defines the current scene
  90463. */
  90464. function MorphTargetManager(scene) {
  90465. if (scene === void 0) { scene = null; }
  90466. this._targets = new Array();
  90467. this._targetObservable = new Array();
  90468. this._activeTargets = new BABYLON.SmartArray(16);
  90469. this._supportsNormals = false;
  90470. this._supportsTangents = false;
  90471. this._vertexCount = 0;
  90472. this._uniqueId = 0;
  90473. this._tempInfluences = new Array();
  90474. if (!scene) {
  90475. scene = BABYLON.Engine.LastCreatedScene;
  90476. }
  90477. this._scene = scene;
  90478. if (this._scene) {
  90479. this._scene.morphTargetManagers.push(this);
  90480. this._uniqueId = this._scene.getUniqueId();
  90481. }
  90482. }
  90483. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90484. /**
  90485. * Gets the unique ID of this manager
  90486. */
  90487. get: function () {
  90488. return this._uniqueId;
  90489. },
  90490. enumerable: true,
  90491. configurable: true
  90492. });
  90493. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90494. /**
  90495. * Gets the number of vertices handled by this manager
  90496. */
  90497. get: function () {
  90498. return this._vertexCount;
  90499. },
  90500. enumerable: true,
  90501. configurable: true
  90502. });
  90503. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  90504. /**
  90505. * Gets a boolean indicating if this manager supports morphing of normals
  90506. */
  90507. get: function () {
  90508. return this._supportsNormals;
  90509. },
  90510. enumerable: true,
  90511. configurable: true
  90512. });
  90513. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  90514. /**
  90515. * Gets a boolean indicating if this manager supports morphing of tangents
  90516. */
  90517. get: function () {
  90518. return this._supportsTangents;
  90519. },
  90520. enumerable: true,
  90521. configurable: true
  90522. });
  90523. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  90524. /**
  90525. * Gets the number of targets stored in this manager
  90526. */
  90527. get: function () {
  90528. return this._targets.length;
  90529. },
  90530. enumerable: true,
  90531. configurable: true
  90532. });
  90533. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  90534. /**
  90535. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90536. */
  90537. get: function () {
  90538. return this._activeTargets.length;
  90539. },
  90540. enumerable: true,
  90541. configurable: true
  90542. });
  90543. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90544. /**
  90545. * Gets the list of influences (one per target)
  90546. */
  90547. get: function () {
  90548. return this._influences;
  90549. },
  90550. enumerable: true,
  90551. configurable: true
  90552. });
  90553. /**
  90554. * Gets the active target at specified index. An active target is a target with an influence > 0
  90555. * @param index defines the index to check
  90556. * @returns the requested target
  90557. */
  90558. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90559. return this._activeTargets.data[index];
  90560. };
  90561. /**
  90562. * Gets the target at specified index
  90563. * @param index defines the index to check
  90564. * @returns the requested target
  90565. */
  90566. MorphTargetManager.prototype.getTarget = function (index) {
  90567. return this._targets[index];
  90568. };
  90569. /**
  90570. * Add a new target to this manager
  90571. * @param target defines the target to add
  90572. */
  90573. MorphTargetManager.prototype.addTarget = function (target) {
  90574. var _this = this;
  90575. this._targets.push(target);
  90576. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90577. _this._syncActiveTargets(needUpdate);
  90578. }));
  90579. this._syncActiveTargets(true);
  90580. };
  90581. /**
  90582. * Removes a target from the manager
  90583. * @param target defines the target to remove
  90584. */
  90585. MorphTargetManager.prototype.removeTarget = function (target) {
  90586. var index = this._targets.indexOf(target);
  90587. if (index >= 0) {
  90588. this._targets.splice(index, 1);
  90589. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90590. this._syncActiveTargets(true);
  90591. }
  90592. };
  90593. /**
  90594. * Serializes the current manager into a Serialization object
  90595. * @returns the serialized object
  90596. */
  90597. MorphTargetManager.prototype.serialize = function () {
  90598. var serializationObject = {};
  90599. serializationObject.id = this.uniqueId;
  90600. serializationObject.targets = [];
  90601. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90602. var target = _a[_i];
  90603. serializationObject.targets.push(target.serialize());
  90604. }
  90605. return serializationObject;
  90606. };
  90607. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90608. var influenceCount = 0;
  90609. this._activeTargets.reset();
  90610. this._supportsNormals = true;
  90611. this._supportsTangents = true;
  90612. this._vertexCount = 0;
  90613. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90614. var target = _a[_i];
  90615. this._activeTargets.push(target);
  90616. this._tempInfluences[influenceCount++] = target.influence;
  90617. var positions = target.getPositions();
  90618. if (positions) {
  90619. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90620. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90621. var vertexCount = positions.length / 3;
  90622. if (this._vertexCount === 0) {
  90623. this._vertexCount = vertexCount;
  90624. }
  90625. else if (this._vertexCount !== vertexCount) {
  90626. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90627. return;
  90628. }
  90629. }
  90630. }
  90631. if (!this._influences || this._influences.length !== influenceCount) {
  90632. this._influences = new Float32Array(influenceCount);
  90633. }
  90634. for (var index = 0; index < influenceCount; index++) {
  90635. this._influences[index] = this._tempInfluences[index];
  90636. }
  90637. if (needUpdate) {
  90638. this.synchronize();
  90639. }
  90640. };
  90641. /**
  90642. * Syncrhonize the targets with all the meshes using this morph target manager
  90643. */
  90644. MorphTargetManager.prototype.synchronize = function () {
  90645. if (!this._scene) {
  90646. return;
  90647. }
  90648. // Flag meshes as dirty to resync with the active targets
  90649. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90650. var mesh = _a[_i];
  90651. if (mesh.morphTargetManager === this) {
  90652. mesh._syncGeometryWithMorphTargetManager();
  90653. }
  90654. }
  90655. };
  90656. // Statics
  90657. /**
  90658. * Creates a new MorphTargetManager from serialized data
  90659. * @param serializationObject defines the serialized data
  90660. * @param scene defines the hosting scene
  90661. * @returns the new MorphTargetManager
  90662. */
  90663. MorphTargetManager.Parse = function (serializationObject, scene) {
  90664. var result = new MorphTargetManager(scene);
  90665. result._uniqueId = serializationObject.id;
  90666. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90667. var targetData = _a[_i];
  90668. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90669. }
  90670. return result;
  90671. };
  90672. return MorphTargetManager;
  90673. }());
  90674. BABYLON.MorphTargetManager = MorphTargetManager;
  90675. })(BABYLON || (BABYLON = {}));
  90676. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90677. var BABYLON;
  90678. (function (BABYLON) {
  90679. var Octree = /** @class */ (function () {
  90680. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90681. if (maxDepth === void 0) { maxDepth = 2; }
  90682. this.maxDepth = maxDepth;
  90683. this.dynamicContent = new Array();
  90684. this._maxBlockCapacity = maxBlockCapacity || 64;
  90685. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90686. this._creationFunc = creationFunc;
  90687. }
  90688. // Methods
  90689. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90690. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90691. };
  90692. Octree.prototype.addMesh = function (entry) {
  90693. for (var index = 0; index < this.blocks.length; index++) {
  90694. var block = this.blocks[index];
  90695. block.addEntry(entry);
  90696. }
  90697. };
  90698. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  90699. this._selectionContent.reset();
  90700. for (var index = 0; index < this.blocks.length; index++) {
  90701. var block = this.blocks[index];
  90702. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  90703. }
  90704. if (allowDuplicate) {
  90705. this._selectionContent.concat(this.dynamicContent);
  90706. }
  90707. else {
  90708. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90709. }
  90710. return this._selectionContent;
  90711. };
  90712. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  90713. this._selectionContent.reset();
  90714. for (var index = 0; index < this.blocks.length; index++) {
  90715. var block = this.blocks[index];
  90716. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  90717. }
  90718. if (allowDuplicate) {
  90719. this._selectionContent.concat(this.dynamicContent);
  90720. }
  90721. else {
  90722. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90723. }
  90724. return this._selectionContent;
  90725. };
  90726. Octree.prototype.intersectsRay = function (ray) {
  90727. this._selectionContent.reset();
  90728. for (var index = 0; index < this.blocks.length; index++) {
  90729. var block = this.blocks[index];
  90730. block.intersectsRay(ray, this._selectionContent);
  90731. }
  90732. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90733. return this._selectionContent;
  90734. };
  90735. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  90736. target.blocks = new Array();
  90737. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  90738. // Segmenting space
  90739. for (var x = 0; x < 2; x++) {
  90740. for (var y = 0; y < 2; y++) {
  90741. for (var z = 0; z < 2; z++) {
  90742. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  90743. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  90744. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  90745. block.addEntries(entries);
  90746. target.blocks.push(block);
  90747. }
  90748. }
  90749. }
  90750. };
  90751. Octree.CreationFuncForMeshes = function (entry, block) {
  90752. var boundingInfo = entry.getBoundingInfo();
  90753. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90754. block.entries.push(entry);
  90755. }
  90756. };
  90757. Octree.CreationFuncForSubMeshes = function (entry, block) {
  90758. var boundingInfo = entry.getBoundingInfo();
  90759. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90760. block.entries.push(entry);
  90761. }
  90762. };
  90763. return Octree;
  90764. }());
  90765. BABYLON.Octree = Octree;
  90766. })(BABYLON || (BABYLON = {}));
  90767. //# sourceMappingURL=babylon.octree.js.map
  90768. var BABYLON;
  90769. (function (BABYLON) {
  90770. var OctreeBlock = /** @class */ (function () {
  90771. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  90772. this.entries = new Array();
  90773. this._boundingVectors = new Array();
  90774. this._capacity = capacity;
  90775. this._depth = depth;
  90776. this._maxDepth = maxDepth;
  90777. this._creationFunc = creationFunc;
  90778. this._minPoint = minPoint;
  90779. this._maxPoint = maxPoint;
  90780. this._boundingVectors.push(minPoint.clone());
  90781. this._boundingVectors.push(maxPoint.clone());
  90782. this._boundingVectors.push(minPoint.clone());
  90783. this._boundingVectors[2].x = maxPoint.x;
  90784. this._boundingVectors.push(minPoint.clone());
  90785. this._boundingVectors[3].y = maxPoint.y;
  90786. this._boundingVectors.push(minPoint.clone());
  90787. this._boundingVectors[4].z = maxPoint.z;
  90788. this._boundingVectors.push(maxPoint.clone());
  90789. this._boundingVectors[5].z = minPoint.z;
  90790. this._boundingVectors.push(maxPoint.clone());
  90791. this._boundingVectors[6].x = minPoint.x;
  90792. this._boundingVectors.push(maxPoint.clone());
  90793. this._boundingVectors[7].y = minPoint.y;
  90794. }
  90795. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  90796. // Property
  90797. get: function () {
  90798. return this._capacity;
  90799. },
  90800. enumerable: true,
  90801. configurable: true
  90802. });
  90803. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  90804. get: function () {
  90805. return this._minPoint;
  90806. },
  90807. enumerable: true,
  90808. configurable: true
  90809. });
  90810. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  90811. get: function () {
  90812. return this._maxPoint;
  90813. },
  90814. enumerable: true,
  90815. configurable: true
  90816. });
  90817. // Methods
  90818. OctreeBlock.prototype.addEntry = function (entry) {
  90819. if (this.blocks) {
  90820. for (var index = 0; index < this.blocks.length; index++) {
  90821. var block = this.blocks[index];
  90822. block.addEntry(entry);
  90823. }
  90824. return;
  90825. }
  90826. this._creationFunc(entry, this);
  90827. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  90828. this.createInnerBlocks();
  90829. }
  90830. };
  90831. OctreeBlock.prototype.addEntries = function (entries) {
  90832. for (var index = 0; index < entries.length; index++) {
  90833. var mesh = entries[index];
  90834. this.addEntry(mesh);
  90835. }
  90836. };
  90837. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  90838. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  90839. if (this.blocks) {
  90840. for (var index = 0; index < this.blocks.length; index++) {
  90841. var block = this.blocks[index];
  90842. block.select(frustumPlanes, selection, allowDuplicate);
  90843. }
  90844. return;
  90845. }
  90846. if (allowDuplicate) {
  90847. selection.concat(this.entries);
  90848. }
  90849. else {
  90850. selection.concatWithNoDuplicate(this.entries);
  90851. }
  90852. }
  90853. };
  90854. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  90855. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  90856. if (this.blocks) {
  90857. for (var index = 0; index < this.blocks.length; index++) {
  90858. var block = this.blocks[index];
  90859. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  90860. }
  90861. return;
  90862. }
  90863. if (allowDuplicate) {
  90864. selection.concat(this.entries);
  90865. }
  90866. else {
  90867. selection.concatWithNoDuplicate(this.entries);
  90868. }
  90869. }
  90870. };
  90871. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  90872. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  90873. if (this.blocks) {
  90874. for (var index = 0; index < this.blocks.length; index++) {
  90875. var block = this.blocks[index];
  90876. block.intersectsRay(ray, selection);
  90877. }
  90878. return;
  90879. }
  90880. selection.concatWithNoDuplicate(this.entries);
  90881. }
  90882. };
  90883. OctreeBlock.prototype.createInnerBlocks = function () {
  90884. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  90885. };
  90886. return OctreeBlock;
  90887. }());
  90888. BABYLON.OctreeBlock = OctreeBlock;
  90889. })(BABYLON || (BABYLON = {}));
  90890. //# sourceMappingURL=babylon.octreeBlock.js.map
  90891. var BABYLON;
  90892. (function (BABYLON) {
  90893. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  90894. __extends(VRDistortionCorrectionPostProcess, _super);
  90895. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  90896. var _this = _super.call(this, name, "vrDistortionCorrection", [
  90897. 'LensCenter',
  90898. 'Scale',
  90899. 'ScaleIn',
  90900. 'HmdWarpParam'
  90901. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  90902. _this._isRightEye = isRightEye;
  90903. _this._distortionFactors = vrMetrics.distortionK;
  90904. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  90905. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  90906. _this.adaptScaleToCurrentViewport = true;
  90907. _this.onSizeChangedObservable.add(function () {
  90908. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  90909. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  90910. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  90911. });
  90912. _this.onApplyObservable.add(function (effect) {
  90913. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  90914. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  90915. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  90916. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  90917. });
  90918. return _this;
  90919. }
  90920. return VRDistortionCorrectionPostProcess;
  90921. }(BABYLON.PostProcess));
  90922. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  90923. })(BABYLON || (BABYLON = {}));
  90924. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  90925. var BABYLON;
  90926. (function (BABYLON) {
  90927. /**
  90928. * Postprocess used to generate anaglyphic rendering
  90929. */
  90930. var AnaglyphPostProcess = /** @class */ (function (_super) {
  90931. __extends(AnaglyphPostProcess, _super);
  90932. /**
  90933. * Creates a new AnaglyphPostProcess
  90934. * @param name defines postprocess name
  90935. * @param options defines creation options or target ratio scale
  90936. * @param rigCameras defines cameras using this postprocess
  90937. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  90938. * @param engine defines hosting engine
  90939. * @param reusable defines if the postprocess will be reused multiple times per frame
  90940. */
  90941. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  90942. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  90943. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90944. _this.onApplyObservable.add(function (effect) {
  90945. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  90946. });
  90947. return _this;
  90948. }
  90949. return AnaglyphPostProcess;
  90950. }(BABYLON.PostProcess));
  90951. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  90952. })(BABYLON || (BABYLON = {}));
  90953. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  90954. var BABYLON;
  90955. (function (BABYLON) {
  90956. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  90957. __extends(StereoscopicInterlacePostProcess, _super);
  90958. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  90959. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  90960. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90961. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90962. _this.onSizeChangedObservable.add(function () {
  90963. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90964. });
  90965. _this.onApplyObservable.add(function (effect) {
  90966. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  90967. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  90968. });
  90969. return _this;
  90970. }
  90971. return StereoscopicInterlacePostProcess;
  90972. }(BABYLON.PostProcess));
  90973. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  90974. })(BABYLON || (BABYLON = {}));
  90975. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  90976. var BABYLON;
  90977. (function (BABYLON) {
  90978. /**
  90979. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  90980. * Screen rotation is taken into account.
  90981. */
  90982. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  90983. function FreeCameraDeviceOrientationInput() {
  90984. var _this = this;
  90985. this._screenOrientationAngle = 0;
  90986. this._screenQuaternion = new BABYLON.Quaternion();
  90987. this._alpha = 0;
  90988. this._beta = 0;
  90989. this._gamma = 0;
  90990. this._orientationChanged = function () {
  90991. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  90992. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  90993. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  90994. };
  90995. this._deviceOrientation = function (evt) {
  90996. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  90997. _this._beta = evt.beta !== null ? evt.beta : 0;
  90998. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  90999. };
  91000. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  91001. this._orientationChanged();
  91002. }
  91003. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  91004. get: function () {
  91005. return this._camera;
  91006. },
  91007. set: function (camera) {
  91008. this._camera = camera;
  91009. if (this._camera != null && !this._camera.rotationQuaternion) {
  91010. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  91011. }
  91012. },
  91013. enumerable: true,
  91014. configurable: true
  91015. });
  91016. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91017. window.addEventListener("orientationchange", this._orientationChanged);
  91018. window.addEventListener("deviceorientation", this._deviceOrientation);
  91019. //In certain cases, the attach control is called AFTER orientation was changed,
  91020. //So this is needed.
  91021. this._orientationChanged();
  91022. };
  91023. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  91024. window.removeEventListener("orientationchange", this._orientationChanged);
  91025. window.removeEventListener("deviceorientation", this._deviceOrientation);
  91026. };
  91027. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  91028. //if no device orientation provided, don't update the rotation.
  91029. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  91030. if (!this._alpha)
  91031. return;
  91032. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  91033. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  91034. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  91035. //Mirror on XY Plane
  91036. this._camera.rotationQuaternion.z *= -1;
  91037. this._camera.rotationQuaternion.w *= -1;
  91038. };
  91039. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  91040. return "FreeCameraDeviceOrientationInput";
  91041. };
  91042. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  91043. return "deviceOrientation";
  91044. };
  91045. return FreeCameraDeviceOrientationInput;
  91046. }());
  91047. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  91048. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  91049. })(BABYLON || (BABYLON = {}));
  91050. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  91051. var BABYLON;
  91052. (function (BABYLON) {
  91053. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  91054. function ArcRotateCameraVRDeviceOrientationInput() {
  91055. this.alphaCorrection = 1;
  91056. this.betaCorrection = 1;
  91057. this.gammaCorrection = 1;
  91058. this._alpha = 0;
  91059. this._gamma = 0;
  91060. this._dirty = false;
  91061. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  91062. }
  91063. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91064. this.camera.attachControl(element, noPreventDefault);
  91065. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  91066. };
  91067. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  91068. if (evt.alpha !== null) {
  91069. this._alpha = +evt.alpha | 0;
  91070. }
  91071. if (evt.gamma !== null) {
  91072. this._gamma = +evt.gamma | 0;
  91073. }
  91074. this._dirty = true;
  91075. };
  91076. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  91077. if (this._dirty) {
  91078. this._dirty = false;
  91079. if (this._gamma < 0) {
  91080. this._gamma = 180 + this._gamma;
  91081. }
  91082. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  91083. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  91084. }
  91085. };
  91086. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  91087. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  91088. };
  91089. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  91090. return "ArcRotateCameraVRDeviceOrientationInput";
  91091. };
  91092. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  91093. return "VRDeviceOrientation";
  91094. };
  91095. return ArcRotateCameraVRDeviceOrientationInput;
  91096. }());
  91097. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  91098. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  91099. })(BABYLON || (BABYLON = {}));
  91100. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  91101. var BABYLON;
  91102. (function (BABYLON) {
  91103. var VRCameraMetrics = /** @class */ (function () {
  91104. function VRCameraMetrics() {
  91105. this.compensateDistortion = true;
  91106. }
  91107. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  91108. get: function () {
  91109. return this.hResolution / (2 * this.vResolution);
  91110. },
  91111. enumerable: true,
  91112. configurable: true
  91113. });
  91114. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  91115. get: function () {
  91116. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  91117. },
  91118. enumerable: true,
  91119. configurable: true
  91120. });
  91121. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  91122. get: function () {
  91123. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91124. var h = (4 * meters) / this.hScreenSize;
  91125. return BABYLON.Matrix.Translation(h, 0, 0);
  91126. },
  91127. enumerable: true,
  91128. configurable: true
  91129. });
  91130. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  91131. get: function () {
  91132. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91133. var h = (4 * meters) / this.hScreenSize;
  91134. return BABYLON.Matrix.Translation(-h, 0, 0);
  91135. },
  91136. enumerable: true,
  91137. configurable: true
  91138. });
  91139. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  91140. get: function () {
  91141. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  91142. },
  91143. enumerable: true,
  91144. configurable: true
  91145. });
  91146. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  91147. get: function () {
  91148. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  91149. },
  91150. enumerable: true,
  91151. configurable: true
  91152. });
  91153. VRCameraMetrics.GetDefault = function () {
  91154. var result = new VRCameraMetrics();
  91155. result.hResolution = 1280;
  91156. result.vResolution = 800;
  91157. result.hScreenSize = 0.149759993;
  91158. result.vScreenSize = 0.0935999975;
  91159. result.vScreenCenter = 0.0467999987;
  91160. result.eyeToScreenDistance = 0.0410000011;
  91161. result.lensSeparationDistance = 0.0635000020;
  91162. result.interpupillaryDistance = 0.0640000030;
  91163. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  91164. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  91165. result.postProcessScaleFactor = 1.714605507808412;
  91166. result.lensCenterOffset = 0.151976421;
  91167. return result;
  91168. };
  91169. return VRCameraMetrics;
  91170. }());
  91171. BABYLON.VRCameraMetrics = VRCameraMetrics;
  91172. })(BABYLON || (BABYLON = {}));
  91173. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  91174. var BABYLON;
  91175. (function (BABYLON) {
  91176. /**
  91177. * This represents a WebVR camera.
  91178. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  91179. * @example http://doc.babylonjs.com/how_to/webvr_camera
  91180. */
  91181. var WebVRFreeCamera = /** @class */ (function (_super) {
  91182. __extends(WebVRFreeCamera, _super);
  91183. /**
  91184. * Instantiates a WebVRFreeCamera.
  91185. * @param name The name of the WebVRFreeCamera
  91186. * @param position The starting anchor position for the camera
  91187. * @param scene The scene the camera belongs to
  91188. * @param webVROptions a set of customizable options for the webVRCamera
  91189. */
  91190. function WebVRFreeCamera(name, position, scene, webVROptions) {
  91191. if (webVROptions === void 0) { webVROptions = {}; }
  91192. var _this = _super.call(this, name, position, scene) || this;
  91193. _this.webVROptions = webVROptions;
  91194. /**
  91195. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  91196. */
  91197. _this._vrDevice = null;
  91198. /**
  91199. * The rawPose of the vrDevice.
  91200. */
  91201. _this.rawPose = null;
  91202. _this._specsVersion = "1.1";
  91203. _this._attached = false;
  91204. _this._descendants = [];
  91205. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  91206. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  91207. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  91208. _this._standingMatrix = null;
  91209. /**
  91210. * Represents device position in babylon space.
  91211. */
  91212. _this.devicePosition = BABYLON.Vector3.Zero();
  91213. /**
  91214. * Represents device rotation in babylon space.
  91215. */
  91216. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  91217. /**
  91218. * The scale of the device to be used when translating from device space to babylon space.
  91219. */
  91220. _this.deviceScaleFactor = 1;
  91221. _this._deviceToWorld = BABYLON.Matrix.Identity();
  91222. _this._worldToDevice = BABYLON.Matrix.Identity();
  91223. /**
  91224. * References to the webVR controllers for the vrDevice.
  91225. */
  91226. _this.controllers = [];
  91227. /**
  91228. * Emits an event when a controller is attached.
  91229. */
  91230. _this.onControllersAttachedObservable = new BABYLON.Observable();
  91231. /**
  91232. * Emits an event when a controller's mesh has been loaded;
  91233. */
  91234. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91235. /**
  91236. * If the rig cameras be used as parent instead of this camera.
  91237. */
  91238. _this.rigParenting = true;
  91239. _this._defaultHeight = undefined;
  91240. _this._workingVector = BABYLON.Vector3.Zero();
  91241. _this._oneVector = BABYLON.Vector3.One();
  91242. _this._workingMatrix = BABYLON.Matrix.Identity();
  91243. _this._cache.position = BABYLON.Vector3.Zero();
  91244. if (webVROptions.defaultHeight) {
  91245. _this._defaultHeight = webVROptions.defaultHeight;
  91246. _this.position.y = _this._defaultHeight;
  91247. }
  91248. _this.minZ = 0.1;
  91249. //legacy support - the compensation boolean was removed.
  91250. if (arguments.length === 5) {
  91251. _this.webVROptions = arguments[4];
  91252. }
  91253. // default webVR options
  91254. if (_this.webVROptions.trackPosition == undefined) {
  91255. _this.webVROptions.trackPosition = true;
  91256. }
  91257. if (_this.webVROptions.controllerMeshes == undefined) {
  91258. _this.webVROptions.controllerMeshes = true;
  91259. }
  91260. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  91261. _this.webVROptions.defaultLightingOnControllers = true;
  91262. }
  91263. _this.rotationQuaternion = new BABYLON.Quaternion();
  91264. if (_this.webVROptions && _this.webVROptions.positionScale) {
  91265. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  91266. }
  91267. //enable VR
  91268. var engine = _this.getEngine();
  91269. _this._onVREnabled = function (success) { if (success) {
  91270. _this.initControllers();
  91271. } };
  91272. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  91273. engine.initWebVR().add(function (event) {
  91274. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  91275. return;
  91276. }
  91277. _this._vrDevice = event.vrDisplay;
  91278. //reset the rig parameters.
  91279. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  91280. if (_this._attached) {
  91281. _this.getEngine().enableVR();
  91282. }
  91283. });
  91284. if (typeof (VRFrameData) !== "undefined")
  91285. _this._frameData = new VRFrameData();
  91286. /**
  91287. * The idea behind the following lines:
  91288. * objects that have the camera as parent should actually have the rig cameras as a parent.
  91289. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  91290. * the second will not show it correctly.
  91291. *
  91292. * To solve this - each object that has the camera as parent will be added to a protected array.
  91293. * When the rig camera renders, it will take this array and set all of those to be its children.
  91294. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  91295. * Amazing!
  91296. */
  91297. scene.onBeforeCameraRenderObservable.add(function (camera) {
  91298. if (camera.parent === _this && _this.rigParenting) {
  91299. _this._descendants = _this.getDescendants(true, function (n) {
  91300. // don't take the cameras or the controllers!
  91301. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  91302. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  91303. return !isController && !isRigCamera;
  91304. });
  91305. _this._descendants.forEach(function (node) {
  91306. node.parent = camera;
  91307. });
  91308. }
  91309. });
  91310. scene.onAfterCameraRenderObservable.add(function (camera) {
  91311. if (camera.parent === _this && _this.rigParenting) {
  91312. _this._descendants.forEach(function (node) {
  91313. node.parent = _this;
  91314. });
  91315. }
  91316. });
  91317. return _this;
  91318. }
  91319. /**
  91320. * Gets the device distance from the ground in meters.
  91321. * @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.
  91322. */
  91323. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  91324. if (this._standingMatrix) {
  91325. // Add standing matrix offset to get real offset from ground in room
  91326. this._standingMatrix.getTranslationToRef(this._workingVector);
  91327. return this._deviceRoomPosition.y + this._workingVector.y;
  91328. }
  91329. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  91330. return this._defaultHeight || 0;
  91331. };
  91332. /**
  91333. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91334. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  91335. */
  91336. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  91337. var _this = this;
  91338. if (callback === void 0) { callback = function (bool) { }; }
  91339. // Use standing matrix if available
  91340. this.getEngine().initWebVRAsync().then(function (result) {
  91341. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  91342. callback(false);
  91343. }
  91344. else {
  91345. _this._standingMatrix = new BABYLON.Matrix();
  91346. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  91347. if (!_this.getScene().useRightHandedSystem) {
  91348. [2, 6, 8, 9, 14].forEach(function (num) {
  91349. if (_this._standingMatrix) {
  91350. _this._standingMatrix.m[num] *= -1;
  91351. }
  91352. });
  91353. }
  91354. callback(true);
  91355. }
  91356. });
  91357. };
  91358. /**
  91359. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91360. * @returns A promise with a boolean set to if the standing matrix is supported.
  91361. */
  91362. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  91363. var _this = this;
  91364. return new Promise(function (res, rej) {
  91365. _this.useStandingMatrix(function (supported) {
  91366. res(supported);
  91367. });
  91368. });
  91369. };
  91370. /**
  91371. * Disposes the camera
  91372. */
  91373. WebVRFreeCamera.prototype.dispose = function () {
  91374. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  91375. _super.prototype.dispose.call(this);
  91376. };
  91377. /**
  91378. * Gets a vrController by name.
  91379. * @param name The name of the controller to retreive
  91380. * @returns the controller matching the name specified or null if not found
  91381. */
  91382. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  91383. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  91384. var gp = _a[_i];
  91385. if (gp.hand === name) {
  91386. return gp;
  91387. }
  91388. }
  91389. return null;
  91390. };
  91391. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  91392. /**
  91393. * The controller corrisponding to the users left hand.
  91394. */
  91395. get: function () {
  91396. if (!this._leftController) {
  91397. this._leftController = this.getControllerByName("left");
  91398. }
  91399. return this._leftController;
  91400. },
  91401. enumerable: true,
  91402. configurable: true
  91403. });
  91404. ;
  91405. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  91406. /**
  91407. * The controller corrisponding to the users right hand.
  91408. */
  91409. get: function () {
  91410. if (!this._rightController) {
  91411. this._rightController = this.getControllerByName("right");
  91412. }
  91413. return this._rightController;
  91414. },
  91415. enumerable: true,
  91416. configurable: true
  91417. });
  91418. ;
  91419. /**
  91420. * Casts a ray forward from the vrCamera's gaze.
  91421. * @param length Length of the ray (default: 100)
  91422. * @returns the ray corrisponding to the gaze
  91423. */
  91424. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  91425. if (length === void 0) { length = 100; }
  91426. if (this.leftCamera) {
  91427. // Use left eye to avoid computation to compute center on every call
  91428. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  91429. }
  91430. else {
  91431. return _super.prototype.getForwardRay.call(this, length);
  91432. }
  91433. };
  91434. /**
  91435. * Updates the camera based on device's frame data
  91436. */
  91437. WebVRFreeCamera.prototype._checkInputs = function () {
  91438. if (this._vrDevice && this._vrDevice.isPresenting) {
  91439. this._vrDevice.getFrameData(this._frameData);
  91440. this.updateFromDevice(this._frameData.pose);
  91441. }
  91442. _super.prototype._checkInputs.call(this);
  91443. };
  91444. /**
  91445. * Updates the poseControlled values based on the input device pose.
  91446. * @param poseData Pose coming from the device
  91447. */
  91448. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  91449. if (poseData && poseData.orientation) {
  91450. this.rawPose = poseData;
  91451. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  91452. if (this.getScene().useRightHandedSystem) {
  91453. this._deviceRoomRotationQuaternion.z *= -1;
  91454. this._deviceRoomRotationQuaternion.w *= -1;
  91455. }
  91456. if (this.webVROptions.trackPosition && this.rawPose.position) {
  91457. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  91458. if (this.getScene().useRightHandedSystem) {
  91459. this._deviceRoomPosition.z *= -1;
  91460. }
  91461. }
  91462. }
  91463. };
  91464. /**
  91465. * WebVR's attach control will start broadcasting frames to the device.
  91466. * Note that in certain browsers (chrome for example) this function must be called
  91467. * within a user-interaction callback. Example:
  91468. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  91469. *
  91470. * @param element html element to attach the vrDevice to
  91471. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  91472. */
  91473. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  91474. _super.prototype.attachControl.call(this, element, noPreventDefault);
  91475. this._attached = true;
  91476. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  91477. if (this._vrDevice) {
  91478. this.getEngine().enableVR();
  91479. }
  91480. };
  91481. /**
  91482. * Detaches the camera from the html element and disables VR
  91483. *
  91484. * @param element html element to detach from
  91485. */
  91486. WebVRFreeCamera.prototype.detachControl = function (element) {
  91487. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  91488. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  91489. _super.prototype.detachControl.call(this, element);
  91490. this._attached = false;
  91491. this.getEngine().disableVR();
  91492. };
  91493. /**
  91494. * @returns the name of this class
  91495. */
  91496. WebVRFreeCamera.prototype.getClassName = function () {
  91497. return "WebVRFreeCamera";
  91498. };
  91499. /**
  91500. * Calls resetPose on the vrDisplay
  91501. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  91502. */
  91503. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  91504. //uses the vrDisplay's "resetPose()".
  91505. //pitch and roll won't be affected.
  91506. this._vrDevice.resetPose();
  91507. };
  91508. /**
  91509. * Updates the rig cameras (left and right eye)
  91510. */
  91511. WebVRFreeCamera.prototype._updateRigCameras = function () {
  91512. var camLeft = this._rigCameras[0];
  91513. var camRight = this._rigCameras[1];
  91514. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91515. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91516. camLeft.position.copyFrom(this._deviceRoomPosition);
  91517. camRight.position.copyFrom(this._deviceRoomPosition);
  91518. };
  91519. /**
  91520. * Updates the cached values of the camera
  91521. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  91522. */
  91523. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  91524. var _this = this;
  91525. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  91526. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  91527. if (!this.updateCacheCalled) {
  91528. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  91529. this.updateCacheCalled = true;
  91530. this.update();
  91531. }
  91532. // Set working vector to the device position in room space rotated by the new rotation
  91533. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  91534. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  91535. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  91536. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  91537. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  91538. // Add translation from anchor position
  91539. this._deviceToWorld.getTranslationToRef(this._workingVector);
  91540. this._workingVector.addInPlace(this.position);
  91541. this._workingVector.subtractInPlace(this._cache.position);
  91542. this._deviceToWorld.setTranslation(this._workingVector);
  91543. // Set an inverted matrix to be used when updating the camera
  91544. this._deviceToWorld.invertToRef(this._worldToDevice);
  91545. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  91546. this.controllers.forEach(function (controller) {
  91547. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  91548. controller.update();
  91549. });
  91550. }
  91551. if (!ignoreParentClass) {
  91552. _super.prototype._updateCache.call(this);
  91553. }
  91554. this.updateCacheCalled = false;
  91555. };
  91556. /**
  91557. * Updates the current device position and rotation in the babylon world
  91558. */
  91559. WebVRFreeCamera.prototype.update = function () {
  91560. // Get current device position in babylon world
  91561. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  91562. // Get current device rotation in babylon world
  91563. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  91564. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  91565. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  91566. _super.prototype.update.call(this);
  91567. };
  91568. /**
  91569. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  91570. * @returns an identity matrix
  91571. */
  91572. WebVRFreeCamera.prototype._getViewMatrix = function () {
  91573. return BABYLON.Matrix.Identity();
  91574. };
  91575. /**
  91576. * This function is called by the two RIG cameras.
  91577. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  91578. */
  91579. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  91580. var _this = this;
  91581. // Update the parent camera prior to using a child camera to avoid desynchronization
  91582. var parentCamera = this._cameraRigParams["parentCamera"];
  91583. parentCamera._updateCache();
  91584. //WebVR 1.1
  91585. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  91586. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  91587. if (!this.getScene().useRightHandedSystem) {
  91588. [2, 6, 8, 9, 14].forEach(function (num) {
  91589. _this._webvrViewMatrix.m[num] *= -1;
  91590. });
  91591. }
  91592. // update the camera rotation matrix
  91593. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  91594. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  91595. // Computing target and final matrix
  91596. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  91597. // should the view matrix be updated with scale and position offset?
  91598. if (parentCamera.deviceScaleFactor !== 1) {
  91599. this._webvrViewMatrix.invert();
  91600. // scale the position, if set
  91601. if (parentCamera.deviceScaleFactor) {
  91602. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  91603. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  91604. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  91605. }
  91606. this._webvrViewMatrix.invert();
  91607. }
  91608. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  91609. // Compute global position
  91610. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  91611. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  91612. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  91613. this._workingMatrix.getTranslationToRef(this._globalPosition);
  91614. this._markSyncedWithParent();
  91615. return this._webvrViewMatrix;
  91616. };
  91617. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  91618. var _this = this;
  91619. var parentCamera = this.parent;
  91620. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  91621. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  91622. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  91623. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  91624. //babylon compatible matrix
  91625. if (!this.getScene().useRightHandedSystem) {
  91626. [8, 9, 10, 11].forEach(function (num) {
  91627. _this._projectionMatrix.m[num] *= -1;
  91628. });
  91629. }
  91630. return this._projectionMatrix;
  91631. };
  91632. /**
  91633. * Initializes the controllers and their meshes
  91634. */
  91635. WebVRFreeCamera.prototype.initControllers = function () {
  91636. var _this = this;
  91637. this.controllers = [];
  91638. var manager = this.getScene().gamepadManager;
  91639. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  91640. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91641. var webVrController = gamepad;
  91642. if (webVrController.defaultModel) {
  91643. webVrController.defaultModel.setEnabled(false);
  91644. }
  91645. if (webVrController.hand === "right") {
  91646. _this._rightController = null;
  91647. }
  91648. if (webVrController.hand === "left") {
  91649. _this._leftController = null;
  91650. }
  91651. var controllerIndex = _this.controllers.indexOf(webVrController);
  91652. if (controllerIndex !== -1) {
  91653. _this.controllers.splice(controllerIndex, 1);
  91654. }
  91655. }
  91656. });
  91657. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  91658. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91659. var webVrController_1 = gamepad;
  91660. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  91661. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  91662. if (_this.webVROptions.controllerMeshes) {
  91663. if (webVrController_1.defaultModel) {
  91664. webVrController_1.defaultModel.setEnabled(true);
  91665. }
  91666. else {
  91667. // Load the meshes
  91668. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  91669. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  91670. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  91671. if (_this.webVROptions.defaultLightingOnControllers) {
  91672. if (!_this._lightOnControllers) {
  91673. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  91674. }
  91675. var activateLightOnSubMeshes_1 = function (mesh, light) {
  91676. var children = mesh.getChildren();
  91677. if (children.length !== 0) {
  91678. children.forEach(function (mesh) {
  91679. light.includedOnlyMeshes.push(mesh);
  91680. activateLightOnSubMeshes_1(mesh, light);
  91681. });
  91682. }
  91683. };
  91684. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  91685. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  91686. }
  91687. });
  91688. }
  91689. }
  91690. webVrController_1.attachToPoseControlledCamera(_this);
  91691. // since this is async - sanity check. Is the controller already stored?
  91692. if (_this.controllers.indexOf(webVrController_1) === -1) {
  91693. //add to the controllers array
  91694. _this.controllers.push(webVrController_1);
  91695. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  91696. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  91697. // So we're overriding setting left & right manually to be sure
  91698. var firstViveWandDetected = false;
  91699. for (var i = 0; i < _this.controllers.length; i++) {
  91700. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91701. if (!firstViveWandDetected) {
  91702. firstViveWandDetected = true;
  91703. _this.controllers[i].hand = "left";
  91704. }
  91705. else {
  91706. _this.controllers[i].hand = "right";
  91707. }
  91708. }
  91709. }
  91710. //did we find enough controllers? Great! let the developer know.
  91711. if (_this.controllers.length >= 2) {
  91712. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  91713. }
  91714. }
  91715. }
  91716. });
  91717. };
  91718. return WebVRFreeCamera;
  91719. }(BABYLON.FreeCamera));
  91720. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  91721. })(BABYLON || (BABYLON = {}));
  91722. //# sourceMappingURL=babylon.webVRCamera.js.map
  91723. var BABYLON;
  91724. (function (BABYLON) {
  91725. // We're mainly based on the logic defined into the FreeCamera code
  91726. /**
  91727. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  91728. * being tilted forward or back and left or right.
  91729. */
  91730. var DeviceOrientationCamera = /** @class */ (function (_super) {
  91731. __extends(DeviceOrientationCamera, _super);
  91732. /**
  91733. * Creates a new device orientation camera
  91734. * @param name The name of the camera
  91735. * @param position The start position camera
  91736. * @param scene The scene the camera belongs to
  91737. */
  91738. function DeviceOrientationCamera(name, position, scene) {
  91739. var _this = _super.call(this, name, position, scene) || this;
  91740. _this._quaternionCache = new BABYLON.Quaternion();
  91741. _this.inputs.addDeviceOrientation();
  91742. return _this;
  91743. }
  91744. /**
  91745. * Gets the current instance class name ("DeviceOrientationCamera").
  91746. * This helps avoiding instanceof at run time.
  91747. * @returns the class name
  91748. */
  91749. DeviceOrientationCamera.prototype.getClassName = function () {
  91750. return "DeviceOrientationCamera";
  91751. };
  91752. /**
  91753. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  91754. */
  91755. DeviceOrientationCamera.prototype._checkInputs = function () {
  91756. _super.prototype._checkInputs.call(this);
  91757. this._quaternionCache.copyFrom(this.rotationQuaternion);
  91758. if (this._initialQuaternion) {
  91759. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91760. }
  91761. };
  91762. /**
  91763. * Reset the camera to its default orientation on the specified axis only.
  91764. * @param axis The axis to reset
  91765. */
  91766. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  91767. var _this = this;
  91768. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  91769. //can only work if this camera has a rotation quaternion already.
  91770. if (!this.rotationQuaternion)
  91771. return;
  91772. if (!this._initialQuaternion) {
  91773. this._initialQuaternion = new BABYLON.Quaternion();
  91774. }
  91775. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  91776. ['x', 'y', 'z'].forEach(function (axisName) {
  91777. if (!axis[axisName]) {
  91778. _this._initialQuaternion[axisName] = 0;
  91779. }
  91780. else {
  91781. _this._initialQuaternion[axisName] *= -1;
  91782. }
  91783. });
  91784. this._initialQuaternion.normalize();
  91785. //force rotation update
  91786. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91787. };
  91788. return DeviceOrientationCamera;
  91789. }(BABYLON.FreeCamera));
  91790. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  91791. })(BABYLON || (BABYLON = {}));
  91792. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  91793. var BABYLON;
  91794. (function (BABYLON) {
  91795. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  91796. __extends(VRDeviceOrientationFreeCamera, _super);
  91797. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91798. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91799. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91800. var _this = _super.call(this, name, position, scene) || this;
  91801. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91802. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91803. return _this;
  91804. }
  91805. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  91806. return "VRDeviceOrientationFreeCamera";
  91807. };
  91808. return VRDeviceOrientationFreeCamera;
  91809. }(BABYLON.DeviceOrientationCamera));
  91810. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  91811. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  91812. __extends(VRDeviceOrientationGamepadCamera, _super);
  91813. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91814. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91815. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91816. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  91817. _this.inputs.addGamepad();
  91818. return _this;
  91819. }
  91820. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  91821. return "VRDeviceOrientationGamepadCamera";
  91822. };
  91823. return VRDeviceOrientationGamepadCamera;
  91824. }(VRDeviceOrientationFreeCamera));
  91825. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  91826. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  91827. __extends(VRDeviceOrientationArcRotateCamera, _super);
  91828. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  91829. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91830. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91831. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91832. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91833. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91834. _this.inputs.addVRDeviceOrientation();
  91835. return _this;
  91836. }
  91837. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  91838. return "VRDeviceOrientationArcRotateCamera";
  91839. };
  91840. return VRDeviceOrientationArcRotateCamera;
  91841. }(BABYLON.ArcRotateCamera));
  91842. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  91843. })(BABYLON || (BABYLON = {}));
  91844. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  91845. var BABYLON;
  91846. (function (BABYLON) {
  91847. /**
  91848. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91849. */
  91850. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91851. __extends(AnaglyphFreeCamera, _super);
  91852. /**
  91853. * Creates a new AnaglyphFreeCamera
  91854. * @param name defines camera name
  91855. * @param position defines initial position
  91856. * @param interaxialDistance defines distance between each color axis
  91857. * @param scene defines the hosting scene
  91858. */
  91859. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91860. var _this = _super.call(this, name, position, scene) || this;
  91861. _this.interaxialDistance = interaxialDistance;
  91862. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91863. return _this;
  91864. }
  91865. /**
  91866. * Gets camera class name
  91867. * @returns AnaglyphFreeCamera
  91868. */
  91869. AnaglyphFreeCamera.prototype.getClassName = function () {
  91870. return "AnaglyphFreeCamera";
  91871. };
  91872. return AnaglyphFreeCamera;
  91873. }(BABYLON.FreeCamera));
  91874. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91875. /**
  91876. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91877. */
  91878. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91879. __extends(AnaglyphArcRotateCamera, _super);
  91880. /**
  91881. * Creates a new AnaglyphArcRotateCamera
  91882. * @param name defines camera name
  91883. * @param alpha defines alpha angle (in radians)
  91884. * @param beta defines beta angle (in radians)
  91885. * @param radius defines radius
  91886. * @param target defines camera target
  91887. * @param interaxialDistance defines distance between each color axis
  91888. * @param scene defines the hosting scene
  91889. */
  91890. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91891. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91892. _this.interaxialDistance = interaxialDistance;
  91893. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91894. return _this;
  91895. }
  91896. /**
  91897. * Gets camera class name
  91898. * @returns AnaglyphArcRotateCamera
  91899. */
  91900. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91901. return "AnaglyphArcRotateCamera";
  91902. };
  91903. return AnaglyphArcRotateCamera;
  91904. }(BABYLON.ArcRotateCamera));
  91905. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91906. /**
  91907. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91908. */
  91909. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91910. __extends(AnaglyphGamepadCamera, _super);
  91911. /**
  91912. * Creates a new AnaglyphGamepadCamera
  91913. * @param name defines camera name
  91914. * @param position defines initial position
  91915. * @param interaxialDistance defines distance between each color axis
  91916. * @param scene defines the hosting scene
  91917. */
  91918. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91919. var _this = _super.call(this, name, position, scene) || this;
  91920. _this.interaxialDistance = interaxialDistance;
  91921. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91922. return _this;
  91923. }
  91924. /**
  91925. * Gets camera class name
  91926. * @returns AnaglyphGamepadCamera
  91927. */
  91928. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91929. return "AnaglyphGamepadCamera";
  91930. };
  91931. return AnaglyphGamepadCamera;
  91932. }(BABYLON.GamepadCamera));
  91933. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91934. /**
  91935. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91936. */
  91937. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91938. __extends(AnaglyphUniversalCamera, _super);
  91939. /**
  91940. * Creates a new AnaglyphUniversalCamera
  91941. * @param name defines camera name
  91942. * @param position defines initial position
  91943. * @param interaxialDistance defines distance between each color axis
  91944. * @param scene defines the hosting scene
  91945. */
  91946. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91947. var _this = _super.call(this, name, position, scene) || this;
  91948. _this.interaxialDistance = interaxialDistance;
  91949. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91950. return _this;
  91951. }
  91952. /**
  91953. * Gets camera class name
  91954. * @returns AnaglyphUniversalCamera
  91955. */
  91956. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91957. return "AnaglyphUniversalCamera";
  91958. };
  91959. return AnaglyphUniversalCamera;
  91960. }(BABYLON.UniversalCamera));
  91961. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91962. /**
  91963. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91964. */
  91965. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91966. __extends(StereoscopicFreeCamera, _super);
  91967. /**
  91968. * Creates a new StereoscopicFreeCamera
  91969. * @param name defines camera name
  91970. * @param position defines initial position
  91971. * @param interaxialDistance defines distance between each color axis
  91972. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91973. * @param scene defines the hosting scene
  91974. */
  91975. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91976. var _this = _super.call(this, name, position, scene) || this;
  91977. _this.interaxialDistance = interaxialDistance;
  91978. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91979. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91980. return _this;
  91981. }
  91982. /**
  91983. * Gets camera class name
  91984. * @returns StereoscopicFreeCamera
  91985. */
  91986. StereoscopicFreeCamera.prototype.getClassName = function () {
  91987. return "StereoscopicFreeCamera";
  91988. };
  91989. return StereoscopicFreeCamera;
  91990. }(BABYLON.FreeCamera));
  91991. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91992. /**
  91993. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91994. */
  91995. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91996. __extends(StereoscopicArcRotateCamera, _super);
  91997. /**
  91998. * Creates a new StereoscopicArcRotateCamera
  91999. * @param name defines camera name
  92000. * @param alpha defines alpha angle (in radians)
  92001. * @param beta defines beta angle (in radians)
  92002. * @param radius defines radius
  92003. * @param target defines camera target
  92004. * @param interaxialDistance defines distance between each color axis
  92005. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92006. * @param scene defines the hosting scene
  92007. */
  92008. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  92009. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92010. _this.interaxialDistance = interaxialDistance;
  92011. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92012. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92013. return _this;
  92014. }
  92015. /**
  92016. * Gets camera class name
  92017. * @returns StereoscopicArcRotateCamera
  92018. */
  92019. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  92020. return "StereoscopicArcRotateCamera";
  92021. };
  92022. return StereoscopicArcRotateCamera;
  92023. }(BABYLON.ArcRotateCamera));
  92024. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  92025. /**
  92026. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  92027. */
  92028. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  92029. __extends(StereoscopicGamepadCamera, _super);
  92030. /**
  92031. * Creates a new StereoscopicGamepadCamera
  92032. * @param name defines camera name
  92033. * @param position defines initial position
  92034. * @param interaxialDistance defines distance between each color axis
  92035. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92036. * @param scene defines the hosting scene
  92037. */
  92038. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92039. var _this = _super.call(this, name, position, scene) || this;
  92040. _this.interaxialDistance = interaxialDistance;
  92041. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92042. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92043. return _this;
  92044. }
  92045. /**
  92046. * Gets camera class name
  92047. * @returns StereoscopicGamepadCamera
  92048. */
  92049. StereoscopicGamepadCamera.prototype.getClassName = function () {
  92050. return "StereoscopicGamepadCamera";
  92051. };
  92052. return StereoscopicGamepadCamera;
  92053. }(BABYLON.GamepadCamera));
  92054. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  92055. /**
  92056. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  92057. */
  92058. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  92059. __extends(StereoscopicUniversalCamera, _super);
  92060. /**
  92061. * Creates a new StereoscopicUniversalCamera
  92062. * @param name defines camera name
  92063. * @param position defines initial position
  92064. * @param interaxialDistance defines distance between each color axis
  92065. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92066. * @param scene defines the hosting scene
  92067. */
  92068. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92069. var _this = _super.call(this, name, position, scene) || this;
  92070. _this.interaxialDistance = interaxialDistance;
  92071. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92072. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92073. return _this;
  92074. }
  92075. /**
  92076. * Gets camera class name
  92077. * @returns StereoscopicUniversalCamera
  92078. */
  92079. StereoscopicUniversalCamera.prototype.getClassName = function () {
  92080. return "StereoscopicUniversalCamera";
  92081. };
  92082. return StereoscopicUniversalCamera;
  92083. }(BABYLON.UniversalCamera));
  92084. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  92085. })(BABYLON || (BABYLON = {}));
  92086. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  92087. var BABYLON;
  92088. (function (BABYLON) {
  92089. var VRExperienceHelperGazer = /** @class */ (function () {
  92090. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  92091. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  92092. this.scene = scene;
  92093. this._pointerDownOnMeshAsked = false;
  92094. this._isActionableMesh = false;
  92095. this._teleportationRequestInitiated = false;
  92096. this._teleportationBackRequestInitiated = false;
  92097. this._rotationRightAsked = false;
  92098. this._rotationLeftAsked = false;
  92099. this._dpadPressed = true;
  92100. this._activePointer = false;
  92101. this._id = VRExperienceHelperGazer._idCounter++;
  92102. // Gaze tracker
  92103. if (!gazeTrackerToClone) {
  92104. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  92105. this._gazeTracker.bakeCurrentTransformIntoVertices();
  92106. this._gazeTracker.isPickable = false;
  92107. this._gazeTracker.isVisible = false;
  92108. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  92109. targetMat.specularColor = BABYLON.Color3.Black();
  92110. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92111. targetMat.backFaceCulling = false;
  92112. this._gazeTracker.material = targetMat;
  92113. }
  92114. else {
  92115. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  92116. }
  92117. }
  92118. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  92119. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  92120. };
  92121. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  92122. this._pointerDownOnMeshAsked = true;
  92123. if (this._currentHit) {
  92124. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  92125. }
  92126. };
  92127. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  92128. if (this._currentHit) {
  92129. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  92130. }
  92131. this._pointerDownOnMeshAsked = false;
  92132. };
  92133. VRExperienceHelperGazer.prototype._activatePointer = function () {
  92134. this._activePointer = true;
  92135. };
  92136. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  92137. this._activePointer = false;
  92138. };
  92139. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  92140. if (distance === void 0) { distance = 100; }
  92141. };
  92142. VRExperienceHelperGazer.prototype.dispose = function () {
  92143. this._interactionsEnabled = false;
  92144. this._teleportationEnabled = false;
  92145. if (this._gazeTracker) {
  92146. this._gazeTracker.dispose();
  92147. }
  92148. };
  92149. VRExperienceHelperGazer._idCounter = 0;
  92150. return VRExperienceHelperGazer;
  92151. }());
  92152. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  92153. __extends(VRExperienceHelperControllerGazer, _super);
  92154. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  92155. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  92156. _this.webVRController = webVRController;
  92157. // Laser pointer
  92158. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  92159. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  92160. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92161. laserPointerMaterial.alpha = 0.6;
  92162. _this._laserPointer.material = laserPointerMaterial;
  92163. _this._laserPointer.rotation.x = Math.PI / 2;
  92164. _this._laserPointer.position.z = -0.5;
  92165. _this._laserPointer.isVisible = false;
  92166. _this._laserPointer.isPickable = false;
  92167. if (!webVRController.mesh) {
  92168. // Create an empty mesh that is used prior to loading the high quality model
  92169. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  92170. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  92171. preloadPointerPose.rotation.x = -0.7;
  92172. preloadMesh.addChild(preloadPointerPose);
  92173. webVRController.attachToMesh(preloadMesh);
  92174. }
  92175. _this._setLaserPointerParent(webVRController.mesh);
  92176. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  92177. _this._setLaserPointerParent(mesh);
  92178. });
  92179. return _this;
  92180. }
  92181. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  92182. return this.webVRController.getForwardRay(length);
  92183. };
  92184. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  92185. _super.prototype._activatePointer.call(this);
  92186. this._laserPointer.isVisible = true;
  92187. };
  92188. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  92189. _super.prototype._deactivatePointer.call(this);
  92190. this._laserPointer.isVisible = false;
  92191. };
  92192. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  92193. this._laserPointer.material.emissiveColor = color;
  92194. };
  92195. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  92196. var makeNotPick = function (root) {
  92197. root.name += " laserPointer";
  92198. root.isPickable = false;
  92199. root.getChildMeshes().forEach(function (c) {
  92200. makeNotPick(c);
  92201. });
  92202. };
  92203. makeNotPick(mesh);
  92204. var childMeshes = mesh.getChildMeshes();
  92205. this.webVRController._pointingPoseNode = null;
  92206. for (var i = 0; i < childMeshes.length; i++) {
  92207. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  92208. mesh = childMeshes[i];
  92209. this.webVRController._pointingPoseNode = mesh;
  92210. break;
  92211. }
  92212. }
  92213. this._laserPointer.parent = mesh;
  92214. };
  92215. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  92216. if (distance === void 0) { distance = 100; }
  92217. this._laserPointer.scaling.y = distance;
  92218. this._laserPointer.position.z = -distance / 2;
  92219. };
  92220. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  92221. _super.prototype.dispose.call(this);
  92222. this._laserPointer.dispose();
  92223. if (this._meshAttachedObserver) {
  92224. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  92225. }
  92226. };
  92227. return VRExperienceHelperControllerGazer;
  92228. }(VRExperienceHelperGazer));
  92229. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  92230. __extends(VRExperienceHelperCameraGazer, _super);
  92231. function VRExperienceHelperCameraGazer(getCamera, scene) {
  92232. var _this = _super.call(this, scene) || this;
  92233. _this.getCamera = getCamera;
  92234. return _this;
  92235. }
  92236. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  92237. var camera = this.getCamera();
  92238. if (camera) {
  92239. return camera.getForwardRay(length);
  92240. }
  92241. else {
  92242. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  92243. }
  92244. };
  92245. return VRExperienceHelperCameraGazer;
  92246. }(VRExperienceHelperGazer));
  92247. /**
  92248. * Helps to quickly add VR support to an existing scene.
  92249. * See http://doc.babylonjs.com/how_to/webvr_helper
  92250. */
  92251. var VRExperienceHelper = /** @class */ (function () {
  92252. /**
  92253. * Instantiates a VRExperienceHelper.
  92254. * Helps to quickly add VR support to an existing scene.
  92255. * @param scene The scene the VRExperienceHelper belongs to.
  92256. * @param webVROptions Options to modify the vr experience helper's behavior.
  92257. */
  92258. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92259. if (webVROptions === void 0) { webVROptions = {}; }
  92260. var _this = this;
  92261. this.webVROptions = webVROptions;
  92262. // Can the system support WebVR, even if a headset isn't plugged in?
  92263. this._webVRsupported = false;
  92264. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92265. this._webVRready = false;
  92266. // Are we waiting for the requestPresent callback to complete?
  92267. this._webVRrequesting = false;
  92268. // Are we presenting to the headset right now?
  92269. this._webVRpresenting = false;
  92270. // Are we presenting in the fullscreen fallback?
  92271. this._fullscreenVRpresenting = false;
  92272. /**
  92273. * Observable raised when entering VR.
  92274. */
  92275. this.onEnteringVRObservable = new BABYLON.Observable();
  92276. /**
  92277. * Observable raised when exiting VR.
  92278. */
  92279. this.onExitingVRObservable = new BABYLON.Observable();
  92280. /**
  92281. * Observable raised when controller mesh is loaded.
  92282. */
  92283. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92284. this._useCustomVRButton = false;
  92285. this._teleportationRequested = false;
  92286. this._teleportActive = false;
  92287. this._floorMeshesCollection = [];
  92288. this._rotationAllowed = true;
  92289. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92290. this._isDefaultTeleportationTarget = true;
  92291. this._teleportationFillColor = "#444444";
  92292. this._teleportationBorderColor = "#FFFFFF";
  92293. this._rotationAngle = 0;
  92294. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92295. this._padSensibilityUp = 0.65;
  92296. this._padSensibilityDown = 0.35;
  92297. this.leftController = null;
  92298. this.rightController = null;
  92299. /**
  92300. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92301. */
  92302. this.onNewMeshSelected = new BABYLON.Observable();
  92303. /**
  92304. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92305. */
  92306. this.onNewMeshPicked = new BABYLON.Observable();
  92307. /**
  92308. * Observable raised before camera teleportation
  92309. */
  92310. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92311. /**
  92312. * Observable raised after camera teleportation
  92313. */
  92314. this.onAfterCameraTeleport = new BABYLON.Observable();
  92315. /**
  92316. * Observable raised when current selected mesh gets unselected
  92317. */
  92318. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92319. /**
  92320. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92321. */
  92322. this.teleportationEnabled = true;
  92323. this._teleportationInitialized = false;
  92324. this._interactionsEnabled = false;
  92325. this._interactionsRequested = false;
  92326. this._displayGaze = true;
  92327. this._displayLaserPointer = true;
  92328. this._onResize = function () {
  92329. _this.moveButtonToBottomRight();
  92330. if (_this._fullscreenVRpresenting && _this._webVRready) {
  92331. _this.exitVR();
  92332. }
  92333. };
  92334. this._onFullscreenChange = function () {
  92335. if (document.fullscreen !== undefined) {
  92336. _this._fullscreenVRpresenting = document.fullscreen;
  92337. }
  92338. else if (document.mozFullScreen !== undefined) {
  92339. _this._fullscreenVRpresenting = document.mozFullScreen;
  92340. }
  92341. else if (document.webkitIsFullScreen !== undefined) {
  92342. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  92343. }
  92344. else if (document.msIsFullScreen !== undefined) {
  92345. _this._fullscreenVRpresenting = document.msIsFullScreen;
  92346. }
  92347. else if (document.msFullscreenElement !== undefined) {
  92348. _this._fullscreenVRpresenting = document.msFullscreenElement;
  92349. }
  92350. if (!_this._fullscreenVRpresenting && _this._canvas) {
  92351. _this.exitVR();
  92352. if (!_this._useCustomVRButton) {
  92353. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  92354. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  92355. }
  92356. }
  92357. };
  92358. this.beforeRender = function () {
  92359. if (_this.leftController && _this.leftController._activePointer) {
  92360. _this._castRayAndSelectObject(_this.leftController);
  92361. }
  92362. if (_this.rightController && _this.rightController._activePointer) {
  92363. _this._castRayAndSelectObject(_this.rightController);
  92364. }
  92365. if (_this._noControllerIsActive) {
  92366. _this._castRayAndSelectObject(_this._cameraGazer);
  92367. }
  92368. else {
  92369. _this._cameraGazer._gazeTracker.isVisible = false;
  92370. }
  92371. };
  92372. this._onNewGamepadConnected = function (gamepad) {
  92373. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  92374. if (gamepad.leftStick) {
  92375. gamepad.onleftstickchanged(function (stickValues) {
  92376. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  92377. // Listening to classic/xbox gamepad only if no VR controller is active
  92378. if ((!_this.leftController && !_this.rightController) ||
  92379. ((_this.leftController && !_this.leftController._activePointer) &&
  92380. (_this.rightController && !_this.rightController._activePointer))) {
  92381. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  92382. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  92383. }
  92384. }
  92385. });
  92386. }
  92387. if (gamepad.rightStick) {
  92388. gamepad.onrightstickchanged(function (stickValues) {
  92389. if (_this._teleportationInitialized) {
  92390. _this._checkRotate(stickValues, _this._cameraGazer);
  92391. }
  92392. });
  92393. }
  92394. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  92395. gamepad.onbuttondown(function (buttonPressed) {
  92396. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92397. _this._cameraGazer._selectionPointerDown();
  92398. }
  92399. });
  92400. gamepad.onbuttonup(function (buttonPressed) {
  92401. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92402. _this._cameraGazer._selectionPointerUp();
  92403. }
  92404. });
  92405. }
  92406. }
  92407. else {
  92408. var webVRController = gamepad;
  92409. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  92410. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  92411. _this.rightController = controller;
  92412. }
  92413. else {
  92414. _this.leftController = controller;
  92415. }
  92416. _this._tryEnableInteractionOnController(controller);
  92417. }
  92418. };
  92419. // 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
  92420. this._tryEnableInteractionOnController = function (controller) {
  92421. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  92422. _this._enableInteractionOnController(controller);
  92423. }
  92424. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  92425. _this._enableTeleportationOnController(controller);
  92426. }
  92427. };
  92428. this._onNewGamepadDisconnected = function (gamepad) {
  92429. if (gamepad instanceof BABYLON.WebVRController) {
  92430. if (gamepad.hand === "left" && _this.leftController != null) {
  92431. _this.leftController.dispose();
  92432. _this.leftController = null;
  92433. }
  92434. if (gamepad.hand === "right" && _this.rightController != null) {
  92435. _this.rightController.dispose();
  92436. _this.rightController = null;
  92437. }
  92438. }
  92439. };
  92440. this._workingVector = BABYLON.Vector3.Zero();
  92441. this._workingQuaternion = BABYLON.Quaternion.Identity();
  92442. this._workingMatrix = BABYLON.Matrix.Identity();
  92443. this._scene = scene;
  92444. this._canvas = scene.getEngine().getRenderingCanvas();
  92445. // Parse options
  92446. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  92447. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  92448. }
  92449. if (webVROptions.createDeviceOrientationCamera === undefined) {
  92450. webVROptions.createDeviceOrientationCamera = true;
  92451. }
  92452. if (webVROptions.laserToggle === undefined) {
  92453. webVROptions.laserToggle = true;
  92454. }
  92455. if (webVROptions.defaultHeight === undefined) {
  92456. webVROptions.defaultHeight = 1.7;
  92457. }
  92458. if (webVROptions.useCustomVRButton) {
  92459. this._useCustomVRButton = true;
  92460. if (webVROptions.customVRButton) {
  92461. this._btnVR = webVROptions.customVRButton;
  92462. }
  92463. }
  92464. if (webVROptions.rayLength) {
  92465. this._rayLength = webVROptions.rayLength;
  92466. }
  92467. this._defaultHeight = webVROptions.defaultHeight;
  92468. if (webVROptions.positionScale) {
  92469. this._rayLength *= webVROptions.positionScale;
  92470. this._defaultHeight *= webVROptions.positionScale;
  92471. }
  92472. // Set position
  92473. if (this._scene.activeCamera) {
  92474. this._position = this._scene.activeCamera.position.clone();
  92475. }
  92476. else {
  92477. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  92478. }
  92479. // Set non-vr camera
  92480. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  92481. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  92482. // Copy data from existing camera
  92483. if (this._scene.activeCamera) {
  92484. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92485. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  92486. // Set rotation from previous camera
  92487. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  92488. var targetCamera = this._scene.activeCamera;
  92489. if (targetCamera.rotationQuaternion) {
  92490. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  92491. }
  92492. else {
  92493. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  92494. }
  92495. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  92496. }
  92497. }
  92498. this._scene.activeCamera = this._deviceOrientationCamera;
  92499. if (this._canvas) {
  92500. this._scene.activeCamera.attachControl(this._canvas);
  92501. }
  92502. }
  92503. else {
  92504. this._existingCamera = this._scene.activeCamera;
  92505. }
  92506. // Create VR cameras
  92507. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92508. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  92509. }
  92510. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  92511. this._webVRCamera.useStandingMatrix();
  92512. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  92513. // Create default button
  92514. if (!this._useCustomVRButton) {
  92515. this._btnVR = document.createElement("BUTTON");
  92516. this._btnVR.className = "babylonVRicon";
  92517. this._btnVR.id = "babylonVRiconbtn";
  92518. this._btnVR.title = "Click to switch to VR";
  92519. 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) }";
  92520. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  92521. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  92522. // css += ".babylonVRicon.vrdisplaysupported { }";
  92523. // css += ".babylonVRicon.vrdisplayready { }";
  92524. // css += ".babylonVRicon.vrdisplayrequesting { }";
  92525. var style = document.createElement('style');
  92526. style.appendChild(document.createTextNode(css));
  92527. document.getElementsByTagName('head')[0].appendChild(style);
  92528. this.moveButtonToBottomRight();
  92529. }
  92530. // VR button click event
  92531. if (this._btnVR) {
  92532. this._btnVR.addEventListener("click", function () {
  92533. if (!_this.isInVRMode) {
  92534. _this.enterVR();
  92535. }
  92536. else {
  92537. _this.exitVR();
  92538. }
  92539. });
  92540. }
  92541. // Window events
  92542. window.addEventListener("resize", this._onResize);
  92543. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92544. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92545. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92546. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92547. document.onmsfullscreenchange = this._onFullscreenChange;
  92548. // Display vr button when headset is connected
  92549. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92550. this.displayVRButton();
  92551. }
  92552. else {
  92553. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92554. if (e.vrDisplay) {
  92555. _this.displayVRButton();
  92556. }
  92557. });
  92558. }
  92559. // Exiting VR mode using 'ESC' key on desktop
  92560. this._onKeyDown = function (event) {
  92561. if (event.keyCode === 27 && _this.isInVRMode) {
  92562. _this.exitVR();
  92563. }
  92564. };
  92565. document.addEventListener("keydown", this._onKeyDown);
  92566. // Exiting VR mode double tapping the touch screen
  92567. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92568. if (_this.isInVRMode) {
  92569. _this.exitVR();
  92570. if (_this._fullscreenVRpresenting) {
  92571. _this._scene.getEngine().switchFullscreen(true);
  92572. }
  92573. }
  92574. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92575. // Listen for WebVR display changes
  92576. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92577. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92578. this._onVRRequestPresentStart = function () {
  92579. _this._webVRrequesting = true;
  92580. _this.updateButtonVisibility();
  92581. };
  92582. this._onVRRequestPresentComplete = function (success) {
  92583. _this._webVRrequesting = false;
  92584. _this.updateButtonVisibility();
  92585. };
  92586. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92587. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92588. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92589. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92590. scene.onDisposeObservable.add(function () {
  92591. _this.dispose();
  92592. });
  92593. // Gamepad connection events
  92594. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92595. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92596. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92597. this.updateButtonVisibility();
  92598. //create easing functions
  92599. this._circleEase = new BABYLON.CircleEase();
  92600. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92601. if (this.webVROptions.floorMeshes) {
  92602. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92603. }
  92604. }
  92605. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92606. /** Return this.onEnteringVRObservable
  92607. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  92608. */
  92609. get: function () {
  92610. return this.onEnteringVRObservable;
  92611. },
  92612. enumerable: true,
  92613. configurable: true
  92614. });
  92615. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  92616. /** Return this.onExitingVRObservable
  92617. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  92618. */
  92619. get: function () {
  92620. return this.onExitingVRObservable;
  92621. },
  92622. enumerable: true,
  92623. configurable: true
  92624. });
  92625. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  92626. /** Return this.onControllerMeshLoadedObservable
  92627. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  92628. */
  92629. get: function () {
  92630. return this.onControllerMeshLoadedObservable;
  92631. },
  92632. enumerable: true,
  92633. configurable: true
  92634. });
  92635. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  92636. /**
  92637. * The mesh used to display where the user is going to teleport.
  92638. */
  92639. get: function () {
  92640. return this._teleportationTarget;
  92641. },
  92642. /**
  92643. * Sets the mesh to be used to display where the user is going to teleport.
  92644. */
  92645. set: function (value) {
  92646. if (value) {
  92647. value.name = "teleportationTarget";
  92648. this._isDefaultTeleportationTarget = false;
  92649. this._teleportationTarget = value;
  92650. }
  92651. },
  92652. enumerable: true,
  92653. configurable: true
  92654. });
  92655. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  92656. /**
  92657. * The mesh used to display where the user is selecting,
  92658. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  92659. * See http://doc.babylonjs.com/resources/baking_transformations
  92660. */
  92661. get: function () {
  92662. return this._cameraGazer._gazeTracker;
  92663. },
  92664. set: function (value) {
  92665. if (value) {
  92666. this._cameraGazer._gazeTracker = value;
  92667. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  92668. this._cameraGazer._gazeTracker.isPickable = false;
  92669. this._cameraGazer._gazeTracker.isVisible = false;
  92670. this._cameraGazer._gazeTracker.name = "gazeTracker";
  92671. if (this.leftController) {
  92672. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92673. }
  92674. if (this.rightController) {
  92675. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92676. }
  92677. }
  92678. },
  92679. enumerable: true,
  92680. configurable: true
  92681. });
  92682. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  92683. /**
  92684. * If the ray of the gaze should be displayed.
  92685. */
  92686. get: function () {
  92687. return this._displayGaze;
  92688. },
  92689. /**
  92690. * Sets if the ray of the gaze should be displayed.
  92691. */
  92692. set: function (value) {
  92693. this._displayGaze = value;
  92694. if (!value) {
  92695. this._cameraGazer._gazeTracker.isVisible = false;
  92696. if (this.leftController) {
  92697. this.leftController._gazeTracker.isVisible = false;
  92698. }
  92699. if (this.rightController) {
  92700. this.rightController._gazeTracker.isVisible = false;
  92701. }
  92702. }
  92703. },
  92704. enumerable: true,
  92705. configurable: true
  92706. });
  92707. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  92708. /**
  92709. * If the ray of the LaserPointer should be displayed.
  92710. */
  92711. get: function () {
  92712. return this._displayLaserPointer;
  92713. },
  92714. /**
  92715. * Sets if the ray of the LaserPointer should be displayed.
  92716. */
  92717. set: function (value) {
  92718. this._displayLaserPointer = value;
  92719. if (!value) {
  92720. if (this.rightController) {
  92721. this.rightController._deactivatePointer();
  92722. this.rightController._gazeTracker.isVisible = false;
  92723. }
  92724. if (this.leftController) {
  92725. this.leftController._deactivatePointer();
  92726. this.leftController._gazeTracker.isVisible = false;
  92727. }
  92728. }
  92729. else {
  92730. if (this.rightController) {
  92731. this.rightController._activatePointer();
  92732. }
  92733. if (this.leftController) {
  92734. this.leftController._activatePointer();
  92735. }
  92736. }
  92737. },
  92738. enumerable: true,
  92739. configurable: true
  92740. });
  92741. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  92742. /**
  92743. * The deviceOrientationCamera used as the camera when not in VR.
  92744. */
  92745. get: function () {
  92746. return this._deviceOrientationCamera;
  92747. },
  92748. enumerable: true,
  92749. configurable: true
  92750. });
  92751. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  92752. /**
  92753. * Based on the current WebVR support, returns the current VR camera used.
  92754. */
  92755. get: function () {
  92756. if (this._webVRready) {
  92757. return this._webVRCamera;
  92758. }
  92759. else {
  92760. return this._scene.activeCamera;
  92761. }
  92762. },
  92763. enumerable: true,
  92764. configurable: true
  92765. });
  92766. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  92767. /**
  92768. * The webVRCamera which is used when in VR.
  92769. */
  92770. get: function () {
  92771. return this._webVRCamera;
  92772. },
  92773. enumerable: true,
  92774. configurable: true
  92775. });
  92776. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  92777. /**
  92778. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  92779. */
  92780. get: function () {
  92781. return this._vrDeviceOrientationCamera;
  92782. },
  92783. enumerable: true,
  92784. configurable: true
  92785. });
  92786. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  92787. get: function () {
  92788. var result = this._cameraGazer._teleportationRequestInitiated
  92789. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  92790. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  92791. return result;
  92792. },
  92793. enumerable: true,
  92794. configurable: true
  92795. });
  92796. // Raised when one of the controller has loaded successfully its associated default mesh
  92797. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  92798. if (this.leftController && this.leftController.webVRController == webVRController) {
  92799. if (webVRController.mesh) {
  92800. this.leftController._setLaserPointerParent(webVRController.mesh);
  92801. }
  92802. }
  92803. if (this.rightController && this.rightController.webVRController == webVRController) {
  92804. if (webVRController.mesh) {
  92805. this.rightController._setLaserPointerParent(webVRController.mesh);
  92806. }
  92807. }
  92808. try {
  92809. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  92810. }
  92811. catch (err) {
  92812. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  92813. }
  92814. };
  92815. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  92816. /**
  92817. * Gets a value indicating if we are currently in VR mode.
  92818. */
  92819. get: function () {
  92820. return this._webVRpresenting || this._fullscreenVRpresenting;
  92821. },
  92822. enumerable: true,
  92823. configurable: true
  92824. });
  92825. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  92826. var vrDisplay = this._scene.getEngine().getVRDevice();
  92827. if (vrDisplay) {
  92828. var wasPresenting = this._webVRpresenting;
  92829. // A VR display is connected
  92830. this._webVRpresenting = vrDisplay.isPresenting;
  92831. if (wasPresenting && !this._webVRpresenting)
  92832. this.exitVR();
  92833. }
  92834. else {
  92835. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  92836. }
  92837. this.updateButtonVisibility();
  92838. };
  92839. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  92840. this._webVRsupported = eventArgs.vrSupported;
  92841. this._webVRready = !!eventArgs.vrDisplay;
  92842. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  92843. this.updateButtonVisibility();
  92844. };
  92845. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  92846. if (this._canvas && !this._useCustomVRButton) {
  92847. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  92848. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  92849. }
  92850. };
  92851. VRExperienceHelper.prototype.displayVRButton = function () {
  92852. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  92853. document.body.appendChild(this._btnVR);
  92854. this._btnVRDisplayed = true;
  92855. }
  92856. };
  92857. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  92858. if (!this._btnVR || this._useCustomVRButton) {
  92859. return;
  92860. }
  92861. this._btnVR.className = "babylonVRicon";
  92862. if (this.isInVRMode) {
  92863. this._btnVR.className += " vrdisplaypresenting";
  92864. }
  92865. else {
  92866. if (this._webVRready)
  92867. this._btnVR.className += " vrdisplayready";
  92868. if (this._webVRsupported)
  92869. this._btnVR.className += " vrdisplaysupported";
  92870. if (this._webVRrequesting)
  92871. this._btnVR.className += " vrdisplayrequesting";
  92872. }
  92873. };
  92874. /**
  92875. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  92876. * Otherwise, will use the fullscreen API.
  92877. */
  92878. VRExperienceHelper.prototype.enterVR = function () {
  92879. if (this.onEnteringVRObservable) {
  92880. try {
  92881. this.onEnteringVRObservable.notifyObservers(this);
  92882. }
  92883. catch (err) {
  92884. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  92885. }
  92886. }
  92887. if (this._scene.activeCamera) {
  92888. this._position = this._scene.activeCamera.position.clone();
  92889. // make sure that we return to the last active camera
  92890. this._existingCamera = this._scene.activeCamera;
  92891. }
  92892. if (this._webVRrequesting)
  92893. return;
  92894. // If WebVR is supported and a headset is connected
  92895. if (this._webVRready) {
  92896. if (!this._webVRpresenting) {
  92897. this._webVRCamera.position = this._position;
  92898. this._scene.activeCamera = this._webVRCamera;
  92899. }
  92900. }
  92901. else if (this._vrDeviceOrientationCamera) {
  92902. this._vrDeviceOrientationCamera.position = this._position;
  92903. if (this._scene.activeCamera) {
  92904. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92905. }
  92906. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  92907. this._scene.getEngine().switchFullscreen(true);
  92908. this.updateButtonVisibility();
  92909. }
  92910. if (this._scene.activeCamera && this._canvas) {
  92911. this._scene.activeCamera.attachControl(this._canvas);
  92912. }
  92913. if (this._interactionsEnabled) {
  92914. this._scene.registerBeforeRender(this.beforeRender);
  92915. }
  92916. };
  92917. /**
  92918. * Attempt to exit VR, or fullscreen.
  92919. */
  92920. VRExperienceHelper.prototype.exitVR = function () {
  92921. if (this.onExitingVRObservable) {
  92922. try {
  92923. this.onExitingVRObservable.notifyObservers(this);
  92924. }
  92925. catch (err) {
  92926. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  92927. }
  92928. }
  92929. if (this._webVRpresenting) {
  92930. this._scene.getEngine().disableVR();
  92931. }
  92932. if (this._scene.activeCamera) {
  92933. this._position = this._scene.activeCamera.position.clone();
  92934. }
  92935. if (this._deviceOrientationCamera) {
  92936. this._deviceOrientationCamera.position = this._position;
  92937. this._scene.activeCamera = this._deviceOrientationCamera;
  92938. if (this._canvas) {
  92939. this._scene.activeCamera.attachControl(this._canvas);
  92940. }
  92941. }
  92942. else if (this._existingCamera) {
  92943. this._existingCamera.position = this._position;
  92944. this._scene.activeCamera = this._existingCamera;
  92945. }
  92946. this.updateButtonVisibility();
  92947. if (this._interactionsEnabled) {
  92948. this._scene.unregisterBeforeRender(this.beforeRender);
  92949. }
  92950. // resize to update width and height when exiting vr exits fullscreen
  92951. this._scene.getEngine().resize();
  92952. };
  92953. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  92954. /**
  92955. * The position of the vr experience helper.
  92956. */
  92957. get: function () {
  92958. return this._position;
  92959. },
  92960. /**
  92961. * Sets the position of the vr experience helper.
  92962. */
  92963. set: function (value) {
  92964. this._position = value;
  92965. if (this._scene.activeCamera) {
  92966. this._scene.activeCamera.position = value;
  92967. }
  92968. },
  92969. enumerable: true,
  92970. configurable: true
  92971. });
  92972. /**
  92973. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  92974. */
  92975. VRExperienceHelper.prototype.enableInteractions = function () {
  92976. var _this = this;
  92977. if (!this._interactionsEnabled) {
  92978. this._interactionsRequested = true;
  92979. if (this.leftController) {
  92980. this._enableInteractionOnController(this.leftController);
  92981. }
  92982. if (this.rightController) {
  92983. this._enableInteractionOnController(this.rightController);
  92984. }
  92985. this.raySelectionPredicate = function (mesh) {
  92986. return mesh.isVisible;
  92987. };
  92988. this.meshSelectionPredicate = function (mesh) {
  92989. return true;
  92990. };
  92991. this._raySelectionPredicate = function (mesh) {
  92992. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  92993. && mesh.name.indexOf("teleportationTarget") === -1
  92994. && mesh.name.indexOf("torusTeleportation") === -1
  92995. && mesh.name.indexOf("laserPointer") === -1)) {
  92996. return _this.raySelectionPredicate(mesh);
  92997. }
  92998. return false;
  92999. };
  93000. this._interactionsEnabled = true;
  93001. }
  93002. };
  93003. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  93004. get: function () {
  93005. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  93006. },
  93007. enumerable: true,
  93008. configurable: true
  93009. });
  93010. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  93011. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  93012. if (this._floorMeshesCollection[i].id === mesh.id) {
  93013. return true;
  93014. }
  93015. }
  93016. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  93017. return true;
  93018. }
  93019. return false;
  93020. };
  93021. /**
  93022. * Adds a floor mesh to be used for teleportation.
  93023. * @param floorMesh the mesh to be used for teleportation.
  93024. */
  93025. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  93026. if (!this._floorMeshesCollection) {
  93027. return;
  93028. }
  93029. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  93030. return;
  93031. }
  93032. this._floorMeshesCollection.push(floorMesh);
  93033. };
  93034. /**
  93035. * Removes a floor mesh from being used for teleportation.
  93036. * @param floorMesh the mesh to be removed.
  93037. */
  93038. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  93039. if (!this._floorMeshesCollection) {
  93040. return;
  93041. }
  93042. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  93043. if (meshIndex !== -1) {
  93044. this._floorMeshesCollection.splice(meshIndex, 1);
  93045. }
  93046. };
  93047. /**
  93048. * Enables interactions and teleportation using the VR controllers and gaze.
  93049. * @param vrTeleportationOptions options to modify teleportation behavior.
  93050. */
  93051. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  93052. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  93053. if (!this._teleportationInitialized) {
  93054. this._teleportationRequested = true;
  93055. this.enableInteractions();
  93056. if (vrTeleportationOptions.floorMeshName) {
  93057. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  93058. }
  93059. if (vrTeleportationOptions.floorMeshes) {
  93060. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  93061. }
  93062. if (this.leftController != null) {
  93063. this._enableTeleportationOnController(this.leftController);
  93064. }
  93065. if (this.rightController != null) {
  93066. this._enableTeleportationOnController(this.rightController);
  93067. }
  93068. // Creates an image processing post process for the vignette not relying
  93069. // on the main scene configuration for image processing to reduce setup and spaces
  93070. // (gamma/linear) conflicts.
  93071. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  93072. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  93073. imageProcessingConfiguration.vignetteEnabled = true;
  93074. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  93075. this._webVRCamera.detachPostProcess(this._postProcessMove);
  93076. this._teleportationInitialized = true;
  93077. if (this._isDefaultTeleportationTarget) {
  93078. this._createTeleportationCircles();
  93079. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  93080. }
  93081. }
  93082. };
  93083. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  93084. var _this = this;
  93085. var controllerMesh = controller.webVRController.mesh;
  93086. if (controllerMesh) {
  93087. controller._interactionsEnabled = true;
  93088. controller._activatePointer();
  93089. if (this.webVROptions.laserToggle) {
  93090. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  93091. // Enabling / disabling laserPointer
  93092. if (_this._displayLaserPointer && stateObject.value === 1) {
  93093. if (controller._activePointer) {
  93094. controller._deactivatePointer();
  93095. }
  93096. else {
  93097. controller._activatePointer();
  93098. }
  93099. if (_this.displayGaze) {
  93100. controller._gazeTracker.isVisible = controller._activePointer;
  93101. }
  93102. }
  93103. });
  93104. }
  93105. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  93106. var gazer = controller;
  93107. if (_this._noControllerIsActive) {
  93108. gazer = _this._cameraGazer;
  93109. }
  93110. if (!gazer._pointerDownOnMeshAsked) {
  93111. if (stateObject.value > _this._padSensibilityUp) {
  93112. gazer._selectionPointerDown();
  93113. }
  93114. }
  93115. else if (stateObject.value < _this._padSensibilityDown) {
  93116. gazer._selectionPointerUp();
  93117. }
  93118. });
  93119. }
  93120. };
  93121. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  93122. // Dont teleport if another gaze already requested teleportation
  93123. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  93124. return;
  93125. }
  93126. if (!gazer._teleportationRequestInitiated) {
  93127. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  93128. gazer._activatePointer();
  93129. gazer._teleportationRequestInitiated = true;
  93130. }
  93131. }
  93132. else {
  93133. // Listening to the proper controller values changes to confirm teleportation
  93134. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  93135. if (this._teleportActive) {
  93136. this._teleportCamera(this._haloCenter);
  93137. }
  93138. gazer._teleportationRequestInitiated = false;
  93139. }
  93140. }
  93141. };
  93142. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  93143. // Only rotate when user is not currently selecting a teleportation location
  93144. if (gazer._teleportationRequestInitiated) {
  93145. return;
  93146. }
  93147. if (!gazer._rotationLeftAsked) {
  93148. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  93149. gazer._rotationLeftAsked = true;
  93150. if (this._rotationAllowed) {
  93151. this._rotateCamera(false);
  93152. }
  93153. }
  93154. }
  93155. else {
  93156. if (stateObject.x > -this._padSensibilityDown) {
  93157. gazer._rotationLeftAsked = false;
  93158. }
  93159. }
  93160. if (!gazer._rotationRightAsked) {
  93161. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  93162. gazer._rotationRightAsked = true;
  93163. if (this._rotationAllowed) {
  93164. this._rotateCamera(true);
  93165. }
  93166. }
  93167. }
  93168. else {
  93169. if (stateObject.x < this._padSensibilityDown) {
  93170. gazer._rotationRightAsked = false;
  93171. }
  93172. }
  93173. };
  93174. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  93175. // Only teleport backwards when user is not currently selecting a teleportation location
  93176. if (gazer._teleportationRequestInitiated) {
  93177. return;
  93178. }
  93179. // Teleport backwards
  93180. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  93181. if (!gazer._teleportationBackRequestInitiated) {
  93182. if (!this.currentVRCamera) {
  93183. return;
  93184. }
  93185. // Get rotation and position of the current camera
  93186. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  93187. var position = this.currentVRCamera.position;
  93188. // If the camera has device position, use that instead
  93189. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  93190. rotation = this.currentVRCamera.deviceRotationQuaternion;
  93191. position = this.currentVRCamera.devicePosition;
  93192. }
  93193. // Get matrix with only the y rotation of the device rotation
  93194. rotation.toEulerAnglesToRef(this._workingVector);
  93195. this._workingVector.z = 0;
  93196. this._workingVector.x = 0;
  93197. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  93198. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  93199. // Rotate backwards ray by device rotation to cast at the ground behind the user
  93200. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  93201. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  93202. var ray = new BABYLON.Ray(position, this._workingVector);
  93203. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93204. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  93205. this._teleportCamera(hit.pickedPoint);
  93206. }
  93207. gazer._teleportationBackRequestInitiated = true;
  93208. }
  93209. }
  93210. else {
  93211. gazer._teleportationBackRequestInitiated = false;
  93212. }
  93213. };
  93214. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  93215. var _this = this;
  93216. var controllerMesh = controller.webVRController.mesh;
  93217. if (controllerMesh) {
  93218. if (!controller._interactionsEnabled) {
  93219. this._enableInteractionOnController(controller);
  93220. }
  93221. controller._interactionsEnabled = true;
  93222. controller._teleportationEnabled = true;
  93223. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93224. controller._dpadPressed = false;
  93225. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  93226. controller._dpadPressed = stateObject.pressed;
  93227. if (!controller._dpadPressed) {
  93228. controller._rotationLeftAsked = false;
  93229. controller._rotationRightAsked = false;
  93230. controller._teleportationBackRequestInitiated = false;
  93231. }
  93232. });
  93233. }
  93234. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  93235. if (_this.teleportationEnabled) {
  93236. _this._checkTeleportBackwards(stateObject, controller);
  93237. _this._checkTeleportWithRay(stateObject, controller);
  93238. }
  93239. _this._checkRotate(stateObject, controller);
  93240. });
  93241. }
  93242. };
  93243. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  93244. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  93245. this._teleportationTarget.isPickable = false;
  93246. var length = 512;
  93247. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  93248. dynamicTexture.hasAlpha = true;
  93249. var context = dynamicTexture.getContext();
  93250. var centerX = length / 2;
  93251. var centerY = length / 2;
  93252. var radius = 200;
  93253. context.beginPath();
  93254. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93255. context.fillStyle = this._teleportationFillColor;
  93256. context.fill();
  93257. context.lineWidth = 10;
  93258. context.strokeStyle = this._teleportationBorderColor;
  93259. context.stroke();
  93260. context.closePath();
  93261. dynamicTexture.update();
  93262. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93263. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93264. this._teleportationTarget.material = teleportationCircleMaterial;
  93265. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93266. torus.isPickable = false;
  93267. torus.parent = this._teleportationTarget;
  93268. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93269. var keys = [];
  93270. keys.push({
  93271. frame: 0,
  93272. value: 0
  93273. });
  93274. keys.push({
  93275. frame: 30,
  93276. value: 0.4
  93277. });
  93278. keys.push({
  93279. frame: 60,
  93280. value: 0
  93281. });
  93282. animationInnerCircle.setKeys(keys);
  93283. var easingFunction = new BABYLON.SineEase();
  93284. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93285. animationInnerCircle.setEasingFunction(easingFunction);
  93286. torus.animations = [];
  93287. torus.animations.push(animationInnerCircle);
  93288. this._scene.beginAnimation(torus, 0, 60, true);
  93289. this._hideTeleportationTarget();
  93290. };
  93291. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93292. this._teleportActive = true;
  93293. if (this._teleportationInitialized) {
  93294. this._teleportationTarget.isVisible = true;
  93295. if (this._isDefaultTeleportationTarget) {
  93296. this._teleportationTarget.getChildren()[0].isVisible = true;
  93297. }
  93298. }
  93299. };
  93300. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93301. this._teleportActive = false;
  93302. if (this._teleportationInitialized) {
  93303. this._teleportationTarget.isVisible = false;
  93304. if (this._isDefaultTeleportationTarget) {
  93305. this._teleportationTarget.getChildren()[0].isVisible = false;
  93306. }
  93307. }
  93308. };
  93309. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93310. var _this = this;
  93311. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93312. return;
  93313. }
  93314. if (right) {
  93315. this._rotationAngle++;
  93316. }
  93317. else {
  93318. this._rotationAngle--;
  93319. }
  93320. this.currentVRCamera.animations = [];
  93321. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93322. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93323. var animationRotationKeys = [];
  93324. animationRotationKeys.push({
  93325. frame: 0,
  93326. value: this.currentVRCamera.rotationQuaternion
  93327. });
  93328. animationRotationKeys.push({
  93329. frame: 6,
  93330. value: target
  93331. });
  93332. animationRotation.setKeys(animationRotationKeys);
  93333. animationRotation.setEasingFunction(this._circleEase);
  93334. this.currentVRCamera.animations.push(animationRotation);
  93335. this._postProcessMove.animations = [];
  93336. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93337. var vignetteWeightKeys = [];
  93338. vignetteWeightKeys.push({
  93339. frame: 0,
  93340. value: 0
  93341. });
  93342. vignetteWeightKeys.push({
  93343. frame: 3,
  93344. value: 4
  93345. });
  93346. vignetteWeightKeys.push({
  93347. frame: 6,
  93348. value: 0
  93349. });
  93350. animationPP.setKeys(vignetteWeightKeys);
  93351. animationPP.setEasingFunction(this._circleEase);
  93352. this._postProcessMove.animations.push(animationPP);
  93353. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93354. var vignetteStretchKeys = [];
  93355. vignetteStretchKeys.push({
  93356. frame: 0,
  93357. value: 0
  93358. });
  93359. vignetteStretchKeys.push({
  93360. frame: 3,
  93361. value: 10
  93362. });
  93363. vignetteStretchKeys.push({
  93364. frame: 6,
  93365. value: 0
  93366. });
  93367. animationPP2.setKeys(vignetteStretchKeys);
  93368. animationPP2.setEasingFunction(this._circleEase);
  93369. this._postProcessMove.animations.push(animationPP2);
  93370. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93371. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93372. this._postProcessMove.samples = 4;
  93373. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93374. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  93375. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93376. });
  93377. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  93378. };
  93379. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  93380. if (hit.pickedPoint) {
  93381. if (gazer._teleportationRequestInitiated) {
  93382. this._displayTeleportationTarget();
  93383. this._haloCenter.copyFrom(hit.pickedPoint);
  93384. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  93385. }
  93386. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  93387. if (pickNormal) {
  93388. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93389. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93390. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  93391. }
  93392. this._teleportationTarget.position.y += 0.1;
  93393. }
  93394. };
  93395. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93396. var _this = this;
  93397. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93398. return;
  93399. }
  93400. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93401. // offset of the headset from the anchor.
  93402. if (this.webVRCamera.leftCamera) {
  93403. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93404. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93405. location.subtractToRef(this._workingVector, this._workingVector);
  93406. }
  93407. else {
  93408. this._workingVector.copyFrom(location);
  93409. }
  93410. // Add height to account for user's height offset
  93411. if (this.isInVRMode) {
  93412. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  93413. }
  93414. else {
  93415. this._workingVector.y += this._defaultHeight;
  93416. }
  93417. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  93418. // Create animation from the camera's position to the new location
  93419. this.currentVRCamera.animations = [];
  93420. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93421. var animationCameraTeleportationKeys = [{
  93422. frame: 0,
  93423. value: this.currentVRCamera.position
  93424. },
  93425. {
  93426. frame: 11,
  93427. value: this._workingVector
  93428. }
  93429. ];
  93430. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  93431. animationCameraTeleportation.setEasingFunction(this._circleEase);
  93432. this.currentVRCamera.animations.push(animationCameraTeleportation);
  93433. this._postProcessMove.animations = [];
  93434. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93435. var vignetteWeightKeys = [];
  93436. vignetteWeightKeys.push({
  93437. frame: 0,
  93438. value: 0
  93439. });
  93440. vignetteWeightKeys.push({
  93441. frame: 5,
  93442. value: 8
  93443. });
  93444. vignetteWeightKeys.push({
  93445. frame: 11,
  93446. value: 0
  93447. });
  93448. animationPP.setKeys(vignetteWeightKeys);
  93449. this._postProcessMove.animations.push(animationPP);
  93450. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93451. var vignetteStretchKeys = [];
  93452. vignetteStretchKeys.push({
  93453. frame: 0,
  93454. value: 0
  93455. });
  93456. vignetteStretchKeys.push({
  93457. frame: 5,
  93458. value: 10
  93459. });
  93460. vignetteStretchKeys.push({
  93461. frame: 11,
  93462. value: 0
  93463. });
  93464. animationPP2.setKeys(vignetteStretchKeys);
  93465. this._postProcessMove.animations.push(animationPP2);
  93466. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93467. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93468. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93469. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  93470. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93471. });
  93472. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  93473. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  93474. });
  93475. this._hideTeleportationTarget();
  93476. };
  93477. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  93478. if (normal) {
  93479. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  93480. if (angle < Math.PI / 2) {
  93481. normal.scaleInPlace(-1);
  93482. }
  93483. }
  93484. return normal;
  93485. };
  93486. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  93487. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93488. return;
  93489. }
  93490. var ray = gazer._getForwardRay(this._rayLength);
  93491. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93492. if (hit) {
  93493. // Populate the contrllers mesh that can be used for drag/drop
  93494. if (gazer._laserPointer) {
  93495. hit.originMesh = gazer._laserPointer.parent;
  93496. }
  93497. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  93498. }
  93499. gazer._currentHit = hit;
  93500. // Moving the gazeTracker on the mesh face targetted
  93501. if (hit && hit.pickedPoint) {
  93502. if (this._displayGaze) {
  93503. var multiplier = 1;
  93504. gazer._gazeTracker.isVisible = true;
  93505. if (gazer._isActionableMesh) {
  93506. multiplier = 3;
  93507. }
  93508. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  93509. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  93510. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  93511. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  93512. // To avoid z-fighting
  93513. var deltaFighting = 0.002;
  93514. if (pickNormal) {
  93515. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93516. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93517. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  93518. }
  93519. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  93520. if (gazer._gazeTracker.position.x < 0) {
  93521. gazer._gazeTracker.position.x += deltaFighting;
  93522. }
  93523. else {
  93524. gazer._gazeTracker.position.x -= deltaFighting;
  93525. }
  93526. if (gazer._gazeTracker.position.y < 0) {
  93527. gazer._gazeTracker.position.y += deltaFighting;
  93528. }
  93529. else {
  93530. gazer._gazeTracker.position.y -= deltaFighting;
  93531. }
  93532. if (gazer._gazeTracker.position.z < 0) {
  93533. gazer._gazeTracker.position.z += deltaFighting;
  93534. }
  93535. else {
  93536. gazer._gazeTracker.position.z -= deltaFighting;
  93537. }
  93538. }
  93539. // Changing the size of the laser pointer based on the distance from the targetted point
  93540. gazer._updatePointerDistance(hit.distance);
  93541. }
  93542. else {
  93543. gazer._updatePointerDistance();
  93544. gazer._gazeTracker.isVisible = false;
  93545. }
  93546. if (hit && hit.pickedMesh) {
  93547. // The object selected is the floor, we're in a teleportation scenario
  93548. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93549. // Moving the teleportation area to this targetted point
  93550. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93551. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93552. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93553. }
  93554. gazer._currentMeshSelected = null;
  93555. if (gazer._teleportationRequestInitiated) {
  93556. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93557. }
  93558. return;
  93559. }
  93560. // If not, we're in a selection scenario
  93561. //this._teleportationAllowed = false;
  93562. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93563. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93564. this.onNewMeshPicked.notifyObservers(hit);
  93565. gazer._currentMeshSelected = hit.pickedMesh;
  93566. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93567. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93568. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93569. gazer._isActionableMesh = true;
  93570. }
  93571. else {
  93572. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93573. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93574. gazer._isActionableMesh = false;
  93575. }
  93576. try {
  93577. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93578. }
  93579. catch (err) {
  93580. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93581. }
  93582. }
  93583. else {
  93584. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93585. gazer._currentMeshSelected = null;
  93586. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93587. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93588. }
  93589. }
  93590. }
  93591. else {
  93592. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93593. gazer._currentMeshSelected = null;
  93594. //this._teleportationAllowed = false;
  93595. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93596. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93597. }
  93598. };
  93599. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93600. if (mesh) {
  93601. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93602. }
  93603. };
  93604. /**
  93605. * Sets the color of the laser ray from the vr controllers.
  93606. * @param color new color for the ray.
  93607. */
  93608. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  93609. if (this.leftController) {
  93610. this.leftController._setLaserPointerColor(color);
  93611. }
  93612. if (this.rightController) {
  93613. this.rightController._setLaserPointerColor(color);
  93614. }
  93615. };
  93616. /**
  93617. * Sets the color of the ray from the vr headsets gaze.
  93618. * @param color new color for the ray.
  93619. */
  93620. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  93621. if (!this._cameraGazer._gazeTracker.material) {
  93622. return;
  93623. }
  93624. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  93625. if (this.leftController) {
  93626. this.leftController._gazeTracker.material.emissiveColor = color;
  93627. }
  93628. if (this.rightController) {
  93629. this.rightController._gazeTracker.material.emissiveColor = color;
  93630. }
  93631. };
  93632. /**
  93633. * Exits VR and disposes of the vr experience helper
  93634. */
  93635. VRExperienceHelper.prototype.dispose = function () {
  93636. if (this.isInVRMode) {
  93637. this.exitVR();
  93638. }
  93639. if (this._postProcessMove) {
  93640. this._postProcessMove.dispose();
  93641. }
  93642. if (this._webVRCamera) {
  93643. this._webVRCamera.dispose();
  93644. }
  93645. if (this._vrDeviceOrientationCamera) {
  93646. this._vrDeviceOrientationCamera.dispose();
  93647. }
  93648. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  93649. document.body.removeChild(this._btnVR);
  93650. }
  93651. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  93652. this._deviceOrientationCamera.dispose();
  93653. }
  93654. if (this._cameraGazer) {
  93655. this._cameraGazer.dispose();
  93656. }
  93657. if (this.leftController) {
  93658. this.leftController.dispose();
  93659. }
  93660. if (this.rightController) {
  93661. this.rightController.dispose();
  93662. }
  93663. if (this._teleportationTarget) {
  93664. this._teleportationTarget.dispose();
  93665. }
  93666. this._floorMeshesCollection = [];
  93667. document.removeEventListener("keydown", this._onKeyDown);
  93668. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93669. window.removeEventListener("resize", this._onResize);
  93670. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  93671. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  93672. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  93673. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  93674. document.onmsfullscreenchange = null;
  93675. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  93676. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  93677. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  93678. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93679. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  93680. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  93681. this._scene.unregisterBeforeRender(this.beforeRender);
  93682. };
  93683. /**
  93684. * Gets the name of the VRExperienceHelper class
  93685. * @returns "VRExperienceHelper"
  93686. */
  93687. VRExperienceHelper.prototype.getClassName = function () {
  93688. return "VRExperienceHelper";
  93689. };
  93690. return VRExperienceHelper;
  93691. }());
  93692. BABYLON.VRExperienceHelper = VRExperienceHelper;
  93693. })(BABYLON || (BABYLON = {}));
  93694. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  93695. // Mainly based on these 2 articles :
  93696. // 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
  93697. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  93698. var BABYLON;
  93699. (function (BABYLON) {
  93700. /**
  93701. * Defines the potential axis of a Joystick
  93702. */
  93703. var JoystickAxis;
  93704. (function (JoystickAxis) {
  93705. /** X axis */
  93706. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  93707. /** Y axis */
  93708. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  93709. /** Z axis */
  93710. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  93711. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  93712. /**
  93713. * Class used to define virtual joystick (used in touch mode)
  93714. */
  93715. var VirtualJoystick = /** @class */ (function () {
  93716. /**
  93717. * Creates a new virtual joystick
  93718. * @param leftJoystick defines that the joystick is for left hand (false by default)
  93719. */
  93720. function VirtualJoystick(leftJoystick) {
  93721. var _this = this;
  93722. if (leftJoystick) {
  93723. this._leftJoystick = true;
  93724. }
  93725. else {
  93726. this._leftJoystick = false;
  93727. }
  93728. VirtualJoystick._globalJoystickIndex++;
  93729. // By default left & right arrow keys are moving the X
  93730. // and up & down keys are moving the Y
  93731. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93732. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93733. this.reverseLeftRight = false;
  93734. this.reverseUpDown = false;
  93735. // collections of pointers
  93736. this._touches = new BABYLON.StringDictionary();
  93737. this.deltaPosition = BABYLON.Vector3.Zero();
  93738. this._joystickSensibility = 25;
  93739. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93740. this._onResize = function (evt) {
  93741. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93742. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93743. if (VirtualJoystick.vjCanvas) {
  93744. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  93745. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  93746. }
  93747. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  93748. };
  93749. // injecting a canvas element on top of the canvas 3D game
  93750. if (!VirtualJoystick.vjCanvas) {
  93751. window.addEventListener("resize", this._onResize, false);
  93752. VirtualJoystick.vjCanvas = document.createElement("canvas");
  93753. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93754. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93755. VirtualJoystick.vjCanvas.width = window.innerWidth;
  93756. VirtualJoystick.vjCanvas.height = window.innerHeight;
  93757. VirtualJoystick.vjCanvas.style.width = "100%";
  93758. VirtualJoystick.vjCanvas.style.height = "100%";
  93759. VirtualJoystick.vjCanvas.style.position = "absolute";
  93760. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  93761. VirtualJoystick.vjCanvas.style.top = "0px";
  93762. VirtualJoystick.vjCanvas.style.left = "0px";
  93763. VirtualJoystick.vjCanvas.style.zIndex = "5";
  93764. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  93765. // Support for jQuery PEP polyfill
  93766. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  93767. var context = VirtualJoystick.vjCanvas.getContext('2d');
  93768. if (!context) {
  93769. throw new Error("Unable to create canvas for virtual joystick");
  93770. }
  93771. VirtualJoystick.vjCanvasContext = context;
  93772. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  93773. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93774. document.body.appendChild(VirtualJoystick.vjCanvas);
  93775. }
  93776. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  93777. this.pressed = false;
  93778. // default joystick color
  93779. this._joystickColor = "cyan";
  93780. this._joystickPointerID = -1;
  93781. // current joystick position
  93782. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  93783. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  93784. // origin joystick position
  93785. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  93786. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  93787. this._onPointerDownHandlerRef = function (evt) {
  93788. _this._onPointerDown(evt);
  93789. };
  93790. this._onPointerMoveHandlerRef = function (evt) {
  93791. _this._onPointerMove(evt);
  93792. };
  93793. this._onPointerUpHandlerRef = function (evt) {
  93794. _this._onPointerUp(evt);
  93795. };
  93796. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  93797. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  93798. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  93799. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  93800. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  93801. evt.preventDefault(); // Disables system menu
  93802. }, false);
  93803. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93804. }
  93805. /**
  93806. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  93807. * @param newJoystickSensibility defines the new sensibility
  93808. */
  93809. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  93810. this._joystickSensibility = newJoystickSensibility;
  93811. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93812. };
  93813. VirtualJoystick.prototype._onPointerDown = function (e) {
  93814. var positionOnScreenCondition;
  93815. e.preventDefault();
  93816. if (this._leftJoystick === true) {
  93817. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  93818. }
  93819. else {
  93820. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  93821. }
  93822. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  93823. // First contact will be dedicated to the virtual joystick
  93824. this._joystickPointerID = e.pointerId;
  93825. this._joystickPointerStartPos.x = e.clientX;
  93826. this._joystickPointerStartPos.y = e.clientY;
  93827. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  93828. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  93829. this._deltaJoystickVector.x = 0;
  93830. this._deltaJoystickVector.y = 0;
  93831. this.pressed = true;
  93832. this._touches.add(e.pointerId.toString(), e);
  93833. }
  93834. else {
  93835. // You can only trigger the action buttons with a joystick declared
  93836. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  93837. this._action();
  93838. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  93839. }
  93840. }
  93841. };
  93842. VirtualJoystick.prototype._onPointerMove = function (e) {
  93843. // If the current pointer is the one associated to the joystick (first touch contact)
  93844. if (this._joystickPointerID == e.pointerId) {
  93845. this._joystickPointerPos.x = e.clientX;
  93846. this._joystickPointerPos.y = e.clientY;
  93847. this._deltaJoystickVector = this._joystickPointerPos.clone();
  93848. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  93849. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  93850. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  93851. switch (this._axisTargetedByLeftAndRight) {
  93852. case JoystickAxis.X:
  93853. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  93854. break;
  93855. case JoystickAxis.Y:
  93856. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  93857. break;
  93858. case JoystickAxis.Z:
  93859. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  93860. break;
  93861. }
  93862. var directionUpDown = this.reverseUpDown ? 1 : -1;
  93863. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  93864. switch (this._axisTargetedByUpAndDown) {
  93865. case JoystickAxis.X:
  93866. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  93867. break;
  93868. case JoystickAxis.Y:
  93869. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  93870. break;
  93871. case JoystickAxis.Z:
  93872. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  93873. break;
  93874. }
  93875. }
  93876. else {
  93877. var data = this._touches.get(e.pointerId.toString());
  93878. if (data) {
  93879. data.x = e.clientX;
  93880. data.y = e.clientY;
  93881. }
  93882. }
  93883. };
  93884. VirtualJoystick.prototype._onPointerUp = function (e) {
  93885. if (this._joystickPointerID == e.pointerId) {
  93886. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  93887. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  93888. this._joystickPointerID = -1;
  93889. this.pressed = false;
  93890. }
  93891. else {
  93892. var touch = this._touches.get(e.pointerId.toString());
  93893. if (touch) {
  93894. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93895. }
  93896. }
  93897. this._deltaJoystickVector.x = 0;
  93898. this._deltaJoystickVector.y = 0;
  93899. this._touches.remove(e.pointerId.toString());
  93900. };
  93901. /**
  93902. * Change the color of the virtual joystick
  93903. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  93904. */
  93905. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  93906. this._joystickColor = newColor;
  93907. };
  93908. /**
  93909. * Defines a callback to call when the joystick is touched
  93910. * @param action defines the callback
  93911. */
  93912. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  93913. this._action = action;
  93914. };
  93915. /**
  93916. * Defines which axis you'd like to control for left & right
  93917. * @param axis defines the axis to use
  93918. */
  93919. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  93920. switch (axis) {
  93921. case JoystickAxis.X:
  93922. case JoystickAxis.Y:
  93923. case JoystickAxis.Z:
  93924. this._axisTargetedByLeftAndRight = axis;
  93925. break;
  93926. default:
  93927. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93928. break;
  93929. }
  93930. };
  93931. /**
  93932. * Defines which axis you'd like to control for up & down
  93933. * @param axis defines the axis to use
  93934. */
  93935. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  93936. switch (axis) {
  93937. case JoystickAxis.X:
  93938. case JoystickAxis.Y:
  93939. case JoystickAxis.Z:
  93940. this._axisTargetedByUpAndDown = axis;
  93941. break;
  93942. default:
  93943. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93944. break;
  93945. }
  93946. };
  93947. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  93948. var _this = this;
  93949. if (this.pressed) {
  93950. this._touches.forEach(function (key, touch) {
  93951. if (touch.pointerId === _this._joystickPointerID) {
  93952. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  93953. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  93954. VirtualJoystick.vjCanvasContext.beginPath();
  93955. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93956. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93957. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  93958. VirtualJoystick.vjCanvasContext.stroke();
  93959. VirtualJoystick.vjCanvasContext.closePath();
  93960. VirtualJoystick.vjCanvasContext.beginPath();
  93961. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93962. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93963. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  93964. VirtualJoystick.vjCanvasContext.stroke();
  93965. VirtualJoystick.vjCanvasContext.closePath();
  93966. VirtualJoystick.vjCanvasContext.beginPath();
  93967. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93968. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  93969. VirtualJoystick.vjCanvasContext.stroke();
  93970. VirtualJoystick.vjCanvasContext.closePath();
  93971. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  93972. }
  93973. else {
  93974. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93975. VirtualJoystick.vjCanvasContext.beginPath();
  93976. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  93977. VirtualJoystick.vjCanvasContext.beginPath();
  93978. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  93979. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93980. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  93981. VirtualJoystick.vjCanvasContext.stroke();
  93982. VirtualJoystick.vjCanvasContext.closePath();
  93983. touch.prevX = touch.x;
  93984. touch.prevY = touch.y;
  93985. }
  93986. ;
  93987. });
  93988. }
  93989. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93990. };
  93991. /**
  93992. * Release internal HTML canvas
  93993. */
  93994. VirtualJoystick.prototype.releaseCanvas = function () {
  93995. if (VirtualJoystick.vjCanvas) {
  93996. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  93997. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  93998. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  93999. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  94000. window.removeEventListener("resize", this._onResize);
  94001. document.body.removeChild(VirtualJoystick.vjCanvas);
  94002. VirtualJoystick.vjCanvas = null;
  94003. }
  94004. };
  94005. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  94006. VirtualJoystick._globalJoystickIndex = 0;
  94007. return VirtualJoystick;
  94008. }());
  94009. BABYLON.VirtualJoystick = VirtualJoystick;
  94010. })(BABYLON || (BABYLON = {}));
  94011. //# sourceMappingURL=babylon.virtualJoystick.js.map
  94012. var BABYLON;
  94013. (function (BABYLON) {
  94014. // We're mainly based on the logic defined into the FreeCamera code
  94015. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  94016. __extends(VirtualJoysticksCamera, _super);
  94017. function VirtualJoysticksCamera(name, position, scene) {
  94018. var _this = _super.call(this, name, position, scene) || this;
  94019. _this.inputs.addVirtualJoystick();
  94020. return _this;
  94021. }
  94022. VirtualJoysticksCamera.prototype.getClassName = function () {
  94023. return "VirtualJoysticksCamera";
  94024. };
  94025. return VirtualJoysticksCamera;
  94026. }(BABYLON.FreeCamera));
  94027. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  94028. })(BABYLON || (BABYLON = {}));
  94029. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  94030. var BABYLON;
  94031. (function (BABYLON) {
  94032. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  94033. function FreeCameraVirtualJoystickInput() {
  94034. }
  94035. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  94036. return this._leftjoystick;
  94037. };
  94038. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  94039. return this._rightjoystick;
  94040. };
  94041. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  94042. if (this._leftjoystick) {
  94043. var camera = this.camera;
  94044. var speed = camera._computeLocalCameraSpeed() * 50;
  94045. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  94046. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  94047. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  94048. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  94049. if (!this._leftjoystick.pressed) {
  94050. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  94051. }
  94052. if (!this._rightjoystick.pressed) {
  94053. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  94054. }
  94055. }
  94056. };
  94057. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  94058. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  94059. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  94060. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  94061. this._leftjoystick.setJoystickSensibility(0.15);
  94062. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  94063. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  94064. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  94065. this._rightjoystick.reverseUpDown = true;
  94066. this._rightjoystick.setJoystickSensibility(0.05);
  94067. this._rightjoystick.setJoystickColor("yellow");
  94068. };
  94069. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  94070. this._leftjoystick.releaseCanvas();
  94071. this._rightjoystick.releaseCanvas();
  94072. };
  94073. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  94074. return "FreeCameraVirtualJoystickInput";
  94075. };
  94076. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  94077. return "virtualJoystick";
  94078. };
  94079. return FreeCameraVirtualJoystickInput;
  94080. }());
  94081. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  94082. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  94083. })(BABYLON || (BABYLON = {}));
  94084. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  94085. var BABYLON;
  94086. (function (BABYLON) {
  94087. var SimplificationSettings = /** @class */ (function () {
  94088. function SimplificationSettings(quality, distance, optimizeMesh) {
  94089. this.quality = quality;
  94090. this.distance = distance;
  94091. this.optimizeMesh = optimizeMesh;
  94092. }
  94093. return SimplificationSettings;
  94094. }());
  94095. BABYLON.SimplificationSettings = SimplificationSettings;
  94096. var SimplificationQueue = /** @class */ (function () {
  94097. function SimplificationQueue() {
  94098. this.running = false;
  94099. this._simplificationArray = [];
  94100. }
  94101. SimplificationQueue.prototype.addTask = function (task) {
  94102. this._simplificationArray.push(task);
  94103. };
  94104. SimplificationQueue.prototype.executeNext = function () {
  94105. var task = this._simplificationArray.pop();
  94106. if (task) {
  94107. this.running = true;
  94108. this.runSimplification(task);
  94109. }
  94110. else {
  94111. this.running = false;
  94112. }
  94113. };
  94114. SimplificationQueue.prototype.runSimplification = function (task) {
  94115. var _this = this;
  94116. if (task.parallelProcessing) {
  94117. //parallel simplifier
  94118. task.settings.forEach(function (setting) {
  94119. var simplifier = _this.getSimplifier(task);
  94120. simplifier.simplify(setting, function (newMesh) {
  94121. task.mesh.addLODLevel(setting.distance, newMesh);
  94122. newMesh.isVisible = true;
  94123. //check if it is the last
  94124. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  94125. //all done, run the success callback.
  94126. task.successCallback();
  94127. }
  94128. _this.executeNext();
  94129. });
  94130. });
  94131. }
  94132. else {
  94133. //single simplifier.
  94134. var simplifier = this.getSimplifier(task);
  94135. var runDecimation = function (setting, callback) {
  94136. simplifier.simplify(setting, function (newMesh) {
  94137. task.mesh.addLODLevel(setting.distance, newMesh);
  94138. newMesh.isVisible = true;
  94139. //run the next quality level
  94140. callback();
  94141. });
  94142. };
  94143. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  94144. runDecimation(task.settings[loop.index], function () {
  94145. loop.executeNext();
  94146. });
  94147. }, function () {
  94148. //execution ended, run the success callback.
  94149. if (task.successCallback) {
  94150. task.successCallback();
  94151. }
  94152. _this.executeNext();
  94153. });
  94154. }
  94155. };
  94156. SimplificationQueue.prototype.getSimplifier = function (task) {
  94157. switch (task.simplificationType) {
  94158. case SimplificationType.QUADRATIC:
  94159. default:
  94160. return new QuadraticErrorSimplification(task.mesh);
  94161. }
  94162. };
  94163. return SimplificationQueue;
  94164. }());
  94165. BABYLON.SimplificationQueue = SimplificationQueue;
  94166. /**
  94167. * The implemented types of simplification
  94168. * At the moment only Quadratic Error Decimation is implemented
  94169. */
  94170. var SimplificationType;
  94171. (function (SimplificationType) {
  94172. /** Quadratic error decimation */
  94173. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  94174. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  94175. var DecimationTriangle = /** @class */ (function () {
  94176. function DecimationTriangle(vertices) {
  94177. this.vertices = vertices;
  94178. this.error = new Array(4);
  94179. this.deleted = false;
  94180. this.isDirty = false;
  94181. this.deletePending = false;
  94182. this.borderFactor = 0;
  94183. }
  94184. return DecimationTriangle;
  94185. }());
  94186. BABYLON.DecimationTriangle = DecimationTriangle;
  94187. var DecimationVertex = /** @class */ (function () {
  94188. function DecimationVertex(position, id) {
  94189. this.position = position;
  94190. this.id = id;
  94191. this.isBorder = true;
  94192. this.q = new QuadraticMatrix();
  94193. this.triangleCount = 0;
  94194. this.triangleStart = 0;
  94195. this.originalOffsets = [];
  94196. }
  94197. DecimationVertex.prototype.updatePosition = function (newPosition) {
  94198. this.position.copyFrom(newPosition);
  94199. };
  94200. return DecimationVertex;
  94201. }());
  94202. BABYLON.DecimationVertex = DecimationVertex;
  94203. var QuadraticMatrix = /** @class */ (function () {
  94204. function QuadraticMatrix(data) {
  94205. this.data = new Array(10);
  94206. for (var i = 0; i < 10; ++i) {
  94207. if (data && data[i]) {
  94208. this.data[i] = data[i];
  94209. }
  94210. else {
  94211. this.data[i] = 0;
  94212. }
  94213. }
  94214. }
  94215. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  94216. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  94217. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  94218. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  94219. return det;
  94220. };
  94221. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  94222. for (var i = 0; i < 10; ++i) {
  94223. this.data[i] += matrix.data[i];
  94224. }
  94225. };
  94226. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  94227. for (var i = 0; i < 10; ++i) {
  94228. this.data[i] += data[i];
  94229. }
  94230. };
  94231. QuadraticMatrix.prototype.add = function (matrix) {
  94232. var m = new QuadraticMatrix();
  94233. for (var i = 0; i < 10; ++i) {
  94234. m.data[i] = this.data[i] + matrix.data[i];
  94235. }
  94236. return m;
  94237. };
  94238. QuadraticMatrix.FromData = function (a, b, c, d) {
  94239. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  94240. };
  94241. //returning an array to avoid garbage collection
  94242. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  94243. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  94244. };
  94245. return QuadraticMatrix;
  94246. }());
  94247. BABYLON.QuadraticMatrix = QuadraticMatrix;
  94248. var Reference = /** @class */ (function () {
  94249. function Reference(vertexId, triangleId) {
  94250. this.vertexId = vertexId;
  94251. this.triangleId = triangleId;
  94252. }
  94253. return Reference;
  94254. }());
  94255. BABYLON.Reference = Reference;
  94256. /**
  94257. * An implementation of the Quadratic Error simplification algorithm.
  94258. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94259. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94260. * @author RaananW
  94261. */
  94262. var QuadraticErrorSimplification = /** @class */ (function () {
  94263. function QuadraticErrorSimplification(_mesh) {
  94264. this._mesh = _mesh;
  94265. this.syncIterations = 5000;
  94266. this.aggressiveness = 7;
  94267. this.decimationIterations = 100;
  94268. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94269. }
  94270. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94271. var _this = this;
  94272. this.initDecimatedMesh();
  94273. //iterating through the submeshes array, one after the other.
  94274. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94275. _this.initWithMesh(loop.index, function () {
  94276. _this.runDecimation(settings, loop.index, function () {
  94277. loop.executeNext();
  94278. });
  94279. }, settings.optimizeMesh);
  94280. }, function () {
  94281. setTimeout(function () {
  94282. successCallback(_this._reconstructedMesh);
  94283. }, 0);
  94284. });
  94285. };
  94286. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94287. var _this = this;
  94288. var targetCount = ~~(this.triangles.length * settings.quality);
  94289. var deletedTriangles = 0;
  94290. var triangleCount = this.triangles.length;
  94291. var iterationFunction = function (iteration, callback) {
  94292. setTimeout(function () {
  94293. if (iteration % 5 === 0) {
  94294. _this.updateMesh(iteration === 0);
  94295. }
  94296. for (var i = 0; i < _this.triangles.length; ++i) {
  94297. _this.triangles[i].isDirty = false;
  94298. }
  94299. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94300. var trianglesIterator = function (i) {
  94301. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94302. var t = _this.triangles[tIdx];
  94303. if (!t)
  94304. return;
  94305. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94306. return;
  94307. }
  94308. for (var j = 0; j < 3; ++j) {
  94309. if (t.error[j] < threshold) {
  94310. var deleted0 = [];
  94311. var deleted1 = [];
  94312. var v0 = t.vertices[j];
  94313. var v1 = t.vertices[(j + 1) % 3];
  94314. if (v0.isBorder || v1.isBorder)
  94315. continue;
  94316. var p = BABYLON.Vector3.Zero();
  94317. var n = BABYLON.Vector3.Zero();
  94318. var uv = BABYLON.Vector2.Zero();
  94319. var color = new BABYLON.Color4(0, 0, 0, 1);
  94320. _this.calculateError(v0, v1, p, n, uv, color);
  94321. var delTr = new Array();
  94322. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94323. continue;
  94324. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  94325. continue;
  94326. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  94327. continue;
  94328. var uniqueArray = new Array();
  94329. delTr.forEach(function (deletedT) {
  94330. if (uniqueArray.indexOf(deletedT) === -1) {
  94331. deletedT.deletePending = true;
  94332. uniqueArray.push(deletedT);
  94333. }
  94334. });
  94335. if (uniqueArray.length % 2 !== 0) {
  94336. continue;
  94337. }
  94338. v0.q = v1.q.add(v0.q);
  94339. v0.updatePosition(p);
  94340. var tStart = _this.references.length;
  94341. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  94342. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  94343. var tCount = _this.references.length - tStart;
  94344. if (tCount <= v0.triangleCount) {
  94345. if (tCount) {
  94346. for (var c = 0; c < tCount; c++) {
  94347. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  94348. }
  94349. }
  94350. }
  94351. else {
  94352. v0.triangleStart = tStart;
  94353. }
  94354. v0.triangleCount = tCount;
  94355. break;
  94356. }
  94357. }
  94358. };
  94359. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  94360. }, 0);
  94361. };
  94362. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  94363. if (triangleCount - deletedTriangles <= targetCount)
  94364. loop.breakLoop();
  94365. else {
  94366. iterationFunction(loop.index, function () {
  94367. loop.executeNext();
  94368. });
  94369. }
  94370. }, function () {
  94371. setTimeout(function () {
  94372. //reconstruct this part of the mesh
  94373. _this.reconstructMesh(submeshIndex);
  94374. successCallback();
  94375. }, 0);
  94376. });
  94377. };
  94378. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  94379. var _this = this;
  94380. this.vertices = [];
  94381. this.triangles = [];
  94382. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94383. var indices = this._mesh.getIndices();
  94384. var submesh = this._mesh.subMeshes[submeshIndex];
  94385. var findInVertices = function (positionToSearch) {
  94386. if (optimizeMesh) {
  94387. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  94388. if (_this.vertices[ii].position.equals(positionToSearch)) {
  94389. return _this.vertices[ii];
  94390. }
  94391. }
  94392. }
  94393. return null;
  94394. };
  94395. var vertexReferences = [];
  94396. var vertexInit = function (i) {
  94397. if (!positionData) {
  94398. return;
  94399. }
  94400. var offset = i + submesh.verticesStart;
  94401. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94402. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94403. vertex.originalOffsets.push(offset);
  94404. if (vertex.id === _this.vertices.length) {
  94405. _this.vertices.push(vertex);
  94406. }
  94407. vertexReferences.push(vertex.id);
  94408. };
  94409. //var totalVertices = mesh.getTotalVertices();
  94410. var totalVertices = submesh.verticesCount;
  94411. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  94412. var indicesInit = function (i) {
  94413. if (!indices) {
  94414. return;
  94415. }
  94416. var offset = (submesh.indexStart / 3) + i;
  94417. var pos = (offset * 3);
  94418. var i0 = indices[pos + 0];
  94419. var i1 = indices[pos + 1];
  94420. var i2 = indices[pos + 2];
  94421. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  94422. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  94423. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  94424. var triangle = new DecimationTriangle([v0, v1, v2]);
  94425. triangle.originalOffset = pos;
  94426. _this.triangles.push(triangle);
  94427. };
  94428. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  94429. _this.init(callback);
  94430. });
  94431. });
  94432. };
  94433. QuadraticErrorSimplification.prototype.init = function (callback) {
  94434. var _this = this;
  94435. var triangleInit1 = function (i) {
  94436. var t = _this.triangles[i];
  94437. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  94438. for (var j = 0; j < 3; j++) {
  94439. 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))));
  94440. }
  94441. };
  94442. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  94443. var triangleInit2 = function (i) {
  94444. var t = _this.triangles[i];
  94445. for (var j = 0; j < 3; ++j) {
  94446. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  94447. }
  94448. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94449. };
  94450. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  94451. callback();
  94452. });
  94453. });
  94454. };
  94455. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  94456. var newTriangles = [];
  94457. var i;
  94458. for (i = 0; i < this.vertices.length; ++i) {
  94459. this.vertices[i].triangleCount = 0;
  94460. }
  94461. var t;
  94462. var j;
  94463. for (i = 0; i < this.triangles.length; ++i) {
  94464. if (!this.triangles[i].deleted) {
  94465. t = this.triangles[i];
  94466. for (j = 0; j < 3; ++j) {
  94467. t.vertices[j].triangleCount = 1;
  94468. }
  94469. newTriangles.push(t);
  94470. }
  94471. }
  94472. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  94473. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  94474. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  94475. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  94476. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  94477. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94478. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  94479. var vertexCount = 0;
  94480. for (i = 0; i < this.vertices.length; ++i) {
  94481. var vertex = this.vertices[i];
  94482. vertex.id = vertexCount;
  94483. if (vertex.triangleCount) {
  94484. vertex.originalOffsets.forEach(function (originalOffset) {
  94485. if (!normalData) {
  94486. return;
  94487. }
  94488. newPositionData.push(vertex.position.x);
  94489. newPositionData.push(vertex.position.y);
  94490. newPositionData.push(vertex.position.z);
  94491. newNormalData.push(normalData[originalOffset * 3]);
  94492. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  94493. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  94494. if (uvs && uvs.length) {
  94495. newUVsData.push(uvs[(originalOffset * 2)]);
  94496. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  94497. }
  94498. else if (colorsData && colorsData.length) {
  94499. newColorsData.push(colorsData[(originalOffset * 4)]);
  94500. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  94501. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  94502. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  94503. }
  94504. ++vertexCount;
  94505. });
  94506. }
  94507. }
  94508. var startingIndex = this._reconstructedMesh.getTotalIndices();
  94509. var startingVertex = this._reconstructedMesh.getTotalVertices();
  94510. var submeshesArray = this._reconstructedMesh.subMeshes;
  94511. this._reconstructedMesh.subMeshes = [];
  94512. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  94513. var originalIndices = this._mesh.getIndices();
  94514. for (i = 0; i < newTriangles.length; ++i) {
  94515. t = newTriangles[i]; //now get the new referencing point for each vertex
  94516. [0, 1, 2].forEach(function (idx) {
  94517. var id = originalIndices[t.originalOffset + idx];
  94518. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  94519. if (offset < 0)
  94520. offset = 0;
  94521. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  94522. });
  94523. }
  94524. //overwriting the old vertex buffers and indices.
  94525. this._reconstructedMesh.setIndices(newIndicesArray);
  94526. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  94527. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  94528. if (newUVsData.length > 0)
  94529. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  94530. if (newColorsData.length > 0)
  94531. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  94532. //create submesh
  94533. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  94534. if (submeshIndex > 0) {
  94535. this._reconstructedMesh.subMeshes = [];
  94536. submeshesArray.forEach(function (submesh) {
  94537. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94538. });
  94539. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94540. }
  94541. };
  94542. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94543. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94544. this._reconstructedMesh.material = this._mesh.material;
  94545. this._reconstructedMesh.parent = this._mesh.parent;
  94546. this._reconstructedMesh.isVisible = false;
  94547. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94548. };
  94549. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94550. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94551. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94552. if (t.deleted)
  94553. continue;
  94554. var s = this.references[vertex1.triangleStart + i].vertexId;
  94555. var v1 = t.vertices[(s + 1) % 3];
  94556. var v2 = t.vertices[(s + 2) % 3];
  94557. if ((v1 === vertex2 || v2 === vertex2)) {
  94558. deletedArray[i] = true;
  94559. delTr.push(t);
  94560. continue;
  94561. }
  94562. var d1 = v1.position.subtract(point);
  94563. d1 = d1.normalize();
  94564. var d2 = v2.position.subtract(point);
  94565. d2 = d2.normalize();
  94566. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94567. return true;
  94568. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94569. deletedArray[i] = false;
  94570. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94571. return true;
  94572. }
  94573. return false;
  94574. };
  94575. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94576. var newDeleted = deletedTriangles;
  94577. for (var i = 0; i < vertex.triangleCount; ++i) {
  94578. var ref = this.references[vertex.triangleStart + i];
  94579. var t = this.triangles[ref.triangleId];
  94580. if (t.deleted)
  94581. continue;
  94582. if (deletedArray[i] && t.deletePending) {
  94583. t.deleted = true;
  94584. newDeleted++;
  94585. continue;
  94586. }
  94587. t.vertices[ref.vertexId] = origVertex;
  94588. t.isDirty = true;
  94589. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94590. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94591. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94592. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94593. this.references.push(ref);
  94594. }
  94595. return newDeleted;
  94596. };
  94597. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94598. for (var i = 0; i < this.vertices.length; ++i) {
  94599. var vCount = [];
  94600. var vId = [];
  94601. var v = this.vertices[i];
  94602. var j;
  94603. for (j = 0; j < v.triangleCount; ++j) {
  94604. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  94605. for (var ii = 0; ii < 3; ii++) {
  94606. var ofs = 0;
  94607. var vv = triangle.vertices[ii];
  94608. while (ofs < vCount.length) {
  94609. if (vId[ofs] === vv.id)
  94610. break;
  94611. ++ofs;
  94612. }
  94613. if (ofs === vCount.length) {
  94614. vCount.push(1);
  94615. vId.push(vv.id);
  94616. }
  94617. else {
  94618. vCount[ofs]++;
  94619. }
  94620. }
  94621. }
  94622. for (j = 0; j < vCount.length; ++j) {
  94623. if (vCount[j] === 1) {
  94624. this.vertices[vId[j]].isBorder = true;
  94625. }
  94626. else {
  94627. this.vertices[vId[j]].isBorder = false;
  94628. }
  94629. }
  94630. }
  94631. };
  94632. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  94633. if (identifyBorders === void 0) { identifyBorders = false; }
  94634. var i;
  94635. if (!identifyBorders) {
  94636. var newTrianglesVector = [];
  94637. for (i = 0; i < this.triangles.length; ++i) {
  94638. if (!this.triangles[i].deleted) {
  94639. newTrianglesVector.push(this.triangles[i]);
  94640. }
  94641. }
  94642. this.triangles = newTrianglesVector;
  94643. }
  94644. for (i = 0; i < this.vertices.length; ++i) {
  94645. this.vertices[i].triangleCount = 0;
  94646. this.vertices[i].triangleStart = 0;
  94647. }
  94648. var t;
  94649. var j;
  94650. var v;
  94651. for (i = 0; i < this.triangles.length; ++i) {
  94652. t = this.triangles[i];
  94653. for (j = 0; j < 3; ++j) {
  94654. v = t.vertices[j];
  94655. v.triangleCount++;
  94656. }
  94657. }
  94658. var tStart = 0;
  94659. for (i = 0; i < this.vertices.length; ++i) {
  94660. this.vertices[i].triangleStart = tStart;
  94661. tStart += this.vertices[i].triangleCount;
  94662. this.vertices[i].triangleCount = 0;
  94663. }
  94664. var newReferences = new Array(this.triangles.length * 3);
  94665. for (i = 0; i < this.triangles.length; ++i) {
  94666. t = this.triangles[i];
  94667. for (j = 0; j < 3; ++j) {
  94668. v = t.vertices[j];
  94669. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  94670. v.triangleCount++;
  94671. }
  94672. }
  94673. this.references = newReferences;
  94674. if (identifyBorders) {
  94675. this.identifyBorder();
  94676. }
  94677. };
  94678. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  94679. var x = point.x;
  94680. var y = point.y;
  94681. var z = point.z;
  94682. 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
  94683. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  94684. };
  94685. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  94686. var q = vertex1.q.add(vertex2.q);
  94687. var border = vertex1.isBorder && vertex2.isBorder;
  94688. var error = 0;
  94689. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  94690. if (qDet !== 0 && !border) {
  94691. if (!pointResult) {
  94692. pointResult = BABYLON.Vector3.Zero();
  94693. }
  94694. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  94695. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  94696. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  94697. error = this.vertexError(q, pointResult);
  94698. }
  94699. else {
  94700. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  94701. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  94702. var error1 = this.vertexError(q, vertex1.position);
  94703. var error2 = this.vertexError(q, vertex2.position);
  94704. var error3 = this.vertexError(q, p3);
  94705. error = Math.min(error1, error2, error3);
  94706. if (error === error1) {
  94707. if (pointResult) {
  94708. pointResult.copyFrom(vertex1.position);
  94709. }
  94710. }
  94711. else if (error === error2) {
  94712. if (pointResult) {
  94713. pointResult.copyFrom(vertex2.position);
  94714. }
  94715. }
  94716. else {
  94717. if (pointResult) {
  94718. pointResult.copyFrom(p3);
  94719. }
  94720. }
  94721. }
  94722. return error;
  94723. };
  94724. return QuadraticErrorSimplification;
  94725. }());
  94726. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  94727. })(BABYLON || (BABYLON = {}));
  94728. //# sourceMappingURL=babylon.meshSimplification.js.map
  94729. var BABYLON;
  94730. (function (BABYLON) {
  94731. var MeshLODLevel = /** @class */ (function () {
  94732. function MeshLODLevel(distance, mesh) {
  94733. this.distance = distance;
  94734. this.mesh = mesh;
  94735. }
  94736. return MeshLODLevel;
  94737. }());
  94738. BABYLON.MeshLODLevel = MeshLODLevel;
  94739. })(BABYLON || (BABYLON = {}));
  94740. //# sourceMappingURL=babylon.meshLODLevel.js.map
  94741. var BABYLON;
  94742. (function (BABYLON) {
  94743. /**
  94744. * Defines the root class used to create scene optimization to use with SceneOptimizer
  94745. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94746. */
  94747. var SceneOptimization = /** @class */ (function () {
  94748. /**
  94749. * Creates the SceneOptimization object
  94750. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94751. * @param desc defines the description associated with the optimization
  94752. */
  94753. function SceneOptimization(
  94754. /**
  94755. * Defines the priority of this optimization (0 by default which means first in the list)
  94756. */
  94757. priority) {
  94758. if (priority === void 0) { priority = 0; }
  94759. this.priority = priority;
  94760. }
  94761. /**
  94762. * Gets a string describing the action executed by the current optimization
  94763. * @returns description string
  94764. */
  94765. SceneOptimization.prototype.getDescription = function () {
  94766. return "";
  94767. };
  94768. /**
  94769. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94770. * @param scene defines the current scene where to apply this optimization
  94771. * @param optimizer defines the current optimizer
  94772. * @returns true if everything that can be done was applied
  94773. */
  94774. SceneOptimization.prototype.apply = function (scene, optimizer) {
  94775. return true;
  94776. };
  94777. ;
  94778. return SceneOptimization;
  94779. }());
  94780. BABYLON.SceneOptimization = SceneOptimization;
  94781. /**
  94782. * Defines an optimization used to reduce the size of render target textures
  94783. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94784. */
  94785. var TextureOptimization = /** @class */ (function (_super) {
  94786. __extends(TextureOptimization, _super);
  94787. /**
  94788. * Creates the TextureOptimization object
  94789. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94790. * @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
  94791. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94792. */
  94793. function TextureOptimization(
  94794. /**
  94795. * Defines the priority of this optimization (0 by default which means first in the list)
  94796. */
  94797. priority,
  94798. /**
  94799. * 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
  94800. */
  94801. maximumSize,
  94802. /**
  94803. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94804. */
  94805. step) {
  94806. if (priority === void 0) { priority = 0; }
  94807. if (maximumSize === void 0) { maximumSize = 1024; }
  94808. if (step === void 0) { step = 0.5; }
  94809. var _this = _super.call(this, priority) || this;
  94810. _this.priority = priority;
  94811. _this.maximumSize = maximumSize;
  94812. _this.step = step;
  94813. return _this;
  94814. }
  94815. /**
  94816. * Gets a string describing the action executed by the current optimization
  94817. * @returns description string
  94818. */
  94819. TextureOptimization.prototype.getDescription = function () {
  94820. return "Reducing render target texture size to " + this.maximumSize;
  94821. };
  94822. /**
  94823. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94824. * @param scene defines the current scene where to apply this optimization
  94825. * @param optimizer defines the current optimizer
  94826. * @returns true if everything that can be done was applied
  94827. */
  94828. TextureOptimization.prototype.apply = function (scene, optimizer) {
  94829. var allDone = true;
  94830. for (var index = 0; index < scene.textures.length; index++) {
  94831. var texture = scene.textures[index];
  94832. if (!texture.canRescale || texture.getContext) {
  94833. continue;
  94834. }
  94835. var currentSize = texture.getSize();
  94836. var maxDimension = Math.max(currentSize.width, currentSize.height);
  94837. if (maxDimension > this.maximumSize) {
  94838. texture.scale(this.step);
  94839. allDone = false;
  94840. }
  94841. }
  94842. return allDone;
  94843. };
  94844. return TextureOptimization;
  94845. }(SceneOptimization));
  94846. BABYLON.TextureOptimization = TextureOptimization;
  94847. /**
  94848. * Defines an optimization used to increase or decrease the rendering resolution
  94849. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94850. */
  94851. var HardwareScalingOptimization = /** @class */ (function (_super) {
  94852. __extends(HardwareScalingOptimization, _super);
  94853. /**
  94854. * Creates the HardwareScalingOptimization object
  94855. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94856. * @param maximumScale defines the maximum scale to use (2 by default)
  94857. * @param step defines the step to use between two passes (0.5 by default)
  94858. */
  94859. function HardwareScalingOptimization(
  94860. /**
  94861. * Defines the priority of this optimization (0 by default which means first in the list)
  94862. */
  94863. priority,
  94864. /**
  94865. * Defines the maximum scale to use (2 by default)
  94866. */
  94867. maximumScale,
  94868. /**
  94869. * Defines the step to use between two passes (0.5 by default)
  94870. */
  94871. step) {
  94872. if (priority === void 0) { priority = 0; }
  94873. if (maximumScale === void 0) { maximumScale = 2; }
  94874. if (step === void 0) { step = 0.25; }
  94875. var _this = _super.call(this, priority) || this;
  94876. _this.priority = priority;
  94877. _this.maximumScale = maximumScale;
  94878. _this.step = step;
  94879. _this._currentScale = -1;
  94880. _this._directionOffset = 1;
  94881. return _this;
  94882. }
  94883. /**
  94884. * Gets a string describing the action executed by the current optimization
  94885. * @return description string
  94886. */
  94887. HardwareScalingOptimization.prototype.getDescription = function () {
  94888. return "Setting hardware scaling level to " + this._currentScale;
  94889. };
  94890. /**
  94891. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94892. * @param scene defines the current scene where to apply this optimization
  94893. * @param optimizer defines the current optimizer
  94894. * @returns true if everything that can be done was applied
  94895. */
  94896. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  94897. if (this._currentScale === -1) {
  94898. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  94899. if (this._currentScale > this.maximumScale) {
  94900. this._directionOffset = -1;
  94901. }
  94902. }
  94903. this._currentScale += this._directionOffset * this.step;
  94904. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  94905. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  94906. };
  94907. ;
  94908. return HardwareScalingOptimization;
  94909. }(SceneOptimization));
  94910. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  94911. /**
  94912. * Defines an optimization used to remove shadows
  94913. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94914. */
  94915. var ShadowsOptimization = /** @class */ (function (_super) {
  94916. __extends(ShadowsOptimization, _super);
  94917. function ShadowsOptimization() {
  94918. return _super !== null && _super.apply(this, arguments) || this;
  94919. }
  94920. /**
  94921. * Gets a string describing the action executed by the current optimization
  94922. * @return description string
  94923. */
  94924. ShadowsOptimization.prototype.getDescription = function () {
  94925. return "Turning shadows on/off";
  94926. };
  94927. /**
  94928. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94929. * @param scene defines the current scene where to apply this optimization
  94930. * @param optimizer defines the current optimizer
  94931. * @returns true if everything that can be done was applied
  94932. */
  94933. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  94934. scene.shadowsEnabled = optimizer.isInImprovementMode;
  94935. return true;
  94936. };
  94937. ;
  94938. return ShadowsOptimization;
  94939. }(SceneOptimization));
  94940. BABYLON.ShadowsOptimization = ShadowsOptimization;
  94941. /**
  94942. * Defines an optimization used to turn post-processes off
  94943. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94944. */
  94945. var PostProcessesOptimization = /** @class */ (function (_super) {
  94946. __extends(PostProcessesOptimization, _super);
  94947. function PostProcessesOptimization() {
  94948. return _super !== null && _super.apply(this, arguments) || this;
  94949. }
  94950. /**
  94951. * Gets a string describing the action executed by the current optimization
  94952. * @return description string
  94953. */
  94954. PostProcessesOptimization.prototype.getDescription = function () {
  94955. return "Turning post-processes on/off";
  94956. };
  94957. /**
  94958. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94959. * @param scene defines the current scene where to apply this optimization
  94960. * @param optimizer defines the current optimizer
  94961. * @returns true if everything that can be done was applied
  94962. */
  94963. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  94964. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  94965. return true;
  94966. };
  94967. ;
  94968. return PostProcessesOptimization;
  94969. }(SceneOptimization));
  94970. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  94971. /**
  94972. * Defines an optimization used to turn lens flares off
  94973. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94974. */
  94975. var LensFlaresOptimization = /** @class */ (function (_super) {
  94976. __extends(LensFlaresOptimization, _super);
  94977. function LensFlaresOptimization() {
  94978. return _super !== null && _super.apply(this, arguments) || this;
  94979. }
  94980. /**
  94981. * Gets a string describing the action executed by the current optimization
  94982. * @return description string
  94983. */
  94984. LensFlaresOptimization.prototype.getDescription = function () {
  94985. return "Turning lens flares on/off";
  94986. };
  94987. /**
  94988. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94989. * @param scene defines the current scene where to apply this optimization
  94990. * @param optimizer defines the current optimizer
  94991. * @returns true if everything that can be done was applied
  94992. */
  94993. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  94994. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  94995. return true;
  94996. };
  94997. ;
  94998. return LensFlaresOptimization;
  94999. }(SceneOptimization));
  95000. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  95001. /**
  95002. * Defines an optimization based on user defined callback.
  95003. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95004. */
  95005. var CustomOptimization = /** @class */ (function (_super) {
  95006. __extends(CustomOptimization, _super);
  95007. function CustomOptimization() {
  95008. return _super !== null && _super.apply(this, arguments) || this;
  95009. }
  95010. /**
  95011. * Gets a string describing the action executed by the current optimization
  95012. * @returns description string
  95013. */
  95014. CustomOptimization.prototype.getDescription = function () {
  95015. if (this.onGetDescription) {
  95016. return this.onGetDescription();
  95017. }
  95018. return "Running user defined callback";
  95019. };
  95020. /**
  95021. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95022. * @param scene defines the current scene where to apply this optimization
  95023. * @param optimizer defines the current optimizer
  95024. * @returns true if everything that can be done was applied
  95025. */
  95026. CustomOptimization.prototype.apply = function (scene, optimizer) {
  95027. if (this.onApply) {
  95028. return this.onApply(scene, optimizer);
  95029. }
  95030. return true;
  95031. };
  95032. ;
  95033. return CustomOptimization;
  95034. }(SceneOptimization));
  95035. BABYLON.CustomOptimization = CustomOptimization;
  95036. /**
  95037. * Defines an optimization used to turn particles off
  95038. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95039. */
  95040. var ParticlesOptimization = /** @class */ (function (_super) {
  95041. __extends(ParticlesOptimization, _super);
  95042. function ParticlesOptimization() {
  95043. return _super !== null && _super.apply(this, arguments) || this;
  95044. }
  95045. /**
  95046. * Gets a string describing the action executed by the current optimization
  95047. * @return description string
  95048. */
  95049. ParticlesOptimization.prototype.getDescription = function () {
  95050. return "Turning particles on/off";
  95051. };
  95052. /**
  95053. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95054. * @param scene defines the current scene where to apply this optimization
  95055. * @param optimizer defines the current optimizer
  95056. * @returns true if everything that can be done was applied
  95057. */
  95058. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  95059. scene.particlesEnabled = optimizer.isInImprovementMode;
  95060. return true;
  95061. };
  95062. ;
  95063. return ParticlesOptimization;
  95064. }(SceneOptimization));
  95065. BABYLON.ParticlesOptimization = ParticlesOptimization;
  95066. /**
  95067. * Defines an optimization used to turn render targets off
  95068. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95069. */
  95070. var RenderTargetsOptimization = /** @class */ (function (_super) {
  95071. __extends(RenderTargetsOptimization, _super);
  95072. function RenderTargetsOptimization() {
  95073. return _super !== null && _super.apply(this, arguments) || this;
  95074. }
  95075. /**
  95076. * Gets a string describing the action executed by the current optimization
  95077. * @return description string
  95078. */
  95079. RenderTargetsOptimization.prototype.getDescription = function () {
  95080. return "Turning render targets off";
  95081. };
  95082. /**
  95083. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95084. * @param scene defines the current scene where to apply this optimization
  95085. * @param optimizer defines the current optimizer
  95086. * @returns true if everything that can be done was applied
  95087. */
  95088. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  95089. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  95090. return true;
  95091. };
  95092. ;
  95093. return RenderTargetsOptimization;
  95094. }(SceneOptimization));
  95095. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  95096. /**
  95097. * Defines an optimization used to merge meshes with compatible materials
  95098. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95099. */
  95100. var MergeMeshesOptimization = /** @class */ (function (_super) {
  95101. __extends(MergeMeshesOptimization, _super);
  95102. function MergeMeshesOptimization() {
  95103. var _this = _super !== null && _super.apply(this, arguments) || this;
  95104. _this._canBeMerged = function (abstractMesh) {
  95105. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  95106. return false;
  95107. }
  95108. var mesh = abstractMesh;
  95109. if (!mesh.isVisible || !mesh.isEnabled()) {
  95110. return false;
  95111. }
  95112. if (mesh.instances.length > 0) {
  95113. return false;
  95114. }
  95115. if (mesh.skeleton || mesh.hasLODLevels) {
  95116. return false;
  95117. }
  95118. if (mesh.parent) {
  95119. return false;
  95120. }
  95121. return true;
  95122. };
  95123. return _this;
  95124. }
  95125. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  95126. /**
  95127. * Gets or sets a boolean which defines if optimization octree has to be updated
  95128. */
  95129. get: function () {
  95130. return MergeMeshesOptimization._UpdateSelectionTree;
  95131. },
  95132. /**
  95133. * Gets or sets a boolean which defines if optimization octree has to be updated
  95134. */
  95135. set: function (value) {
  95136. MergeMeshesOptimization._UpdateSelectionTree = value;
  95137. },
  95138. enumerable: true,
  95139. configurable: true
  95140. });
  95141. /**
  95142. * Gets a string describing the action executed by the current optimization
  95143. * @return description string
  95144. */
  95145. MergeMeshesOptimization.prototype.getDescription = function () {
  95146. return "Merging similar meshes together";
  95147. };
  95148. /**
  95149. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95150. * @param scene defines the current scene where to apply this optimization
  95151. * @param optimizer defines the current optimizer
  95152. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  95153. * @returns true if everything that can be done was applied
  95154. */
  95155. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  95156. var globalPool = scene.meshes.slice(0);
  95157. var globalLength = globalPool.length;
  95158. for (var index = 0; index < globalLength; index++) {
  95159. var currentPool = new Array();
  95160. var current = globalPool[index];
  95161. // Checks
  95162. if (!this._canBeMerged(current)) {
  95163. continue;
  95164. }
  95165. currentPool.push(current);
  95166. // Find compatible meshes
  95167. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  95168. var otherMesh = globalPool[subIndex];
  95169. if (!this._canBeMerged(otherMesh)) {
  95170. continue;
  95171. }
  95172. if (otherMesh.material !== current.material) {
  95173. continue;
  95174. }
  95175. if (otherMesh.checkCollisions !== current.checkCollisions) {
  95176. continue;
  95177. }
  95178. currentPool.push(otherMesh);
  95179. globalLength--;
  95180. globalPool.splice(subIndex, 1);
  95181. subIndex--;
  95182. }
  95183. if (currentPool.length < 2) {
  95184. continue;
  95185. }
  95186. // Merge meshes
  95187. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  95188. }
  95189. if (updateSelectionTree != undefined) {
  95190. if (updateSelectionTree) {
  95191. scene.createOrUpdateSelectionOctree();
  95192. }
  95193. }
  95194. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  95195. scene.createOrUpdateSelectionOctree();
  95196. }
  95197. return true;
  95198. };
  95199. ;
  95200. MergeMeshesOptimization._UpdateSelectionTree = false;
  95201. return MergeMeshesOptimization;
  95202. }(SceneOptimization));
  95203. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  95204. /**
  95205. * Defines a list of options used by SceneOptimizer
  95206. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95207. */
  95208. var SceneOptimizerOptions = /** @class */ (function () {
  95209. /**
  95210. * Creates a new list of options used by SceneOptimizer
  95211. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  95212. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  95213. */
  95214. function SceneOptimizerOptions(
  95215. /**
  95216. * Defines the target frame rate to reach (60 by default)
  95217. */
  95218. targetFrameRate,
  95219. /**
  95220. * Defines the interval between two checkes (2000ms by default)
  95221. */
  95222. trackerDuration) {
  95223. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  95224. if (trackerDuration === void 0) { trackerDuration = 2000; }
  95225. this.targetFrameRate = targetFrameRate;
  95226. this.trackerDuration = trackerDuration;
  95227. /**
  95228. * Gets the list of optimizations to apply
  95229. */
  95230. this.optimizations = new Array();
  95231. }
  95232. /**
  95233. * Add a new optimization
  95234. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  95235. * @returns the current SceneOptimizerOptions
  95236. */
  95237. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  95238. this.optimizations.push(optimization);
  95239. return this;
  95240. };
  95241. /**
  95242. * Add a new custom optimization
  95243. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  95244. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  95245. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95246. * @returns the current SceneOptimizerOptions
  95247. */
  95248. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  95249. if (priority === void 0) { priority = 0; }
  95250. var optimization = new CustomOptimization(priority);
  95251. optimization.onApply = onApply;
  95252. optimization.onGetDescription = onGetDescription;
  95253. this.optimizations.push(optimization);
  95254. return this;
  95255. };
  95256. /**
  95257. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95258. * @param targetFrameRate defines the target frame rate (60 by default)
  95259. * @returns a SceneOptimizerOptions object
  95260. */
  95261. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95262. var result = new SceneOptimizerOptions(targetFrameRate);
  95263. var priority = 0;
  95264. result.addOptimization(new MergeMeshesOptimization(priority));
  95265. result.addOptimization(new ShadowsOptimization(priority));
  95266. result.addOptimization(new LensFlaresOptimization(priority));
  95267. // Next priority
  95268. priority++;
  95269. result.addOptimization(new PostProcessesOptimization(priority));
  95270. result.addOptimization(new ParticlesOptimization(priority));
  95271. // Next priority
  95272. priority++;
  95273. result.addOptimization(new TextureOptimization(priority, 1024));
  95274. return result;
  95275. };
  95276. /**
  95277. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95278. * @param targetFrameRate defines the target frame rate (60 by default)
  95279. * @returns a SceneOptimizerOptions object
  95280. */
  95281. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95282. var result = new SceneOptimizerOptions(targetFrameRate);
  95283. var priority = 0;
  95284. result.addOptimization(new MergeMeshesOptimization(priority));
  95285. result.addOptimization(new ShadowsOptimization(priority));
  95286. result.addOptimization(new LensFlaresOptimization(priority));
  95287. // Next priority
  95288. priority++;
  95289. result.addOptimization(new PostProcessesOptimization(priority));
  95290. result.addOptimization(new ParticlesOptimization(priority));
  95291. // Next priority
  95292. priority++;
  95293. result.addOptimization(new TextureOptimization(priority, 512));
  95294. // Next priority
  95295. priority++;
  95296. result.addOptimization(new RenderTargetsOptimization(priority));
  95297. // Next priority
  95298. priority++;
  95299. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95300. return result;
  95301. };
  95302. /**
  95303. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95304. * @param targetFrameRate defines the target frame rate (60 by default)
  95305. * @returns a SceneOptimizerOptions object
  95306. */
  95307. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95308. var result = new SceneOptimizerOptions(targetFrameRate);
  95309. var priority = 0;
  95310. result.addOptimization(new MergeMeshesOptimization(priority));
  95311. result.addOptimization(new ShadowsOptimization(priority));
  95312. result.addOptimization(new LensFlaresOptimization(priority));
  95313. // Next priority
  95314. priority++;
  95315. result.addOptimization(new PostProcessesOptimization(priority));
  95316. result.addOptimization(new ParticlesOptimization(priority));
  95317. // Next priority
  95318. priority++;
  95319. result.addOptimization(new TextureOptimization(priority, 256));
  95320. // Next priority
  95321. priority++;
  95322. result.addOptimization(new RenderTargetsOptimization(priority));
  95323. // Next priority
  95324. priority++;
  95325. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  95326. return result;
  95327. };
  95328. return SceneOptimizerOptions;
  95329. }());
  95330. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  95331. /**
  95332. * Class used to run optimizations in order to reach a target frame rate
  95333. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95334. */
  95335. var SceneOptimizer = /** @class */ (function () {
  95336. /**
  95337. * Creates a new SceneOptimizer
  95338. * @param scene defines the scene to work on
  95339. * @param options defines the options to use with the SceneOptimizer
  95340. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  95341. * @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)
  95342. */
  95343. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  95344. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  95345. if (improvementMode === void 0) { improvementMode = false; }
  95346. var _this = this;
  95347. this._isRunning = false;
  95348. this._currentPriorityLevel = 0;
  95349. this._targetFrameRate = 60;
  95350. this._trackerDuration = 2000;
  95351. this._currentFrameRate = 0;
  95352. this._improvementMode = false;
  95353. /**
  95354. * Defines an observable called when the optimizer reaches the target frame rate
  95355. */
  95356. this.onSuccessObservable = new BABYLON.Observable();
  95357. /**
  95358. * Defines an observable called when the optimizer enables an optimization
  95359. */
  95360. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  95361. /**
  95362. * Defines an observable called when the optimizer is not able to reach the target frame rate
  95363. */
  95364. this.onFailureObservable = new BABYLON.Observable();
  95365. if (!options) {
  95366. this._options = new SceneOptimizerOptions();
  95367. }
  95368. else {
  95369. this._options = options;
  95370. }
  95371. if (this._options.targetFrameRate) {
  95372. this._targetFrameRate = this._options.targetFrameRate;
  95373. }
  95374. if (this._options.trackerDuration) {
  95375. this._trackerDuration = this._options.trackerDuration;
  95376. }
  95377. if (autoGeneratePriorities) {
  95378. var priority = 0;
  95379. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  95380. var optim = _a[_i];
  95381. optim.priority = priority++;
  95382. }
  95383. }
  95384. this._improvementMode = improvementMode;
  95385. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95386. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  95387. _this._sceneDisposeObserver = null;
  95388. _this.dispose();
  95389. });
  95390. }
  95391. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  95392. /**
  95393. * Gets a boolean indicating if the optimizer is in improvement mode
  95394. */
  95395. get: function () {
  95396. return this._improvementMode;
  95397. },
  95398. enumerable: true,
  95399. configurable: true
  95400. });
  95401. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95402. /**
  95403. * Gets the current priority level (0 at start)
  95404. */
  95405. get: function () {
  95406. return this._currentPriorityLevel;
  95407. },
  95408. enumerable: true,
  95409. configurable: true
  95410. });
  95411. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  95412. /**
  95413. * Gets the current frame rate checked by the SceneOptimizer
  95414. */
  95415. get: function () {
  95416. return this._currentFrameRate;
  95417. },
  95418. enumerable: true,
  95419. configurable: true
  95420. });
  95421. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  95422. /**
  95423. * Gets or sets the current target frame rate (60 by default)
  95424. */
  95425. get: function () {
  95426. return this._targetFrameRate;
  95427. },
  95428. /**
  95429. * Gets or sets the current target frame rate (60 by default)
  95430. */
  95431. set: function (value) {
  95432. this._targetFrameRate = value;
  95433. },
  95434. enumerable: true,
  95435. configurable: true
  95436. });
  95437. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  95438. /**
  95439. * Gets or sets the current interval between two checks (every 2000ms by default)
  95440. */
  95441. get: function () {
  95442. return this._trackerDuration;
  95443. },
  95444. /**
  95445. * Gets or sets the current interval between two checks (every 2000ms by default)
  95446. */
  95447. set: function (value) {
  95448. this._trackerDuration = value;
  95449. },
  95450. enumerable: true,
  95451. configurable: true
  95452. });
  95453. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  95454. /**
  95455. * Gets the list of active optimizations
  95456. */
  95457. get: function () {
  95458. return this._options.optimizations;
  95459. },
  95460. enumerable: true,
  95461. configurable: true
  95462. });
  95463. /**
  95464. * Stops the current optimizer
  95465. */
  95466. SceneOptimizer.prototype.stop = function () {
  95467. this._isRunning = false;
  95468. };
  95469. /**
  95470. * Reset the optimizer to initial step (current priority level = 0)
  95471. */
  95472. SceneOptimizer.prototype.reset = function () {
  95473. this._currentPriorityLevel = 0;
  95474. };
  95475. /**
  95476. * Start the optimizer. By default it will try to reach a specific framerate
  95477. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  95478. */
  95479. SceneOptimizer.prototype.start = function () {
  95480. var _this = this;
  95481. if (this._isRunning) {
  95482. return;
  95483. }
  95484. this._isRunning = true;
  95485. // Let's wait for the scene to be ready before running our check
  95486. this._scene.executeWhenReady(function () {
  95487. setTimeout(function () {
  95488. _this._checkCurrentState();
  95489. }, _this._trackerDuration);
  95490. });
  95491. };
  95492. SceneOptimizer.prototype._checkCurrentState = function () {
  95493. var _this = this;
  95494. if (!this._isRunning) {
  95495. return;
  95496. }
  95497. var scene = this._scene;
  95498. var options = this._options;
  95499. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  95500. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  95501. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  95502. this._isRunning = false;
  95503. this.onSuccessObservable.notifyObservers(this);
  95504. return;
  95505. }
  95506. // Apply current level of optimizations
  95507. var allDone = true;
  95508. var noOptimizationApplied = true;
  95509. for (var index = 0; index < options.optimizations.length; index++) {
  95510. var optimization = options.optimizations[index];
  95511. if (optimization.priority === this._currentPriorityLevel) {
  95512. noOptimizationApplied = false;
  95513. allDone = allDone && optimization.apply(scene, this);
  95514. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  95515. }
  95516. }
  95517. // If no optimization was applied, this is a failure :(
  95518. if (noOptimizationApplied) {
  95519. this._isRunning = false;
  95520. this.onFailureObservable.notifyObservers(this);
  95521. return;
  95522. }
  95523. // If all optimizations were done, move to next level
  95524. if (allDone) {
  95525. this._currentPriorityLevel++;
  95526. }
  95527. // Let's the system running for a specific amount of time before checking FPS
  95528. scene.executeWhenReady(function () {
  95529. setTimeout(function () {
  95530. _this._checkCurrentState();
  95531. }, _this._trackerDuration);
  95532. });
  95533. };
  95534. /**
  95535. * Release all resources
  95536. */
  95537. SceneOptimizer.prototype.dispose = function () {
  95538. this.stop();
  95539. this.onSuccessObservable.clear();
  95540. this.onFailureObservable.clear();
  95541. this.onNewOptimizationAppliedObservable.clear();
  95542. if (this._sceneDisposeObserver) {
  95543. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95544. }
  95545. };
  95546. /**
  95547. * Helper function to create a SceneOptimizer with one single line of code
  95548. * @param scene defines the scene to work on
  95549. * @param options defines the options to use with the SceneOptimizer
  95550. * @param onSuccess defines a callback to call on success
  95551. * @param onFailure defines a callback to call on failure
  95552. * @returns the new SceneOptimizer object
  95553. */
  95554. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95555. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95556. if (onSuccess) {
  95557. optimizer.onSuccessObservable.add(function () {
  95558. onSuccess();
  95559. });
  95560. }
  95561. if (onFailure) {
  95562. optimizer.onFailureObservable.add(function () {
  95563. onFailure();
  95564. });
  95565. }
  95566. optimizer.start();
  95567. return optimizer;
  95568. };
  95569. return SceneOptimizer;
  95570. }());
  95571. BABYLON.SceneOptimizer = SceneOptimizer;
  95572. })(BABYLON || (BABYLON = {}));
  95573. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95574. var BABYLON;
  95575. (function (BABYLON) {
  95576. var OutlineRenderer = /** @class */ (function () {
  95577. function OutlineRenderer(scene) {
  95578. this.zOffset = 1;
  95579. this._scene = scene;
  95580. }
  95581. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95582. var _this = this;
  95583. if (useOverlay === void 0) { useOverlay = false; }
  95584. var scene = this._scene;
  95585. var engine = this._scene.getEngine();
  95586. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95587. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95588. return;
  95589. }
  95590. var mesh = subMesh.getRenderingMesh();
  95591. var material = subMesh.getMaterial();
  95592. if (!material || !scene.activeCamera) {
  95593. return;
  95594. }
  95595. engine.enableEffect(this._effect);
  95596. // Logarithmic depth
  95597. if (material.useLogarithmicDepth) {
  95598. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95599. }
  95600. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95601. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95602. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95603. // Bones
  95604. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95605. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95606. }
  95607. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  95608. // Alpha test
  95609. if (material && material.needAlphaTesting()) {
  95610. var alphaTexture = material.getAlphaTestTexture();
  95611. if (alphaTexture) {
  95612. this._effect.setTexture("diffuseSampler", alphaTexture);
  95613. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  95614. }
  95615. }
  95616. engine.setZOffset(-this.zOffset);
  95617. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  95618. engine.setZOffset(0);
  95619. };
  95620. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  95621. var defines = [];
  95622. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  95623. var mesh = subMesh.getMesh();
  95624. var material = subMesh.getMaterial();
  95625. if (material) {
  95626. // Alpha test
  95627. if (material.needAlphaTesting()) {
  95628. defines.push("#define ALPHATEST");
  95629. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95630. attribs.push(BABYLON.VertexBuffer.UVKind);
  95631. defines.push("#define UV1");
  95632. }
  95633. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  95634. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95635. defines.push("#define UV2");
  95636. }
  95637. }
  95638. //Logarithmic depth
  95639. if (material.useLogarithmicDepth) {
  95640. defines.push("#define LOGARITHMICDEPTH");
  95641. }
  95642. }
  95643. // Bones
  95644. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95645. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95646. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95647. if (mesh.numBoneInfluencers > 4) {
  95648. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95649. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95650. }
  95651. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95652. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  95653. }
  95654. else {
  95655. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95656. }
  95657. // Instances
  95658. if (useInstances) {
  95659. defines.push("#define INSTANCES");
  95660. attribs.push("world0");
  95661. attribs.push("world1");
  95662. attribs.push("world2");
  95663. attribs.push("world3");
  95664. }
  95665. // Get correct effect
  95666. var join = defines.join("\n");
  95667. if (this._cachedDefines !== join) {
  95668. this._cachedDefines = join;
  95669. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  95670. }
  95671. return this._effect.isReady();
  95672. };
  95673. return OutlineRenderer;
  95674. }());
  95675. BABYLON.OutlineRenderer = OutlineRenderer;
  95676. })(BABYLON || (BABYLON = {}));
  95677. //# sourceMappingURL=babylon.outlineRenderer.js.map
  95678. var BABYLON;
  95679. (function (BABYLON) {
  95680. var FaceAdjacencies = /** @class */ (function () {
  95681. function FaceAdjacencies() {
  95682. this.edges = new Array();
  95683. this.edgesConnectedCount = 0;
  95684. }
  95685. return FaceAdjacencies;
  95686. }());
  95687. var EdgesRenderer = /** @class */ (function () {
  95688. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  95689. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  95690. if (epsilon === void 0) { epsilon = 0.95; }
  95691. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  95692. this.edgesWidthScalerForOrthographic = 1000.0;
  95693. this.edgesWidthScalerForPerspective = 50.0;
  95694. this._linesPositions = new Array();
  95695. this._linesNormals = new Array();
  95696. this._linesIndices = new Array();
  95697. this._buffers = {};
  95698. this._checkVerticesInsteadOfIndices = false;
  95699. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  95700. this.isEnabled = true;
  95701. this._source = source;
  95702. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  95703. this._epsilon = epsilon;
  95704. this._prepareRessources();
  95705. this._generateEdgesLines();
  95706. }
  95707. EdgesRenderer.prototype._prepareRessources = function () {
  95708. if (this._lineShader) {
  95709. return;
  95710. }
  95711. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  95712. attributes: ["position", "normal"],
  95713. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  95714. });
  95715. this._lineShader.disableDepthWrite = true;
  95716. this._lineShader.backFaceCulling = false;
  95717. };
  95718. EdgesRenderer.prototype._rebuild = function () {
  95719. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95720. if (buffer) {
  95721. buffer._rebuild();
  95722. }
  95723. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95724. if (buffer) {
  95725. buffer._rebuild();
  95726. }
  95727. var scene = this._source.getScene();
  95728. var engine = scene.getEngine();
  95729. this._ib = engine.createIndexBuffer(this._linesIndices);
  95730. };
  95731. EdgesRenderer.prototype.dispose = function () {
  95732. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95733. if (buffer) {
  95734. buffer.dispose();
  95735. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  95736. }
  95737. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95738. if (buffer) {
  95739. buffer.dispose();
  95740. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  95741. }
  95742. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  95743. this._lineShader.dispose();
  95744. };
  95745. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  95746. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  95747. return 0;
  95748. }
  95749. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  95750. return 1;
  95751. }
  95752. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  95753. return 2;
  95754. }
  95755. return -1;
  95756. };
  95757. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  95758. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  95759. return 0;
  95760. }
  95761. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  95762. return 1;
  95763. }
  95764. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  95765. return 2;
  95766. }
  95767. return -1;
  95768. };
  95769. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  95770. var needToCreateLine;
  95771. if (edge === undefined) {
  95772. needToCreateLine = true;
  95773. }
  95774. else {
  95775. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  95776. needToCreateLine = dotProduct < this._epsilon;
  95777. }
  95778. if (needToCreateLine) {
  95779. var offset = this._linesPositions.length / 3;
  95780. var normal = p0.subtract(p1);
  95781. normal.normalize();
  95782. // Positions
  95783. this._linesPositions.push(p0.x);
  95784. this._linesPositions.push(p0.y);
  95785. this._linesPositions.push(p0.z);
  95786. this._linesPositions.push(p0.x);
  95787. this._linesPositions.push(p0.y);
  95788. this._linesPositions.push(p0.z);
  95789. this._linesPositions.push(p1.x);
  95790. this._linesPositions.push(p1.y);
  95791. this._linesPositions.push(p1.z);
  95792. this._linesPositions.push(p1.x);
  95793. this._linesPositions.push(p1.y);
  95794. this._linesPositions.push(p1.z);
  95795. // Normals
  95796. this._linesNormals.push(p1.x);
  95797. this._linesNormals.push(p1.y);
  95798. this._linesNormals.push(p1.z);
  95799. this._linesNormals.push(-1);
  95800. this._linesNormals.push(p1.x);
  95801. this._linesNormals.push(p1.y);
  95802. this._linesNormals.push(p1.z);
  95803. this._linesNormals.push(1);
  95804. this._linesNormals.push(p0.x);
  95805. this._linesNormals.push(p0.y);
  95806. this._linesNormals.push(p0.z);
  95807. this._linesNormals.push(-1);
  95808. this._linesNormals.push(p0.x);
  95809. this._linesNormals.push(p0.y);
  95810. this._linesNormals.push(p0.z);
  95811. this._linesNormals.push(1);
  95812. // Indices
  95813. this._linesIndices.push(offset);
  95814. this._linesIndices.push(offset + 1);
  95815. this._linesIndices.push(offset + 2);
  95816. this._linesIndices.push(offset);
  95817. this._linesIndices.push(offset + 2);
  95818. this._linesIndices.push(offset + 3);
  95819. }
  95820. };
  95821. EdgesRenderer.prototype._generateEdgesLines = function () {
  95822. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95823. var indices = this._source.getIndices();
  95824. if (!indices || !positions) {
  95825. return;
  95826. }
  95827. // First let's find adjacencies
  95828. var adjacencies = new Array();
  95829. var faceNormals = new Array();
  95830. var index;
  95831. var faceAdjacencies;
  95832. // Prepare faces
  95833. for (index = 0; index < indices.length; index += 3) {
  95834. faceAdjacencies = new FaceAdjacencies();
  95835. var p0Index = indices[index];
  95836. var p1Index = indices[index + 1];
  95837. var p2Index = indices[index + 2];
  95838. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  95839. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  95840. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  95841. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  95842. faceNormal.normalize();
  95843. faceNormals.push(faceNormal);
  95844. adjacencies.push(faceAdjacencies);
  95845. }
  95846. // Scan
  95847. for (index = 0; index < adjacencies.length; index++) {
  95848. faceAdjacencies = adjacencies[index];
  95849. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  95850. var otherFaceAdjacencies = adjacencies[otherIndex];
  95851. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  95852. break;
  95853. }
  95854. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  95855. continue;
  95856. }
  95857. var otherP0 = indices[otherIndex * 3];
  95858. var otherP1 = indices[otherIndex * 3 + 1];
  95859. var otherP2 = indices[otherIndex * 3 + 2];
  95860. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  95861. var otherEdgeIndex = 0;
  95862. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  95863. continue;
  95864. }
  95865. switch (edgeIndex) {
  95866. case 0:
  95867. if (this._checkVerticesInsteadOfIndices) {
  95868. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95869. }
  95870. else {
  95871. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  95872. }
  95873. break;
  95874. case 1:
  95875. if (this._checkVerticesInsteadOfIndices) {
  95876. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95877. }
  95878. else {
  95879. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  95880. }
  95881. break;
  95882. case 2:
  95883. if (this._checkVerticesInsteadOfIndices) {
  95884. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95885. }
  95886. else {
  95887. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  95888. }
  95889. break;
  95890. }
  95891. if (otherEdgeIndex === -1) {
  95892. continue;
  95893. }
  95894. faceAdjacencies.edges[edgeIndex] = otherIndex;
  95895. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  95896. faceAdjacencies.edgesConnectedCount++;
  95897. otherFaceAdjacencies.edgesConnectedCount++;
  95898. if (faceAdjacencies.edgesConnectedCount === 3) {
  95899. break;
  95900. }
  95901. }
  95902. }
  95903. }
  95904. // Create lines
  95905. for (index = 0; index < adjacencies.length; index++) {
  95906. // 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
  95907. var current = adjacencies[index];
  95908. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  95909. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  95910. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  95911. }
  95912. // Merge into a single mesh
  95913. var engine = this._source.getScene().getEngine();
  95914. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  95915. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  95916. this._ib = engine.createIndexBuffer(this._linesIndices);
  95917. this._indicesCount = this._linesIndices.length;
  95918. };
  95919. EdgesRenderer.prototype.render = function () {
  95920. var scene = this._source.getScene();
  95921. if (!this._lineShader.isReady() || !scene.activeCamera) {
  95922. return;
  95923. }
  95924. var engine = scene.getEngine();
  95925. this._lineShader._preBind();
  95926. // VBOs
  95927. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  95928. scene.resetCachedMaterial();
  95929. this._lineShader.setColor4("color", this._source.edgesColor);
  95930. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  95931. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  95932. }
  95933. else {
  95934. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  95935. }
  95936. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  95937. this._lineShader.bind(this._source.getWorldMatrix());
  95938. // Draw order
  95939. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  95940. this._lineShader.unbind();
  95941. engine.setDepthWrite(true);
  95942. };
  95943. return EdgesRenderer;
  95944. }());
  95945. BABYLON.EdgesRenderer = EdgesRenderer;
  95946. })(BABYLON || (BABYLON = {}));
  95947. //# sourceMappingURL=babylon.edgesRenderer.js.map
  95948. var BABYLON;
  95949. (function (BABYLON) {
  95950. // Adds the parser to the scene parsers.
  95951. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  95952. if (parsedData.effectLayers) {
  95953. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  95954. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  95955. container.effectLayers.push(effectLayer);
  95956. }
  95957. }
  95958. });
  95959. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  95960. var index = this.effectLayers.indexOf(toRemove);
  95961. if (index !== -1) {
  95962. this.effectLayers.splice(index, 1);
  95963. }
  95964. return index;
  95965. };
  95966. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  95967. this.effectLayers.push(newEffectLayer);
  95968. };
  95969. /**
  95970. * Defines the layer scene component responsible to manage any effect layers
  95971. * in a given scene.
  95972. */
  95973. var EffectLayerSceneComponent = /** @class */ (function () {
  95974. /**
  95975. * Creates a new instance of the component for the given scene
  95976. * @param scene Defines the scene to register the component in
  95977. */
  95978. function EffectLayerSceneComponent(scene) {
  95979. /**
  95980. * The component name helpfull to identify the component in the list of scene components.
  95981. */
  95982. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  95983. this._renderEffects = false;
  95984. this._needStencil = false;
  95985. this._previousStencilState = false;
  95986. this.scene = scene;
  95987. this._engine = scene.getEngine();
  95988. this._effectLayers = scene.effectLayers = new Array();
  95989. }
  95990. /**
  95991. * Registers the component in a given scene
  95992. */
  95993. EffectLayerSceneComponent.prototype.register = function () {
  95994. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  95995. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  95996. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  95997. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  95998. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._draw);
  95999. };
  96000. /**
  96001. * Rebuilds the elements related to this component in case of
  96002. * context lost for instance.
  96003. */
  96004. EffectLayerSceneComponent.prototype.rebuild = function () {
  96005. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  96006. var effectLayer = _a[_i];
  96007. effectLayer._rebuild();
  96008. }
  96009. };
  96010. /**
  96011. * Serializes the component data to the specified json object
  96012. * @param serializationObject The object to serialize to
  96013. */
  96014. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  96015. // Effect layers
  96016. serializationObject.effectLayers = [];
  96017. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  96018. var effectLayer = _a[_i];
  96019. if (effectLayer.serialize) {
  96020. serializationObject.effectLayers.push(effectLayer.serialize());
  96021. }
  96022. }
  96023. };
  96024. /**
  96025. * Adds all the element from the container to the scene
  96026. * @param container the container holding the elements
  96027. */
  96028. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  96029. var _this = this;
  96030. if (!container.effectLayers) {
  96031. return;
  96032. }
  96033. container.effectLayers.forEach(function (o) {
  96034. _this.scene.addEffectLayer(o);
  96035. });
  96036. };
  96037. /**
  96038. * Removes all the elements in the container from the scene
  96039. * @param container contains the elements to remove
  96040. */
  96041. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  96042. var _this = this;
  96043. if (!container.effectLayers) {
  96044. return;
  96045. }
  96046. container.effectLayers.forEach(function (o) {
  96047. _this.scene.removeEffectLayer(o);
  96048. });
  96049. };
  96050. /**
  96051. * Disposes the component and the associated ressources.
  96052. */
  96053. EffectLayerSceneComponent.prototype.dispose = function () {
  96054. while (this._effectLayers.length) {
  96055. this._effectLayers[0].dispose();
  96056. }
  96057. };
  96058. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  96059. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  96060. var layer = _a[_i];
  96061. if (!layer.hasMesh(mesh)) {
  96062. continue;
  96063. }
  96064. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  96065. var subMesh = _c[_b];
  96066. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  96067. return false;
  96068. }
  96069. }
  96070. }
  96071. return true;
  96072. };
  96073. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  96074. this._renderEffects = false;
  96075. this._needStencil = false;
  96076. if (this._effectLayers && this._effectLayers.length > 0) {
  96077. this._previousStencilState = this._engine.getStencilBuffer();
  96078. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  96079. var effectLayer = _a[_i];
  96080. if (effectLayer.shouldRender() &&
  96081. (!effectLayer.camera ||
  96082. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  96083. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  96084. this._renderEffects = true;
  96085. this._needStencil = this._needStencil || effectLayer.needStencil();
  96086. var renderTarget = effectLayer._mainTexture;
  96087. if (renderTarget._shouldRender()) {
  96088. this.scene.incrementRenderId();
  96089. renderTarget.render(false, false);
  96090. }
  96091. }
  96092. }
  96093. this.scene.incrementRenderId();
  96094. }
  96095. };
  96096. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  96097. // Activate effect Layer stencil
  96098. if (this._needStencil) {
  96099. this._engine.setStencilBuffer(true);
  96100. }
  96101. };
  96102. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  96103. // Restore effect Layer stencil
  96104. if (this._needStencil) {
  96105. this._engine.setStencilBuffer(this._previousStencilState);
  96106. }
  96107. };
  96108. EffectLayerSceneComponent.prototype._draw = function (camera) {
  96109. if (this._renderEffects) {
  96110. this._engine.setDepthBuffer(false);
  96111. for (var i = 0; i < this._effectLayers.length; i++) {
  96112. if (this._effectLayers[i].shouldRender()) {
  96113. this._effectLayers[i].render();
  96114. }
  96115. }
  96116. this._engine.setDepthBuffer(true);
  96117. }
  96118. };
  96119. return EffectLayerSceneComponent;
  96120. }());
  96121. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  96122. })(BABYLON || (BABYLON = {}));
  96123. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  96124. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96125. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96126. s = arguments[i];
  96127. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96128. t[p] = s[p];
  96129. }
  96130. return t;
  96131. };
  96132. var BABYLON;
  96133. (function (BABYLON) {
  96134. /**
  96135. * The effect layer Helps adding post process effect blended with the main pass.
  96136. *
  96137. * This can be for instance use to generate glow or higlight effects on the scene.
  96138. *
  96139. * The effect layer class can not be used directly and is intented to inherited from to be
  96140. * customized per effects.
  96141. */
  96142. var EffectLayer = /** @class */ (function () {
  96143. /**
  96144. * Instantiates a new effect Layer and references it in the scene.
  96145. * @param name The name of the layer
  96146. * @param scene The scene to use the layer in
  96147. */
  96148. function EffectLayer(
  96149. /** The Friendly of the effect in the scene */
  96150. name, scene) {
  96151. this._vertexBuffers = {};
  96152. this._maxSize = 0;
  96153. this._mainTextureDesiredSize = { width: 0, height: 0 };
  96154. this._shouldRender = true;
  96155. this._postProcesses = [];
  96156. this._textures = [];
  96157. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  96158. /**
  96159. * The clear color of the texture used to generate the glow map.
  96160. */
  96161. this.neutralColor = new BABYLON.Color4();
  96162. /**
  96163. * Specifies wether the highlight layer is enabled or not.
  96164. */
  96165. this.isEnabled = true;
  96166. /**
  96167. * An event triggered when the effect layer has been disposed.
  96168. */
  96169. this.onDisposeObservable = new BABYLON.Observable();
  96170. /**
  96171. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  96172. */
  96173. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  96174. /**
  96175. * An event triggered when the generated texture is being merged in the scene.
  96176. */
  96177. this.onBeforeComposeObservable = new BABYLON.Observable();
  96178. /**
  96179. * An event triggered when the generated texture has been merged in the scene.
  96180. */
  96181. this.onAfterComposeObservable = new BABYLON.Observable();
  96182. /**
  96183. * An event triggered when the efffect layer changes its size.
  96184. */
  96185. this.onSizeChangedObservable = new BABYLON.Observable();
  96186. this.name = name;
  96187. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96188. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  96189. if (!component) {
  96190. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  96191. this._scene._addComponent(component);
  96192. }
  96193. this._engine = this._scene.getEngine();
  96194. this._maxSize = this._engine.getCaps().maxTextureSize;
  96195. this._scene.effectLayers.push(this);
  96196. // Generate Buffers
  96197. this._generateIndexBuffer();
  96198. this._genrateVertexBuffer();
  96199. }
  96200. Object.defineProperty(EffectLayer.prototype, "camera", {
  96201. /**
  96202. * Gets the camera attached to the layer.
  96203. */
  96204. get: function () {
  96205. return this._effectLayerOptions.camera;
  96206. },
  96207. enumerable: true,
  96208. configurable: true
  96209. });
  96210. /**
  96211. * Initializes the effect layer with the required options.
  96212. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  96213. */
  96214. EffectLayer.prototype._init = function (options) {
  96215. // Adapt options
  96216. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  96217. this._setMainTextureSize();
  96218. this._createMainTexture();
  96219. this._createTextureAndPostProcesses();
  96220. this._mergeEffect = this._createMergeEffect();
  96221. };
  96222. /**
  96223. * Generates the index buffer of the full screen quad blending to the main canvas.
  96224. */
  96225. EffectLayer.prototype._generateIndexBuffer = function () {
  96226. // Indices
  96227. var indices = [];
  96228. indices.push(0);
  96229. indices.push(1);
  96230. indices.push(2);
  96231. indices.push(0);
  96232. indices.push(2);
  96233. indices.push(3);
  96234. this._indexBuffer = this._engine.createIndexBuffer(indices);
  96235. };
  96236. /**
  96237. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  96238. */
  96239. EffectLayer.prototype._genrateVertexBuffer = function () {
  96240. // VBO
  96241. var vertices = [];
  96242. vertices.push(1, 1);
  96243. vertices.push(-1, 1);
  96244. vertices.push(-1, -1);
  96245. vertices.push(1, -1);
  96246. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96247. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96248. };
  96249. /**
  96250. * Sets the main texture desired size which is the closest power of two
  96251. * of the engine canvas size.
  96252. */
  96253. EffectLayer.prototype._setMainTextureSize = function () {
  96254. if (this._effectLayerOptions.mainTextureFixedSize) {
  96255. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  96256. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  96257. }
  96258. else {
  96259. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  96260. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  96261. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  96262. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  96263. }
  96264. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  96265. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  96266. };
  96267. /**
  96268. * Creates the main texture for the effect layer.
  96269. */
  96270. EffectLayer.prototype._createMainTexture = function () {
  96271. var _this = this;
  96272. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  96273. width: this._mainTextureDesiredSize.width,
  96274. height: this._mainTextureDesiredSize.height
  96275. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96276. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  96277. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96278. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96279. this._mainTexture.anisotropicFilteringLevel = 1;
  96280. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96281. this._mainTexture.renderParticles = false;
  96282. this._mainTexture.renderList = null;
  96283. this._mainTexture.ignoreCameraViewport = true;
  96284. // Custom render function
  96285. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  96286. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  96287. var index;
  96288. var engine = _this._scene.getEngine();
  96289. if (depthOnlySubMeshes.length) {
  96290. engine.setColorWrite(false);
  96291. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  96292. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  96293. }
  96294. engine.setColorWrite(true);
  96295. }
  96296. for (index = 0; index < opaqueSubMeshes.length; index++) {
  96297. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  96298. }
  96299. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  96300. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  96301. }
  96302. for (index = 0; index < transparentSubMeshes.length; index++) {
  96303. _this._renderSubMesh(transparentSubMeshes.data[index]);
  96304. }
  96305. };
  96306. this._mainTexture.onClearObservable.add(function (engine) {
  96307. engine.clear(_this.neutralColor, true, true, true);
  96308. });
  96309. };
  96310. /**
  96311. * Checks for the readiness of the element composing the layer.
  96312. * @param subMesh the mesh to check for
  96313. * @param useInstances specify wether or not to use instances to render the mesh
  96314. * @param emissiveTexture the associated emissive texture used to generate the glow
  96315. * @return true if ready otherwise, false
  96316. */
  96317. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  96318. var material = subMesh.getMaterial();
  96319. if (!material) {
  96320. return false;
  96321. }
  96322. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  96323. return false;
  96324. }
  96325. var defines = [];
  96326. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96327. var mesh = subMesh.getMesh();
  96328. var uv1 = false;
  96329. var uv2 = false;
  96330. // Alpha test
  96331. if (material && material.needAlphaTesting()) {
  96332. var alphaTexture = material.getAlphaTestTexture();
  96333. if (alphaTexture) {
  96334. defines.push("#define ALPHATEST");
  96335. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96336. alphaTexture.coordinatesIndex === 1) {
  96337. defines.push("#define DIFFUSEUV2");
  96338. uv2 = true;
  96339. }
  96340. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96341. defines.push("#define DIFFUSEUV1");
  96342. uv1 = true;
  96343. }
  96344. }
  96345. }
  96346. // Emissive
  96347. if (emissiveTexture) {
  96348. defines.push("#define EMISSIVE");
  96349. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96350. emissiveTexture.coordinatesIndex === 1) {
  96351. defines.push("#define EMISSIVEUV2");
  96352. uv2 = true;
  96353. }
  96354. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96355. defines.push("#define EMISSIVEUV1");
  96356. uv1 = true;
  96357. }
  96358. }
  96359. if (uv1) {
  96360. attribs.push(BABYLON.VertexBuffer.UVKind);
  96361. defines.push("#define UV1");
  96362. }
  96363. if (uv2) {
  96364. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96365. defines.push("#define UV2");
  96366. }
  96367. // Bones
  96368. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96369. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96370. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96371. if (mesh.numBoneInfluencers > 4) {
  96372. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96373. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96374. }
  96375. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96376. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  96377. }
  96378. else {
  96379. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96380. }
  96381. // Morph targets
  96382. var manager = mesh.morphTargetManager;
  96383. var morphInfluencers = 0;
  96384. if (manager) {
  96385. if (manager.numInfluencers > 0) {
  96386. defines.push("#define MORPHTARGETS");
  96387. morphInfluencers = manager.numInfluencers;
  96388. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  96389. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  96390. }
  96391. }
  96392. // Instances
  96393. if (useInstances) {
  96394. defines.push("#define INSTANCES");
  96395. attribs.push("world0");
  96396. attribs.push("world1");
  96397. attribs.push("world2");
  96398. attribs.push("world3");
  96399. }
  96400. // Get correct effect
  96401. var join = defines.join("\n");
  96402. if (this._cachedDefines !== join) {
  96403. this._cachedDefines = join;
  96404. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  96405. }
  96406. return this._effectLayerMapGenerationEffect.isReady();
  96407. };
  96408. /**
  96409. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  96410. */
  96411. EffectLayer.prototype.render = function () {
  96412. var currentEffect = this._mergeEffect;
  96413. // Check
  96414. if (!currentEffect.isReady())
  96415. return;
  96416. for (var i = 0; i < this._postProcesses.length; i++) {
  96417. if (!this._postProcesses[i].isReady()) {
  96418. return;
  96419. }
  96420. }
  96421. var engine = this._scene.getEngine();
  96422. this.onBeforeComposeObservable.notifyObservers(this);
  96423. // Render
  96424. engine.enableEffect(currentEffect);
  96425. engine.setState(false);
  96426. // VBOs
  96427. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96428. // Cache
  96429. var previousAlphaMode = engine.getAlphaMode();
  96430. // Go Blend.
  96431. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  96432. // Blends the map on the main canvas.
  96433. this._internalRender(currentEffect);
  96434. // Restore Alpha
  96435. engine.setAlphaMode(previousAlphaMode);
  96436. this.onAfterComposeObservable.notifyObservers(this);
  96437. // Handle size changes.
  96438. var size = this._mainTexture.getSize();
  96439. this._setMainTextureSize();
  96440. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  96441. // Recreate RTT and post processes on size change.
  96442. this.onSizeChangedObservable.notifyObservers(this);
  96443. this._disposeTextureAndPostProcesses();
  96444. this._createMainTexture();
  96445. this._createTextureAndPostProcesses();
  96446. }
  96447. };
  96448. /**
  96449. * Determine if a given mesh will be used in the current effect.
  96450. * @param mesh mesh to test
  96451. * @returns true if the mesh will be used
  96452. */
  96453. EffectLayer.prototype.hasMesh = function (mesh) {
  96454. return true;
  96455. };
  96456. /**
  96457. * Returns true if the layer contains information to display, otherwise false.
  96458. * @returns true if the glow layer should be rendered
  96459. */
  96460. EffectLayer.prototype.shouldRender = function () {
  96461. return this.isEnabled && this._shouldRender;
  96462. };
  96463. /**
  96464. * Returns true if the mesh should render, otherwise false.
  96465. * @param mesh The mesh to render
  96466. * @returns true if it should render otherwise false
  96467. */
  96468. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  96469. return true;
  96470. };
  96471. /**
  96472. * Returns true if the mesh should render, otherwise false.
  96473. * @param mesh The mesh to render
  96474. * @returns true if it should render otherwise false
  96475. */
  96476. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  96477. return true;
  96478. };
  96479. /**
  96480. * Renders the submesh passed in parameter to the generation map.
  96481. */
  96482. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  96483. var _this = this;
  96484. if (!this.shouldRender()) {
  96485. return;
  96486. }
  96487. var material = subMesh.getMaterial();
  96488. var mesh = subMesh.getRenderingMesh();
  96489. var scene = this._scene;
  96490. var engine = scene.getEngine();
  96491. if (!material) {
  96492. return;
  96493. }
  96494. // Do not block in blend mode.
  96495. if (material.needAlphaBlendingForMesh(mesh)) {
  96496. return;
  96497. }
  96498. // Culling
  96499. engine.setState(material.backFaceCulling);
  96500. // Managing instances
  96501. var batch = mesh._getInstancesRenderList(subMesh._id);
  96502. if (batch.mustReturn) {
  96503. return;
  96504. }
  96505. // Early Exit per mesh
  96506. if (!this._shouldRenderMesh(mesh)) {
  96507. return;
  96508. }
  96509. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96510. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  96511. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  96512. engine.enableEffect(this._effectLayerMapGenerationEffect);
  96513. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  96514. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  96515. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  96516. // Alpha test
  96517. if (material && material.needAlphaTesting()) {
  96518. var alphaTexture = material.getAlphaTestTexture();
  96519. if (alphaTexture) {
  96520. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  96521. var textureMatrix = alphaTexture.getTextureMatrix();
  96522. if (textureMatrix) {
  96523. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  96524. }
  96525. }
  96526. }
  96527. // Glow emissive only
  96528. if (this._emissiveTextureAndColor.texture) {
  96529. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  96530. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  96531. }
  96532. // Bones
  96533. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96534. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96535. }
  96536. // Morph targets
  96537. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  96538. // Draw
  96539. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  96540. }
  96541. else {
  96542. // Need to reset refresh rate of the main map
  96543. this._mainTexture.resetRefreshCounter();
  96544. }
  96545. };
  96546. /**
  96547. * Rebuild the required buffers.
  96548. * @hidden Internal use only.
  96549. */
  96550. EffectLayer.prototype._rebuild = function () {
  96551. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96552. if (vb) {
  96553. vb._rebuild();
  96554. }
  96555. this._generateIndexBuffer();
  96556. };
  96557. /**
  96558. * Dispose only the render target textures and post process.
  96559. */
  96560. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  96561. this._mainTexture.dispose();
  96562. for (var i = 0; i < this._postProcesses.length; i++) {
  96563. if (this._postProcesses[i]) {
  96564. this._postProcesses[i].dispose();
  96565. }
  96566. }
  96567. this._postProcesses = [];
  96568. for (var i = 0; i < this._textures.length; i++) {
  96569. if (this._textures[i]) {
  96570. this._textures[i].dispose();
  96571. }
  96572. }
  96573. this._textures = [];
  96574. };
  96575. /**
  96576. * Dispose the highlight layer and free resources.
  96577. */
  96578. EffectLayer.prototype.dispose = function () {
  96579. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96580. if (vertexBuffer) {
  96581. vertexBuffer.dispose();
  96582. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96583. }
  96584. if (this._indexBuffer) {
  96585. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96586. this._indexBuffer = null;
  96587. }
  96588. // Clean textures and post processes
  96589. this._disposeTextureAndPostProcesses();
  96590. // Remove from scene
  96591. var index = this._scene.effectLayers.indexOf(this, 0);
  96592. if (index > -1) {
  96593. this._scene.effectLayers.splice(index, 1);
  96594. }
  96595. // Callback
  96596. this.onDisposeObservable.notifyObservers(this);
  96597. this.onDisposeObservable.clear();
  96598. this.onBeforeRenderMainTextureObservable.clear();
  96599. this.onBeforeComposeObservable.clear();
  96600. this.onAfterComposeObservable.clear();
  96601. this.onSizeChangedObservable.clear();
  96602. };
  96603. /**
  96604. * Gets the class name of the effect layer
  96605. * @returns the string with the class name of the effect layer
  96606. */
  96607. EffectLayer.prototype.getClassName = function () {
  96608. return "EffectLayer";
  96609. };
  96610. /**
  96611. * Creates an effect layer from parsed effect layer data
  96612. * @param parsedEffectLayer defines effect layer data
  96613. * @param scene defines the current scene
  96614. * @param rootUrl defines the root URL containing the effect layer information
  96615. * @returns a parsed effect Layer
  96616. */
  96617. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  96618. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  96619. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  96620. };
  96621. __decorate([
  96622. BABYLON.serialize()
  96623. ], EffectLayer.prototype, "name", void 0);
  96624. __decorate([
  96625. BABYLON.serializeAsColor4()
  96626. ], EffectLayer.prototype, "neutralColor", void 0);
  96627. __decorate([
  96628. BABYLON.serialize()
  96629. ], EffectLayer.prototype, "isEnabled", void 0);
  96630. __decorate([
  96631. BABYLON.serializeAsCameraReference()
  96632. ], EffectLayer.prototype, "camera", null);
  96633. return EffectLayer;
  96634. }());
  96635. BABYLON.EffectLayer = EffectLayer;
  96636. })(BABYLON || (BABYLON = {}));
  96637. //# sourceMappingURL=babylon.effectLayer.js.map
  96638. var BABYLON;
  96639. (function (BABYLON) {
  96640. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  96641. for (var index = 0; index < this.effectLayers.length; index++) {
  96642. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  96643. return this.effectLayers[index];
  96644. }
  96645. }
  96646. return null;
  96647. };
  96648. /**
  96649. * Special Glow Blur post process only blurring the alpha channel
  96650. * It enforces keeping the most luminous color in the color channel.
  96651. */
  96652. var GlowBlurPostProcess = /** @class */ (function (_super) {
  96653. __extends(GlowBlurPostProcess, _super);
  96654. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  96655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  96656. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  96657. _this.direction = direction;
  96658. _this.kernel = kernel;
  96659. _this.onApplyObservable.add(function (effect) {
  96660. effect.setFloat2("screenSize", _this.width, _this.height);
  96661. effect.setVector2("direction", _this.direction);
  96662. effect.setFloat("blurWidth", _this.kernel);
  96663. });
  96664. return _this;
  96665. }
  96666. return GlowBlurPostProcess;
  96667. }(BABYLON.PostProcess));
  96668. /**
  96669. * The highlight layer Helps adding a glow effect around a mesh.
  96670. *
  96671. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96672. * glowy meshes to your scene.
  96673. *
  96674. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  96675. */
  96676. var HighlightLayer = /** @class */ (function (_super) {
  96677. __extends(HighlightLayer, _super);
  96678. /**
  96679. * Instantiates a new highlight Layer and references it to the scene..
  96680. * @param name The name of the layer
  96681. * @param scene The scene to use the layer in
  96682. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  96683. */
  96684. function HighlightLayer(name, scene, options) {
  96685. var _this = _super.call(this, name, scene) || this;
  96686. _this.name = name;
  96687. /**
  96688. * Specifies whether or not the inner glow is ACTIVE in the layer.
  96689. */
  96690. _this.innerGlow = true;
  96691. /**
  96692. * Specifies whether or not the outer glow is ACTIVE in the layer.
  96693. */
  96694. _this.outerGlow = true;
  96695. /**
  96696. * An event triggered when the highlight layer is being blurred.
  96697. */
  96698. _this.onBeforeBlurObservable = new BABYLON.Observable();
  96699. /**
  96700. * An event triggered when the highlight layer has been blurred.
  96701. */
  96702. _this.onAfterBlurObservable = new BABYLON.Observable();
  96703. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  96704. _this._meshes = {};
  96705. _this._excludedMeshes = {};
  96706. _this.neutralColor = HighlightLayer.NeutralColor;
  96707. // Warn on stencil
  96708. if (!_this._engine.isStencilEnable) {
  96709. 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 }");
  96710. }
  96711. // Adapt options
  96712. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  96713. // Initialize the layer
  96714. _this._init({
  96715. alphaBlendingMode: _this._options.alphaBlendingMode,
  96716. camera: _this._options.camera,
  96717. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96718. mainTextureRatio: _this._options.mainTextureRatio
  96719. });
  96720. // Do not render as long as no meshes have been added
  96721. _this._shouldRender = false;
  96722. return _this;
  96723. }
  96724. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  96725. /**
  96726. * Gets the horizontal size of the blur.
  96727. */
  96728. get: function () {
  96729. return this._horizontalBlurPostprocess.kernel;
  96730. },
  96731. /**
  96732. * Specifies the horizontal size of the blur.
  96733. */
  96734. set: function (value) {
  96735. this._horizontalBlurPostprocess.kernel = value;
  96736. },
  96737. enumerable: true,
  96738. configurable: true
  96739. });
  96740. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  96741. /**
  96742. * Gets the vertical size of the blur.
  96743. */
  96744. get: function () {
  96745. return this._verticalBlurPostprocess.kernel;
  96746. },
  96747. /**
  96748. * Specifies the vertical size of the blur.
  96749. */
  96750. set: function (value) {
  96751. this._verticalBlurPostprocess.kernel = value;
  96752. },
  96753. enumerable: true,
  96754. configurable: true
  96755. });
  96756. /**
  96757. * Get the effect name of the layer.
  96758. * @return The effect name
  96759. */
  96760. HighlightLayer.prototype.getEffectName = function () {
  96761. return HighlightLayer.EffectName;
  96762. };
  96763. /**
  96764. * Create the merge effect. This is the shader use to blit the information back
  96765. * to the main canvas at the end of the scene rendering.
  96766. */
  96767. HighlightLayer.prototype._createMergeEffect = function () {
  96768. // Effect
  96769. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  96770. };
  96771. /**
  96772. * Creates the render target textures and post processes used in the highlight layer.
  96773. */
  96774. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  96775. var _this = this;
  96776. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  96777. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  96778. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96779. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96780. var textureType = 0;
  96781. if (this._engine.getCaps().textureHalfFloatRender) {
  96782. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96783. }
  96784. else {
  96785. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96786. }
  96787. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  96788. width: blurTextureWidth,
  96789. height: blurTextureHeight
  96790. }, this._scene, false, true, textureType);
  96791. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96792. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96793. this._blurTexture.anisotropicFilteringLevel = 16;
  96794. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  96795. this._blurTexture.renderParticles = false;
  96796. this._blurTexture.ignoreCameraViewport = true;
  96797. this._textures = [this._blurTexture];
  96798. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  96799. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96800. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  96801. effect.setTexture("textureSampler", _this._mainTexture);
  96802. });
  96803. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96804. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96805. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96806. });
  96807. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96808. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  96809. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96810. });
  96811. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96812. }
  96813. else {
  96814. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  96815. width: blurTextureWidth,
  96816. height: blurTextureHeight
  96817. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96818. this._horizontalBlurPostprocess.width = blurTextureWidth;
  96819. this._horizontalBlurPostprocess.height = blurTextureHeight;
  96820. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96821. effect.setTexture("textureSampler", _this._mainTexture);
  96822. });
  96823. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  96824. width: blurTextureWidth,
  96825. height: blurTextureHeight
  96826. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96827. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96828. }
  96829. this._mainTexture.onAfterUnbindObservable.add(function () {
  96830. _this.onBeforeBlurObservable.notifyObservers(_this);
  96831. var internalTexture = _this._blurTexture.getInternalTexture();
  96832. if (internalTexture) {
  96833. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  96834. }
  96835. _this.onAfterBlurObservable.notifyObservers(_this);
  96836. });
  96837. // Prevent autoClear.
  96838. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96839. };
  96840. /**
  96841. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96842. */
  96843. HighlightLayer.prototype.needStencil = function () {
  96844. return true;
  96845. };
  96846. /**
  96847. * Checks for the readiness of the element composing the layer.
  96848. * @param subMesh the mesh to check for
  96849. * @param useInstances specify wether or not to use instances to render the mesh
  96850. * @param emissiveTexture the associated emissive texture used to generate the glow
  96851. * @return true if ready otherwise, false
  96852. */
  96853. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  96854. var material = subMesh.getMaterial();
  96855. var mesh = subMesh.getRenderingMesh();
  96856. if (!material || !mesh || !this._meshes) {
  96857. return false;
  96858. }
  96859. var emissiveTexture = null;
  96860. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96861. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96862. emissiveTexture = material.emissiveTexture;
  96863. }
  96864. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96865. };
  96866. /**
  96867. * Implementation specific of rendering the generating effect on the main canvas.
  96868. * @param effect The effect used to render through
  96869. */
  96870. HighlightLayer.prototype._internalRender = function (effect) {
  96871. // Texture
  96872. effect.setTexture("textureSampler", this._blurTexture);
  96873. // Cache
  96874. var engine = this._engine;
  96875. var previousStencilBuffer = engine.getStencilBuffer();
  96876. var previousStencilFunction = engine.getStencilFunction();
  96877. var previousStencilMask = engine.getStencilMask();
  96878. var previousStencilOperationPass = engine.getStencilOperationPass();
  96879. var previousStencilOperationFail = engine.getStencilOperationFail();
  96880. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  96881. var previousStencilReference = engine.getStencilFunctionReference();
  96882. // Stencil operations
  96883. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  96884. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  96885. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  96886. // Draw order
  96887. engine.setStencilMask(0x00);
  96888. engine.setStencilBuffer(true);
  96889. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  96890. // 2 passes inner outer
  96891. if (this.outerGlow) {
  96892. effect.setFloat("offset", 0);
  96893. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  96894. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96895. }
  96896. if (this.innerGlow) {
  96897. effect.setFloat("offset", 1);
  96898. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  96899. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96900. }
  96901. // Restore Cache
  96902. engine.setStencilFunction(previousStencilFunction);
  96903. engine.setStencilMask(previousStencilMask);
  96904. engine.setStencilBuffer(previousStencilBuffer);
  96905. engine.setStencilOperationPass(previousStencilOperationPass);
  96906. engine.setStencilOperationFail(previousStencilOperationFail);
  96907. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  96908. engine.setStencilFunctionReference(previousStencilReference);
  96909. };
  96910. /**
  96911. * Returns true if the layer contains information to display, otherwise false.
  96912. */
  96913. HighlightLayer.prototype.shouldRender = function () {
  96914. if (_super.prototype.shouldRender.call(this)) {
  96915. return this._meshes ? true : false;
  96916. }
  96917. return false;
  96918. };
  96919. /**
  96920. * Returns true if the mesh should render, otherwise false.
  96921. * @param mesh The mesh to render
  96922. * @returns true if it should render otherwise false
  96923. */
  96924. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  96925. // Excluded Mesh
  96926. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  96927. return false;
  96928. }
  96929. ;
  96930. return true;
  96931. };
  96932. /**
  96933. * Sets the required values for both the emissive texture and and the main color.
  96934. */
  96935. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96936. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96937. if (highlightLayerMesh) {
  96938. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  96939. }
  96940. else {
  96941. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96942. }
  96943. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96944. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96945. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  96946. }
  96947. else {
  96948. this._emissiveTextureAndColor.texture = null;
  96949. }
  96950. };
  96951. /**
  96952. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  96953. * @param mesh The mesh to exclude from the highlight layer
  96954. */
  96955. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  96956. if (!this._excludedMeshes) {
  96957. return;
  96958. }
  96959. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96960. if (!meshExcluded) {
  96961. this._excludedMeshes[mesh.uniqueId] = {
  96962. mesh: mesh,
  96963. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  96964. mesh.getEngine().setStencilBuffer(false);
  96965. }),
  96966. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  96967. mesh.getEngine().setStencilBuffer(true);
  96968. }),
  96969. };
  96970. }
  96971. };
  96972. /**
  96973. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  96974. * @param mesh The mesh to highlight
  96975. */
  96976. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  96977. if (!this._excludedMeshes) {
  96978. return;
  96979. }
  96980. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96981. if (meshExcluded) {
  96982. if (meshExcluded.beforeRender) {
  96983. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  96984. }
  96985. if (meshExcluded.afterRender) {
  96986. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  96987. }
  96988. }
  96989. this._excludedMeshes[mesh.uniqueId] = null;
  96990. };
  96991. /**
  96992. * Determine if a given mesh will be highlighted by the current HighlightLayer
  96993. * @param mesh mesh to test
  96994. * @returns true if the mesh will be highlighted by the current HighlightLayer
  96995. */
  96996. HighlightLayer.prototype.hasMesh = function (mesh) {
  96997. if (!this._meshes) {
  96998. return false;
  96999. }
  97000. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  97001. };
  97002. /**
  97003. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  97004. * @param mesh The mesh to highlight
  97005. * @param color The color of the highlight
  97006. * @param glowEmissiveOnly Extract the glow from the emissive texture
  97007. */
  97008. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  97009. var _this = this;
  97010. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  97011. if (!this._meshes) {
  97012. return;
  97013. }
  97014. var meshHighlight = this._meshes[mesh.uniqueId];
  97015. if (meshHighlight) {
  97016. meshHighlight.color = color;
  97017. }
  97018. else {
  97019. this._meshes[mesh.uniqueId] = {
  97020. mesh: mesh,
  97021. color: color,
  97022. // Lambda required for capture due to Observable this context
  97023. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  97024. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  97025. _this._defaultStencilReference(mesh);
  97026. }
  97027. else {
  97028. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  97029. }
  97030. }),
  97031. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  97032. glowEmissiveOnly: glowEmissiveOnly
  97033. };
  97034. mesh.onDisposeObservable.add(function () {
  97035. _this._disposeMesh(mesh);
  97036. });
  97037. }
  97038. this._shouldRender = true;
  97039. };
  97040. /**
  97041. * Remove a mesh from the highlight layer in order to make it stop glowing.
  97042. * @param mesh The mesh to highlight
  97043. */
  97044. HighlightLayer.prototype.removeMesh = function (mesh) {
  97045. if (!this._meshes) {
  97046. return;
  97047. }
  97048. var meshHighlight = this._meshes[mesh.uniqueId];
  97049. if (meshHighlight) {
  97050. if (meshHighlight.observerHighlight) {
  97051. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97052. }
  97053. if (meshHighlight.observerDefault) {
  97054. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97055. }
  97056. delete this._meshes[mesh.uniqueId];
  97057. }
  97058. this._shouldRender = false;
  97059. for (var meshHighlightToCheck in this._meshes) {
  97060. if (this._meshes[meshHighlightToCheck]) {
  97061. this._shouldRender = true;
  97062. break;
  97063. }
  97064. }
  97065. };
  97066. /**
  97067. * Force the stencil to the normal expected value for none glowing parts
  97068. */
  97069. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  97070. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  97071. };
  97072. /**
  97073. * Free any resources and references associated to a mesh.
  97074. * Internal use
  97075. * @param mesh The mesh to free.
  97076. */
  97077. HighlightLayer.prototype._disposeMesh = function (mesh) {
  97078. this.removeMesh(mesh);
  97079. this.removeExcludedMesh(mesh);
  97080. };
  97081. /**
  97082. * Dispose the highlight layer and free resources.
  97083. */
  97084. HighlightLayer.prototype.dispose = function () {
  97085. if (this._meshes) {
  97086. // Clean mesh references
  97087. for (var id in this._meshes) {
  97088. var meshHighlight = this._meshes[id];
  97089. if (meshHighlight && meshHighlight.mesh) {
  97090. if (meshHighlight.observerHighlight) {
  97091. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97092. }
  97093. if (meshHighlight.observerDefault) {
  97094. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97095. }
  97096. }
  97097. }
  97098. this._meshes = null;
  97099. }
  97100. if (this._excludedMeshes) {
  97101. for (var id in this._excludedMeshes) {
  97102. var meshHighlight = this._excludedMeshes[id];
  97103. if (meshHighlight) {
  97104. if (meshHighlight.beforeRender) {
  97105. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  97106. }
  97107. if (meshHighlight.afterRender) {
  97108. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  97109. }
  97110. }
  97111. }
  97112. this._excludedMeshes = null;
  97113. }
  97114. _super.prototype.dispose.call(this);
  97115. };
  97116. /**
  97117. * Gets the class name of the effect layer
  97118. * @returns the string with the class name of the effect layer
  97119. */
  97120. HighlightLayer.prototype.getClassName = function () {
  97121. return "HighlightLayer";
  97122. };
  97123. /**
  97124. * Serializes this Highlight layer
  97125. * @returns a serialized Highlight layer object
  97126. */
  97127. HighlightLayer.prototype.serialize = function () {
  97128. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97129. serializationObject.customType = "BABYLON.HighlightLayer";
  97130. // Highlighted meshes
  97131. serializationObject.meshes = [];
  97132. if (this._meshes) {
  97133. for (var m in this._meshes) {
  97134. var mesh = this._meshes[m];
  97135. if (mesh) {
  97136. serializationObject.meshes.push({
  97137. glowEmissiveOnly: mesh.glowEmissiveOnly,
  97138. color: mesh.color.asArray(),
  97139. meshId: mesh.mesh.id
  97140. });
  97141. }
  97142. }
  97143. }
  97144. // Excluded meshes
  97145. serializationObject.excludedMeshes = [];
  97146. if (this._excludedMeshes) {
  97147. for (var e in this._excludedMeshes) {
  97148. var excludedMesh = this._excludedMeshes[e];
  97149. if (excludedMesh) {
  97150. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  97151. }
  97152. }
  97153. }
  97154. return serializationObject;
  97155. };
  97156. /**
  97157. * Creates a Highlight layer from parsed Highlight layer data
  97158. * @param parsedHightlightLayer defines the Highlight layer data
  97159. * @param scene defines the current scene
  97160. * @param rootUrl defines the root URL containing the Highlight layer information
  97161. * @returns a parsed Highlight layer
  97162. */
  97163. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  97164. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  97165. var index;
  97166. // Excluded meshes
  97167. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  97168. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  97169. if (mesh) {
  97170. hl.addExcludedMesh(mesh);
  97171. }
  97172. }
  97173. // Included meshes
  97174. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  97175. var highlightedMesh = parsedHightlightLayer.meshes[index];
  97176. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  97177. if (mesh) {
  97178. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  97179. }
  97180. }
  97181. return hl;
  97182. };
  97183. /**
  97184. * Effect Name of the highlight layer.
  97185. */
  97186. HighlightLayer.EffectName = "HighlightLayer";
  97187. /**
  97188. * The neutral color used during the preparation of the glow effect.
  97189. * This is black by default as the blend operation is a blend operation.
  97190. */
  97191. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  97192. /**
  97193. * Stencil value used for glowing meshes.
  97194. */
  97195. HighlightLayer.GlowingMeshStencilReference = 0x02;
  97196. /**
  97197. * Stencil value used for the other meshes in the scene.
  97198. */
  97199. HighlightLayer.NormalMeshStencilReference = 0x01;
  97200. __decorate([
  97201. BABYLON.serialize()
  97202. ], HighlightLayer.prototype, "innerGlow", void 0);
  97203. __decorate([
  97204. BABYLON.serialize()
  97205. ], HighlightLayer.prototype, "outerGlow", void 0);
  97206. __decorate([
  97207. BABYLON.serialize()
  97208. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  97209. __decorate([
  97210. BABYLON.serialize()
  97211. ], HighlightLayer.prototype, "blurVerticalSize", null);
  97212. __decorate([
  97213. BABYLON.serialize("options")
  97214. ], HighlightLayer.prototype, "_options", void 0);
  97215. return HighlightLayer;
  97216. }(BABYLON.EffectLayer));
  97217. BABYLON.HighlightLayer = HighlightLayer;
  97218. })(BABYLON || (BABYLON = {}));
  97219. //# sourceMappingURL=babylon.highlightLayer.js.map
  97220. var BABYLON;
  97221. (function (BABYLON) {
  97222. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  97223. for (var index = 0; index < this.effectLayers.length; index++) {
  97224. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  97225. return this.effectLayers[index];
  97226. }
  97227. }
  97228. return null;
  97229. };
  97230. /**
  97231. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  97232. *
  97233. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97234. * glowy meshes to your scene.
  97235. *
  97236. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  97237. */
  97238. var GlowLayer = /** @class */ (function (_super) {
  97239. __extends(GlowLayer, _super);
  97240. /**
  97241. * Instantiates a new glow Layer and references it to the scene.
  97242. * @param name The name of the layer
  97243. * @param scene The scene to use the layer in
  97244. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  97245. */
  97246. function GlowLayer(name, scene, options) {
  97247. var _this = _super.call(this, name, scene) || this;
  97248. _this._intensity = 1.0;
  97249. _this._includedOnlyMeshes = [];
  97250. _this._excludedMeshes = [];
  97251. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  97252. // Adapt options
  97253. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  97254. // Initialize the layer
  97255. _this._init({
  97256. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  97257. camera: _this._options.camera,
  97258. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97259. mainTextureRatio: _this._options.mainTextureRatio
  97260. });
  97261. return _this;
  97262. }
  97263. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  97264. /**
  97265. * Gets the kernel size of the blur.
  97266. */
  97267. get: function () {
  97268. return this._horizontalBlurPostprocess1.kernel;
  97269. },
  97270. /**
  97271. * Sets the kernel size of the blur.
  97272. */
  97273. set: function (value) {
  97274. this._horizontalBlurPostprocess1.kernel = value;
  97275. this._verticalBlurPostprocess1.kernel = value;
  97276. this._horizontalBlurPostprocess2.kernel = value;
  97277. this._verticalBlurPostprocess2.kernel = value;
  97278. },
  97279. enumerable: true,
  97280. configurable: true
  97281. });
  97282. Object.defineProperty(GlowLayer.prototype, "intensity", {
  97283. /**
  97284. * Gets the glow intensity.
  97285. */
  97286. get: function () {
  97287. return this._intensity;
  97288. },
  97289. /**
  97290. * Sets the glow intensity.
  97291. */
  97292. set: function (value) {
  97293. this._intensity = value;
  97294. },
  97295. enumerable: true,
  97296. configurable: true
  97297. });
  97298. /**
  97299. * Get the effect name of the layer.
  97300. * @return The effect name
  97301. */
  97302. GlowLayer.prototype.getEffectName = function () {
  97303. return GlowLayer.EffectName;
  97304. };
  97305. /**
  97306. * Create the merge effect. This is the shader use to blit the information back
  97307. * to the main canvas at the end of the scene rendering.
  97308. */
  97309. GlowLayer.prototype._createMergeEffect = function () {
  97310. // Effect
  97311. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  97312. };
  97313. /**
  97314. * Creates the render target textures and post processes used in the glow layer.
  97315. */
  97316. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  97317. var _this = this;
  97318. var blurTextureWidth = this._mainTextureDesiredSize.width;
  97319. var blurTextureHeight = this._mainTextureDesiredSize.height;
  97320. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97321. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97322. var textureType = 0;
  97323. if (this._engine.getCaps().textureHalfFloatRender) {
  97324. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97325. }
  97326. else {
  97327. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97328. }
  97329. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  97330. width: blurTextureWidth,
  97331. height: blurTextureHeight
  97332. }, this._scene, false, true, textureType);
  97333. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97334. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97335. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97336. this._blurTexture1.renderParticles = false;
  97337. this._blurTexture1.ignoreCameraViewport = true;
  97338. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  97339. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  97340. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  97341. width: blurTextureWidth2,
  97342. height: blurTextureHeight2
  97343. }, this._scene, false, true, textureType);
  97344. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97345. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97346. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97347. this._blurTexture2.renderParticles = false;
  97348. this._blurTexture2.ignoreCameraViewport = true;
  97349. this._textures = [this._blurTexture1, this._blurTexture2];
  97350. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97351. width: blurTextureWidth,
  97352. height: blurTextureHeight
  97353. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97354. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  97355. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  97356. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  97357. effect.setTexture("textureSampler", _this._mainTexture);
  97358. });
  97359. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97360. width: blurTextureWidth,
  97361. height: blurTextureHeight
  97362. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97363. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97364. width: blurTextureWidth2,
  97365. height: blurTextureHeight2
  97366. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97367. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  97368. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  97369. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  97370. effect.setTexture("textureSampler", _this._blurTexture1);
  97371. });
  97372. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97373. width: blurTextureWidth2,
  97374. height: blurTextureHeight2
  97375. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97376. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97377. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  97378. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97379. this._mainTexture.samples = this._options.mainTextureSamples;
  97380. this._mainTexture.onAfterUnbindObservable.add(function () {
  97381. var internalTexture = _this._blurTexture1.getInternalTexture();
  97382. if (internalTexture) {
  97383. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  97384. internalTexture = _this._blurTexture2.getInternalTexture();
  97385. if (internalTexture) {
  97386. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  97387. }
  97388. }
  97389. });
  97390. // Prevent autoClear.
  97391. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97392. };
  97393. /**
  97394. * Checks for the readiness of the element composing the layer.
  97395. * @param subMesh the mesh to check for
  97396. * @param useInstances specify wether or not to use instances to render the mesh
  97397. * @param emissiveTexture the associated emissive texture used to generate the glow
  97398. * @return true if ready otherwise, false
  97399. */
  97400. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  97401. var material = subMesh.getMaterial();
  97402. var mesh = subMesh.getRenderingMesh();
  97403. if (!material || !mesh) {
  97404. return false;
  97405. }
  97406. var emissiveTexture = material.emissiveTexture;
  97407. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97408. };
  97409. /**
  97410. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97411. */
  97412. GlowLayer.prototype.needStencil = function () {
  97413. return false;
  97414. };
  97415. /**
  97416. * Implementation specific of rendering the generating effect on the main canvas.
  97417. * @param effect The effect used to render through
  97418. */
  97419. GlowLayer.prototype._internalRender = function (effect) {
  97420. // Texture
  97421. effect.setTexture("textureSampler", this._blurTexture1);
  97422. effect.setTexture("textureSampler2", this._blurTexture2);
  97423. effect.setFloat("offset", this._intensity);
  97424. // Cache
  97425. var engine = this._engine;
  97426. var previousStencilBuffer = engine.getStencilBuffer();
  97427. // Draw order
  97428. engine.setStencilBuffer(false);
  97429. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97430. // Draw order
  97431. engine.setStencilBuffer(previousStencilBuffer);
  97432. };
  97433. /**
  97434. * Sets the required values for both the emissive texture and and the main color.
  97435. */
  97436. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97437. var textureLevel = 1.0;
  97438. if (this.customEmissiveTextureSelector) {
  97439. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  97440. }
  97441. else {
  97442. if (material) {
  97443. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97444. if (this._emissiveTextureAndColor.texture) {
  97445. textureLevel = this._emissiveTextureAndColor.texture.level;
  97446. }
  97447. }
  97448. else {
  97449. this._emissiveTextureAndColor.texture = null;
  97450. }
  97451. }
  97452. if (this.customEmissiveColorSelector) {
  97453. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  97454. }
  97455. else {
  97456. if (material.emissiveColor) {
  97457. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  97458. }
  97459. else {
  97460. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97461. }
  97462. }
  97463. };
  97464. /**
  97465. * Returns true if the mesh should render, otherwise false.
  97466. * @param mesh The mesh to render
  97467. * @returns true if it should render otherwise false
  97468. */
  97469. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  97470. return this.hasMesh(mesh);
  97471. };
  97472. /**
  97473. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  97474. * @param mesh The mesh to exclude from the glow layer
  97475. */
  97476. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  97477. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  97478. this._excludedMeshes.push(mesh.uniqueId);
  97479. }
  97480. };
  97481. /**
  97482. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  97483. * @param mesh The mesh to remove
  97484. */
  97485. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  97486. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  97487. if (index !== -1) {
  97488. this._excludedMeshes.splice(index, 1);
  97489. }
  97490. };
  97491. /**
  97492. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  97493. * @param mesh The mesh to include in the glow layer
  97494. */
  97495. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  97496. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  97497. this._includedOnlyMeshes.push(mesh.uniqueId);
  97498. }
  97499. };
  97500. /**
  97501. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  97502. * @param mesh The mesh to remove
  97503. */
  97504. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  97505. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  97506. if (index !== -1) {
  97507. this._includedOnlyMeshes.splice(index, 1);
  97508. }
  97509. };
  97510. /**
  97511. * Determine if a given mesh will be used in the glow layer
  97512. * @param mesh The mesh to test
  97513. * @returns true if the mesh will be highlighted by the current glow layer
  97514. */
  97515. GlowLayer.prototype.hasMesh = function (mesh) {
  97516. // Included Mesh
  97517. if (this._includedOnlyMeshes.length) {
  97518. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  97519. }
  97520. ;
  97521. // Excluded Mesh
  97522. if (this._excludedMeshes.length) {
  97523. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  97524. }
  97525. ;
  97526. return true;
  97527. };
  97528. /**
  97529. * Free any resources and references associated to a mesh.
  97530. * Internal use
  97531. * @param mesh The mesh to free.
  97532. */
  97533. GlowLayer.prototype._disposeMesh = function (mesh) {
  97534. this.removeIncludedOnlyMesh(mesh);
  97535. this.removeExcludedMesh(mesh);
  97536. };
  97537. /**
  97538. * Gets the class name of the effect layer
  97539. * @returns the string with the class name of the effect layer
  97540. */
  97541. GlowLayer.prototype.getClassName = function () {
  97542. return "GlowLayer";
  97543. };
  97544. /**
  97545. * Serializes this glow layer
  97546. * @returns a serialized glow layer object
  97547. */
  97548. GlowLayer.prototype.serialize = function () {
  97549. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97550. serializationObject.customType = "BABYLON.GlowLayer";
  97551. var index;
  97552. // Included meshes
  97553. serializationObject.includedMeshes = [];
  97554. if (this._includedOnlyMeshes.length) {
  97555. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  97556. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  97557. if (mesh) {
  97558. serializationObject.includedMeshes.push(mesh.id);
  97559. }
  97560. }
  97561. }
  97562. // Excluded meshes
  97563. serializationObject.excludedMeshes = [];
  97564. if (this._excludedMeshes.length) {
  97565. for (index = 0; index < this._excludedMeshes.length; index++) {
  97566. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  97567. if (mesh) {
  97568. serializationObject.excludedMeshes.push(mesh.id);
  97569. }
  97570. }
  97571. }
  97572. return serializationObject;
  97573. };
  97574. /**
  97575. * Creates a Glow Layer from parsed glow layer data
  97576. * @param parsedGlowLayer defines glow layer data
  97577. * @param scene defines the current scene
  97578. * @param rootUrl defines the root URL containing the glow layer information
  97579. * @returns a parsed Glow Layer
  97580. */
  97581. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  97582. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  97583. var index;
  97584. // Excluded meshes
  97585. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  97586. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  97587. if (mesh) {
  97588. gl.addExcludedMesh(mesh);
  97589. }
  97590. }
  97591. // Included meshes
  97592. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  97593. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  97594. if (mesh) {
  97595. gl.addIncludedOnlyMesh(mesh);
  97596. }
  97597. }
  97598. return gl;
  97599. };
  97600. /**
  97601. * Effect Name of the layer.
  97602. */
  97603. GlowLayer.EffectName = "GlowLayer";
  97604. /**
  97605. * The default blur kernel size used for the glow.
  97606. */
  97607. GlowLayer.DefaultBlurKernelSize = 32;
  97608. /**
  97609. * The default texture size ratio used for the glow.
  97610. */
  97611. GlowLayer.DefaultTextureRatio = 0.5;
  97612. __decorate([
  97613. BABYLON.serialize()
  97614. ], GlowLayer.prototype, "blurKernelSize", null);
  97615. __decorate([
  97616. BABYLON.serialize()
  97617. ], GlowLayer.prototype, "intensity", null);
  97618. __decorate([
  97619. BABYLON.serialize("options")
  97620. ], GlowLayer.prototype, "_options", void 0);
  97621. return GlowLayer;
  97622. }(BABYLON.EffectLayer));
  97623. BABYLON.GlowLayer = GlowLayer;
  97624. })(BABYLON || (BABYLON = {}));
  97625. //# sourceMappingURL=babylon.glowLayer.js.map
  97626. var BABYLON;
  97627. (function (BABYLON) {
  97628. /**
  97629. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  97630. */
  97631. var AssetTaskState;
  97632. (function (AssetTaskState) {
  97633. /**
  97634. * Initialization
  97635. */
  97636. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  97637. /**
  97638. * Running
  97639. */
  97640. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  97641. /**
  97642. * Done
  97643. */
  97644. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  97645. /**
  97646. * Error
  97647. */
  97648. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  97649. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  97650. /**
  97651. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  97652. */
  97653. var AbstractAssetTask = /** @class */ (function () {
  97654. /**
  97655. * Creates a new {BABYLON.AssetsManager}
  97656. * @param name defines the name of the task
  97657. */
  97658. function AbstractAssetTask(
  97659. /**
  97660. * Task name
  97661. */ name) {
  97662. this.name = name;
  97663. this._isCompleted = false;
  97664. this._taskState = AssetTaskState.INIT;
  97665. }
  97666. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  97667. /**
  97668. * Get if the task is completed
  97669. */
  97670. get: function () {
  97671. return this._isCompleted;
  97672. },
  97673. enumerable: true,
  97674. configurable: true
  97675. });
  97676. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  97677. /**
  97678. * Gets the current state of the task
  97679. */
  97680. get: function () {
  97681. return this._taskState;
  97682. },
  97683. enumerable: true,
  97684. configurable: true
  97685. });
  97686. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  97687. /**
  97688. * Gets the current error object (if task is in error)
  97689. */
  97690. get: function () {
  97691. return this._errorObject;
  97692. },
  97693. enumerable: true,
  97694. configurable: true
  97695. });
  97696. /**
  97697. * Internal only
  97698. * @hidden
  97699. */
  97700. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  97701. if (this._errorObject) {
  97702. return;
  97703. }
  97704. this._errorObject = {
  97705. message: message,
  97706. exception: exception
  97707. };
  97708. };
  97709. /**
  97710. * Execute the current task
  97711. * @param scene defines the scene where you want your assets to be loaded
  97712. * @param onSuccess is a callback called when the task is successfully executed
  97713. * @param onError is a callback called if an error occurs
  97714. */
  97715. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97716. var _this = this;
  97717. this._taskState = AssetTaskState.RUNNING;
  97718. this.runTask(scene, function () {
  97719. _this.onDoneCallback(onSuccess, onError);
  97720. }, function (msg, exception) {
  97721. _this.onErrorCallback(onError, msg, exception);
  97722. });
  97723. };
  97724. /**
  97725. * Execute the current task
  97726. * @param scene defines the scene where you want your assets to be loaded
  97727. * @param onSuccess is a callback called when the task is successfully executed
  97728. * @param onError is a callback called if an error occurs
  97729. */
  97730. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97731. throw new Error("runTask is not implemented");
  97732. };
  97733. /**
  97734. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  97735. * This can be used with failed tasks that have the reason for failure fixed.
  97736. */
  97737. AbstractAssetTask.prototype.reset = function () {
  97738. this._taskState = AssetTaskState.INIT;
  97739. };
  97740. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  97741. this._taskState = AssetTaskState.ERROR;
  97742. this._errorObject = {
  97743. message: message,
  97744. exception: exception
  97745. };
  97746. if (this.onError) {
  97747. this.onError(this, message, exception);
  97748. }
  97749. onError();
  97750. };
  97751. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  97752. try {
  97753. this._taskState = AssetTaskState.DONE;
  97754. this._isCompleted = true;
  97755. if (this.onSuccess) {
  97756. this.onSuccess(this);
  97757. }
  97758. onSuccess();
  97759. }
  97760. catch (e) {
  97761. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  97762. }
  97763. };
  97764. return AbstractAssetTask;
  97765. }());
  97766. BABYLON.AbstractAssetTask = AbstractAssetTask;
  97767. /**
  97768. * Class used to share progress information about assets loading
  97769. */
  97770. var AssetsProgressEvent = /** @class */ (function () {
  97771. /**
  97772. * Creates a {BABYLON.AssetsProgressEvent}
  97773. * @param remainingCount defines the number of remaining tasks to process
  97774. * @param totalCount defines the total number of tasks
  97775. * @param task defines the task that was just processed
  97776. */
  97777. function AssetsProgressEvent(remainingCount, totalCount, task) {
  97778. this.remainingCount = remainingCount;
  97779. this.totalCount = totalCount;
  97780. this.task = task;
  97781. }
  97782. return AssetsProgressEvent;
  97783. }());
  97784. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  97785. /**
  97786. * Define a task used by {BABYLON.AssetsManager} to load meshes
  97787. */
  97788. var MeshAssetTask = /** @class */ (function (_super) {
  97789. __extends(MeshAssetTask, _super);
  97790. /**
  97791. * Creates a new {BABYLON.MeshAssetTask}
  97792. * @param name defines the name of the task
  97793. * @param meshesNames defines the list of mesh's names you want to load
  97794. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  97795. * @param sceneFilename defines the filename of the scene to load from
  97796. */
  97797. function MeshAssetTask(
  97798. /**
  97799. * Defines the name of the task
  97800. */
  97801. name,
  97802. /**
  97803. * Defines the list of mesh's names you want to load
  97804. */
  97805. meshesNames,
  97806. /**
  97807. * Defines the root url to use as a base to load your meshes and associated resources
  97808. */
  97809. rootUrl,
  97810. /**
  97811. * Defines the filename of the scene to load from
  97812. */
  97813. sceneFilename) {
  97814. var _this = _super.call(this, name) || this;
  97815. _this.name = name;
  97816. _this.meshesNames = meshesNames;
  97817. _this.rootUrl = rootUrl;
  97818. _this.sceneFilename = sceneFilename;
  97819. return _this;
  97820. }
  97821. /**
  97822. * Execute the current task
  97823. * @param scene defines the scene where you want your assets to be loaded
  97824. * @param onSuccess is a callback called when the task is successfully executed
  97825. * @param onError is a callback called if an error occurs
  97826. */
  97827. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97828. var _this = this;
  97829. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  97830. _this.loadedMeshes = meshes;
  97831. _this.loadedParticleSystems = particleSystems;
  97832. _this.loadedSkeletons = skeletons;
  97833. onSuccess();
  97834. }, null, function (scene, message, exception) {
  97835. onError(message, exception);
  97836. });
  97837. };
  97838. return MeshAssetTask;
  97839. }(AbstractAssetTask));
  97840. BABYLON.MeshAssetTask = MeshAssetTask;
  97841. /**
  97842. * Define a task used by {BABYLON.AssetsManager} to load text content
  97843. */
  97844. var TextFileAssetTask = /** @class */ (function (_super) {
  97845. __extends(TextFileAssetTask, _super);
  97846. /**
  97847. * Creates a new TextFileAssetTask object
  97848. * @param name defines the name of the task
  97849. * @param url defines the location of the file to load
  97850. */
  97851. function TextFileAssetTask(
  97852. /**
  97853. * Defines the name of the task
  97854. */
  97855. name,
  97856. /**
  97857. * Defines the location of the file to load
  97858. */
  97859. url) {
  97860. var _this = _super.call(this, name) || this;
  97861. _this.name = name;
  97862. _this.url = url;
  97863. return _this;
  97864. }
  97865. /**
  97866. * Execute the current task
  97867. * @param scene defines the scene where you want your assets to be loaded
  97868. * @param onSuccess is a callback called when the task is successfully executed
  97869. * @param onError is a callback called if an error occurs
  97870. */
  97871. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97872. var _this = this;
  97873. scene._loadFile(this.url, function (data) {
  97874. _this.text = data;
  97875. onSuccess();
  97876. }, undefined, false, false, function (request, exception) {
  97877. if (request) {
  97878. onError(request.status + " " + request.statusText, exception);
  97879. }
  97880. });
  97881. };
  97882. return TextFileAssetTask;
  97883. }(AbstractAssetTask));
  97884. BABYLON.TextFileAssetTask = TextFileAssetTask;
  97885. /**
  97886. * Define a task used by {BABYLON.AssetsManager} to load binary data
  97887. */
  97888. var BinaryFileAssetTask = /** @class */ (function (_super) {
  97889. __extends(BinaryFileAssetTask, _super);
  97890. /**
  97891. * Creates a new BinaryFileAssetTask object
  97892. * @param name defines the name of the new task
  97893. * @param url defines the location of the file to load
  97894. */
  97895. function BinaryFileAssetTask(
  97896. /**
  97897. * Defines the name of the task
  97898. */
  97899. name,
  97900. /**
  97901. * Defines the location of the file to load
  97902. */
  97903. url) {
  97904. var _this = _super.call(this, name) || this;
  97905. _this.name = name;
  97906. _this.url = url;
  97907. return _this;
  97908. }
  97909. /**
  97910. * Execute the current task
  97911. * @param scene defines the scene where you want your assets to be loaded
  97912. * @param onSuccess is a callback called when the task is successfully executed
  97913. * @param onError is a callback called if an error occurs
  97914. */
  97915. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97916. var _this = this;
  97917. scene._loadFile(this.url, function (data) {
  97918. _this.data = data;
  97919. onSuccess();
  97920. }, undefined, true, true, function (request, exception) {
  97921. if (request) {
  97922. onError(request.status + " " + request.statusText, exception);
  97923. }
  97924. });
  97925. };
  97926. return BinaryFileAssetTask;
  97927. }(AbstractAssetTask));
  97928. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  97929. /**
  97930. * Define a task used by {BABYLON.AssetsManager} to load images
  97931. */
  97932. var ImageAssetTask = /** @class */ (function (_super) {
  97933. __extends(ImageAssetTask, _super);
  97934. /**
  97935. * Creates a new ImageAssetTask
  97936. * @param name defines the name of the task
  97937. * @param url defines the location of the image to load
  97938. */
  97939. function ImageAssetTask(
  97940. /**
  97941. * Defines the name of the task
  97942. */
  97943. name,
  97944. /**
  97945. * Defines the location of the image to load
  97946. */
  97947. url) {
  97948. var _this = _super.call(this, name) || this;
  97949. _this.name = name;
  97950. _this.url = url;
  97951. return _this;
  97952. }
  97953. /**
  97954. * Execute the current task
  97955. * @param scene defines the scene where you want your assets to be loaded
  97956. * @param onSuccess is a callback called when the task is successfully executed
  97957. * @param onError is a callback called if an error occurs
  97958. */
  97959. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97960. var _this = this;
  97961. var img = new Image();
  97962. BABYLON.Tools.SetCorsBehavior(this.url, img);
  97963. img.onload = function () {
  97964. _this.image = img;
  97965. onSuccess();
  97966. };
  97967. img.onerror = function (err) {
  97968. onError("Error loading image", err);
  97969. };
  97970. img.src = this.url;
  97971. };
  97972. return ImageAssetTask;
  97973. }(AbstractAssetTask));
  97974. BABYLON.ImageAssetTask = ImageAssetTask;
  97975. /**
  97976. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  97977. */
  97978. var TextureAssetTask = /** @class */ (function (_super) {
  97979. __extends(TextureAssetTask, _super);
  97980. /**
  97981. * Creates a new TextureAssetTask object
  97982. * @param name defines the name of the task
  97983. * @param url defines the location of the file to load
  97984. * @param noMipmap defines if mipmap should not be generated (default is false)
  97985. * @param invertY defines if texture must be inverted on Y axis (default is false)
  97986. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97987. */
  97988. function TextureAssetTask(
  97989. /**
  97990. * Defines the name of the task
  97991. */
  97992. name,
  97993. /**
  97994. * Defines the location of the file to load
  97995. */
  97996. url,
  97997. /**
  97998. * Defines if mipmap should not be generated (default is false)
  97999. */
  98000. noMipmap,
  98001. /**
  98002. * Defines if texture must be inverted on Y axis (default is false)
  98003. */
  98004. invertY,
  98005. /**
  98006. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98007. */
  98008. samplingMode) {
  98009. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98010. var _this = _super.call(this, name) || this;
  98011. _this.name = name;
  98012. _this.url = url;
  98013. _this.noMipmap = noMipmap;
  98014. _this.invertY = invertY;
  98015. _this.samplingMode = samplingMode;
  98016. return _this;
  98017. }
  98018. /**
  98019. * Execute the current task
  98020. * @param scene defines the scene where you want your assets to be loaded
  98021. * @param onSuccess is a callback called when the task is successfully executed
  98022. * @param onError is a callback called if an error occurs
  98023. */
  98024. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98025. var onload = function () {
  98026. onSuccess();
  98027. };
  98028. var onerror = function (message, exception) {
  98029. onError(message, exception);
  98030. };
  98031. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  98032. };
  98033. return TextureAssetTask;
  98034. }(AbstractAssetTask));
  98035. BABYLON.TextureAssetTask = TextureAssetTask;
  98036. /**
  98037. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  98038. */
  98039. var CubeTextureAssetTask = /** @class */ (function (_super) {
  98040. __extends(CubeTextureAssetTask, _super);
  98041. /**
  98042. * Creates a new CubeTextureAssetTask
  98043. * @param name defines the name of the task
  98044. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98045. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98046. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98047. * @param files defines the explicit list of files (undefined by default)
  98048. */
  98049. function CubeTextureAssetTask(
  98050. /**
  98051. * Defines the name of the task
  98052. */
  98053. name,
  98054. /**
  98055. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98056. */
  98057. url,
  98058. /**
  98059. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98060. */
  98061. extensions,
  98062. /**
  98063. * Defines if mipmaps should not be generated (default is false)
  98064. */
  98065. noMipmap,
  98066. /**
  98067. * Defines the explicit list of files (undefined by default)
  98068. */
  98069. files) {
  98070. var _this = _super.call(this, name) || this;
  98071. _this.name = name;
  98072. _this.url = url;
  98073. _this.extensions = extensions;
  98074. _this.noMipmap = noMipmap;
  98075. _this.files = files;
  98076. return _this;
  98077. }
  98078. /**
  98079. * Execute the current task
  98080. * @param scene defines the scene where you want your assets to be loaded
  98081. * @param onSuccess is a callback called when the task is successfully executed
  98082. * @param onError is a callback called if an error occurs
  98083. */
  98084. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98085. var onload = function () {
  98086. onSuccess();
  98087. };
  98088. var onerror = function (message, exception) {
  98089. onError(message, exception);
  98090. };
  98091. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  98092. };
  98093. return CubeTextureAssetTask;
  98094. }(AbstractAssetTask));
  98095. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  98096. /**
  98097. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  98098. */
  98099. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  98100. __extends(HDRCubeTextureAssetTask, _super);
  98101. /**
  98102. * Creates a new HDRCubeTextureAssetTask object
  98103. * @param name defines the name of the task
  98104. * @param url defines the location of the file to load
  98105. * @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.
  98106. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98107. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98108. * @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)
  98109. * @param reserved Internal use only
  98110. */
  98111. function HDRCubeTextureAssetTask(
  98112. /**
  98113. * Defines the name of the task
  98114. */
  98115. name,
  98116. /**
  98117. * Defines the location of the file to load
  98118. */
  98119. url,
  98120. /**
  98121. * Defines the desired size (the more it increases the longer the generation will be)
  98122. */
  98123. size,
  98124. /**
  98125. * Defines if mipmaps should not be generated (default is false)
  98126. */
  98127. noMipmap,
  98128. /**
  98129. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98130. */
  98131. generateHarmonics,
  98132. /**
  98133. * 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)
  98134. */
  98135. gammaSpace,
  98136. /**
  98137. * Internal Use Only
  98138. */
  98139. reserved) {
  98140. if (noMipmap === void 0) { noMipmap = false; }
  98141. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98142. if (gammaSpace === void 0) { gammaSpace = false; }
  98143. if (reserved === void 0) { reserved = false; }
  98144. var _this = _super.call(this, name) || this;
  98145. _this.name = name;
  98146. _this.url = url;
  98147. _this.size = size;
  98148. _this.noMipmap = noMipmap;
  98149. _this.generateHarmonics = generateHarmonics;
  98150. _this.gammaSpace = gammaSpace;
  98151. _this.reserved = reserved;
  98152. return _this;
  98153. }
  98154. /**
  98155. * Execute the current task
  98156. * @param scene defines the scene where you want your assets to be loaded
  98157. * @param onSuccess is a callback called when the task is successfully executed
  98158. * @param onError is a callback called if an error occurs
  98159. */
  98160. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98161. var onload = function () {
  98162. onSuccess();
  98163. };
  98164. var onerror = function (message, exception) {
  98165. onError(message, exception);
  98166. };
  98167. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  98168. };
  98169. return HDRCubeTextureAssetTask;
  98170. }(AbstractAssetTask));
  98171. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  98172. /**
  98173. * This class can be used to easily import assets into a scene
  98174. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  98175. */
  98176. var AssetsManager = /** @class */ (function () {
  98177. /**
  98178. * Creates a new AssetsManager
  98179. * @param scene defines the scene to work on
  98180. */
  98181. function AssetsManager(scene) {
  98182. this._isLoading = false;
  98183. this._tasks = new Array();
  98184. this._waitingTasksCount = 0;
  98185. this._totalTasksCount = 0;
  98186. /**
  98187. * Observable called when all tasks are processed
  98188. */
  98189. this.onTaskSuccessObservable = new BABYLON.Observable();
  98190. /**
  98191. * Observable called when a task had an error
  98192. */
  98193. this.onTaskErrorObservable = new BABYLON.Observable();
  98194. /**
  98195. * Observable called when a task is successful
  98196. */
  98197. this.onTasksDoneObservable = new BABYLON.Observable();
  98198. /**
  98199. * Observable called when a task is done (whatever the result is)
  98200. */
  98201. this.onProgressObservable = new BABYLON.Observable();
  98202. /**
  98203. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  98204. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  98205. */
  98206. this.useDefaultLoadingScreen = true;
  98207. this._scene = scene;
  98208. }
  98209. /**
  98210. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  98211. * @param taskName defines the name of the new task
  98212. * @param meshesNames defines the name of meshes to load
  98213. * @param rootUrl defines the root url to use to locate files
  98214. * @param sceneFilename defines the filename of the scene file
  98215. * @returns a new {BABYLON.MeshAssetTask} object
  98216. */
  98217. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  98218. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  98219. this._tasks.push(task);
  98220. return task;
  98221. };
  98222. /**
  98223. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  98224. * @param taskName defines the name of the new task
  98225. * @param url defines the url of the file to load
  98226. * @returns a new {BABYLON.TextFileAssetTask} object
  98227. */
  98228. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  98229. var task = new TextFileAssetTask(taskName, url);
  98230. this._tasks.push(task);
  98231. return task;
  98232. };
  98233. /**
  98234. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  98235. * @param taskName defines the name of the new task
  98236. * @param url defines the url of the file to load
  98237. * @returns a new {BABYLON.BinaryFileAssetTask} object
  98238. */
  98239. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  98240. var task = new BinaryFileAssetTask(taskName, url);
  98241. this._tasks.push(task);
  98242. return task;
  98243. };
  98244. /**
  98245. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  98246. * @param taskName defines the name of the new task
  98247. * @param url defines the url of the file to load
  98248. * @returns a new {BABYLON.ImageAssetTask} object
  98249. */
  98250. AssetsManager.prototype.addImageTask = function (taskName, url) {
  98251. var task = new ImageAssetTask(taskName, url);
  98252. this._tasks.push(task);
  98253. return task;
  98254. };
  98255. /**
  98256. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  98257. * @param taskName defines the name of the new task
  98258. * @param url defines the url of the file to load
  98259. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98260. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  98261. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  98262. * @returns a new {BABYLON.TextureAssetTask} object
  98263. */
  98264. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  98265. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98266. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  98267. this._tasks.push(task);
  98268. return task;
  98269. };
  98270. /**
  98271. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  98272. * @param taskName defines the name of the new task
  98273. * @param url defines the url of the file to load
  98274. * @param extensions defines the extension to use to load the cube map (can be null)
  98275. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98276. * @param files defines the list of files to load (can be null)
  98277. * @returns a new {BABYLON.CubeTextureAssetTask} object
  98278. */
  98279. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  98280. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  98281. this._tasks.push(task);
  98282. return task;
  98283. };
  98284. /**
  98285. *
  98286. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  98287. * @param taskName defines the name of the new task
  98288. * @param url defines the url of the file to load
  98289. * @param size defines the size you want for the cubemap (can be null)
  98290. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98291. * @param generateHarmonics defines if you want to automatically generate (true by default)
  98292. * @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)
  98293. * @param reserved Internal use only
  98294. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  98295. */
  98296. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  98297. if (noMipmap === void 0) { noMipmap = false; }
  98298. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98299. if (gammaSpace === void 0) { gammaSpace = false; }
  98300. if (reserved === void 0) { reserved = false; }
  98301. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  98302. this._tasks.push(task);
  98303. return task;
  98304. };
  98305. /**
  98306. * Remove a task from the assets manager.
  98307. * @param task the task to remove
  98308. */
  98309. AssetsManager.prototype.removeTask = function (task) {
  98310. var index = this._tasks.indexOf(task);
  98311. if (index > -1) {
  98312. this._tasks.splice(index, 1);
  98313. }
  98314. };
  98315. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  98316. this._waitingTasksCount--;
  98317. try {
  98318. if (this.onProgress) {
  98319. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  98320. }
  98321. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  98322. }
  98323. catch (e) {
  98324. BABYLON.Tools.Error("Error running progress callbacks.");
  98325. console.log(e);
  98326. }
  98327. if (this._waitingTasksCount === 0) {
  98328. try {
  98329. if (this.onFinish) {
  98330. this.onFinish(this._tasks);
  98331. }
  98332. // Let's remove successfull tasks
  98333. var currentTasks = this._tasks.slice();
  98334. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  98335. var task = currentTasks_1[_i];
  98336. if (task.taskState === AssetTaskState.DONE) {
  98337. var index = this._tasks.indexOf(task);
  98338. if (index > -1) {
  98339. this._tasks.splice(index, 1);
  98340. }
  98341. }
  98342. }
  98343. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98344. }
  98345. catch (e) {
  98346. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  98347. console.log(e);
  98348. }
  98349. this._isLoading = false;
  98350. this._scene.getEngine().hideLoadingUI();
  98351. }
  98352. };
  98353. AssetsManager.prototype._runTask = function (task) {
  98354. var _this = this;
  98355. var done = function () {
  98356. try {
  98357. if (_this.onTaskSuccess) {
  98358. _this.onTaskSuccess(task);
  98359. }
  98360. _this.onTaskSuccessObservable.notifyObservers(task);
  98361. _this._decreaseWaitingTasksCount(task);
  98362. }
  98363. catch (e) {
  98364. error("Error executing task success callbacks", e);
  98365. }
  98366. };
  98367. var error = function (message, exception) {
  98368. task._setErrorObject(message, exception);
  98369. if (_this.onTaskError) {
  98370. _this.onTaskError(task);
  98371. }
  98372. _this.onTaskErrorObservable.notifyObservers(task);
  98373. _this._decreaseWaitingTasksCount(task);
  98374. };
  98375. task.run(this._scene, done, error);
  98376. };
  98377. /**
  98378. * Reset the {BABYLON.AssetsManager} and remove all tasks
  98379. * @return the current instance of the {BABYLON.AssetsManager}
  98380. */
  98381. AssetsManager.prototype.reset = function () {
  98382. this._isLoading = false;
  98383. this._tasks = new Array();
  98384. return this;
  98385. };
  98386. /**
  98387. * Start the loading process
  98388. * @return the current instance of the {BABYLON.AssetsManager}
  98389. */
  98390. AssetsManager.prototype.load = function () {
  98391. if (this._isLoading) {
  98392. return this;
  98393. }
  98394. this._isLoading = true;
  98395. this._waitingTasksCount = this._tasks.length;
  98396. this._totalTasksCount = this._tasks.length;
  98397. if (this._waitingTasksCount === 0) {
  98398. this._isLoading = false;
  98399. if (this.onFinish) {
  98400. this.onFinish(this._tasks);
  98401. }
  98402. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98403. return this;
  98404. }
  98405. if (this.useDefaultLoadingScreen) {
  98406. this._scene.getEngine().displayLoadingUI();
  98407. }
  98408. for (var index = 0; index < this._tasks.length; index++) {
  98409. var task = this._tasks[index];
  98410. if (task.taskState === AssetTaskState.INIT) {
  98411. this._runTask(task);
  98412. }
  98413. }
  98414. return this;
  98415. };
  98416. return AssetsManager;
  98417. }());
  98418. BABYLON.AssetsManager = AssetsManager;
  98419. })(BABYLON || (BABYLON = {}));
  98420. //# sourceMappingURL=babylon.assetsManager.js.map
  98421. var BABYLON;
  98422. (function (BABYLON) {
  98423. var serializedGeometries = [];
  98424. var serializeGeometry = function (geometry, serializationGeometries) {
  98425. if (serializedGeometries[geometry.id]) {
  98426. return;
  98427. }
  98428. if (geometry.doNotSerialize) {
  98429. return;
  98430. }
  98431. if (geometry instanceof BABYLON.BoxGeometry) {
  98432. serializationGeometries.boxes.push(geometry.serialize());
  98433. }
  98434. else if (geometry instanceof BABYLON.SphereGeometry) {
  98435. serializationGeometries.spheres.push(geometry.serialize());
  98436. }
  98437. else if (geometry instanceof BABYLON.CylinderGeometry) {
  98438. serializationGeometries.cylinders.push(geometry.serialize());
  98439. }
  98440. else if (geometry instanceof BABYLON.TorusGeometry) {
  98441. serializationGeometries.toruses.push(geometry.serialize());
  98442. }
  98443. else if (geometry instanceof BABYLON.GroundGeometry) {
  98444. serializationGeometries.grounds.push(geometry.serialize());
  98445. }
  98446. else if (geometry instanceof BABYLON.Plane) {
  98447. serializationGeometries.planes.push(geometry.serialize());
  98448. }
  98449. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  98450. serializationGeometries.torusKnots.push(geometry.serialize());
  98451. }
  98452. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  98453. throw new Error("Unknown primitive type");
  98454. }
  98455. else {
  98456. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  98457. }
  98458. serializedGeometries[geometry.id] = true;
  98459. };
  98460. var serializeMesh = function (mesh, serializationScene) {
  98461. var serializationObject = {};
  98462. // Geometry
  98463. var geometry = mesh._geometry;
  98464. if (geometry) {
  98465. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  98466. // 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
  98467. serializeGeometry(geometry, serializationScene.geometries);
  98468. }
  98469. }
  98470. // Custom
  98471. if (mesh.serialize) {
  98472. mesh.serialize(serializationObject);
  98473. }
  98474. return serializationObject;
  98475. };
  98476. var finalizeSingleMesh = function (mesh, serializationObject) {
  98477. //only works if the mesh is already loaded
  98478. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98479. //serialize material
  98480. if (mesh.material) {
  98481. if (mesh.material instanceof BABYLON.MultiMaterial) {
  98482. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  98483. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98484. serializationObject.multiMaterials.push(mesh.material.serialize());
  98485. }
  98486. }
  98487. else {
  98488. serializationObject.materials = serializationObject.materials || [];
  98489. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98490. serializationObject.materials.push(mesh.material.serialize());
  98491. }
  98492. }
  98493. }
  98494. //serialize geometry
  98495. var geometry = mesh._geometry;
  98496. if (geometry) {
  98497. if (!serializationObject.geometries) {
  98498. serializationObject.geometries = {};
  98499. serializationObject.geometries.boxes = [];
  98500. serializationObject.geometries.spheres = [];
  98501. serializationObject.geometries.cylinders = [];
  98502. serializationObject.geometries.toruses = [];
  98503. serializationObject.geometries.grounds = [];
  98504. serializationObject.geometries.planes = [];
  98505. serializationObject.geometries.torusKnots = [];
  98506. serializationObject.geometries.vertexData = [];
  98507. }
  98508. serializeGeometry(geometry, serializationObject.geometries);
  98509. }
  98510. // Skeletons
  98511. if (mesh.skeleton) {
  98512. serializationObject.skeletons = serializationObject.skeletons || [];
  98513. serializationObject.skeletons.push(mesh.skeleton.serialize());
  98514. }
  98515. //serialize the actual mesh
  98516. serializationObject.meshes = serializationObject.meshes || [];
  98517. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98518. }
  98519. };
  98520. var SceneSerializer = /** @class */ (function () {
  98521. function SceneSerializer() {
  98522. }
  98523. SceneSerializer.ClearCache = function () {
  98524. serializedGeometries = [];
  98525. };
  98526. SceneSerializer.Serialize = function (scene) {
  98527. var serializationObject = {};
  98528. SceneSerializer.ClearCache();
  98529. // Scene
  98530. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  98531. serializationObject.autoClear = scene.autoClear;
  98532. serializationObject.clearColor = scene.clearColor.asArray();
  98533. serializationObject.ambientColor = scene.ambientColor.asArray();
  98534. serializationObject.gravity = scene.gravity.asArray();
  98535. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  98536. serializationObject.workerCollisions = scene.workerCollisions;
  98537. // Fog
  98538. if (scene.fogMode && scene.fogMode !== 0) {
  98539. serializationObject.fogMode = scene.fogMode;
  98540. serializationObject.fogColor = scene.fogColor.asArray();
  98541. serializationObject.fogStart = scene.fogStart;
  98542. serializationObject.fogEnd = scene.fogEnd;
  98543. serializationObject.fogDensity = scene.fogDensity;
  98544. }
  98545. //Physics
  98546. if (scene.isPhysicsEnabled()) {
  98547. var physicEngine = scene.getPhysicsEngine();
  98548. if (physicEngine) {
  98549. serializationObject.physicsEnabled = true;
  98550. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  98551. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  98552. }
  98553. }
  98554. // Metadata
  98555. if (scene.metadata) {
  98556. serializationObject.metadata = scene.metadata;
  98557. }
  98558. // Morph targets
  98559. serializationObject.morphTargetManagers = [];
  98560. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  98561. var abstractMesh = _a[_i];
  98562. var manager = abstractMesh.morphTargetManager;
  98563. if (manager) {
  98564. serializationObject.morphTargetManagers.push(manager.serialize());
  98565. }
  98566. }
  98567. // Lights
  98568. serializationObject.lights = [];
  98569. var index;
  98570. var light;
  98571. for (index = 0; index < scene.lights.length; index++) {
  98572. light = scene.lights[index];
  98573. if (!light.doNotSerialize) {
  98574. serializationObject.lights.push(light.serialize());
  98575. }
  98576. }
  98577. // Cameras
  98578. serializationObject.cameras = [];
  98579. for (index = 0; index < scene.cameras.length; index++) {
  98580. var camera = scene.cameras[index];
  98581. if (!camera.doNotSerialize) {
  98582. serializationObject.cameras.push(camera.serialize());
  98583. }
  98584. }
  98585. if (scene.activeCamera) {
  98586. serializationObject.activeCameraID = scene.activeCamera.id;
  98587. }
  98588. // Animations
  98589. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  98590. // Materials
  98591. serializationObject.materials = [];
  98592. serializationObject.multiMaterials = [];
  98593. var material;
  98594. for (index = 0; index < scene.materials.length; index++) {
  98595. material = scene.materials[index];
  98596. if (!material.doNotSerialize) {
  98597. serializationObject.materials.push(material.serialize());
  98598. }
  98599. }
  98600. // MultiMaterials
  98601. serializationObject.multiMaterials = [];
  98602. for (index = 0; index < scene.multiMaterials.length; index++) {
  98603. var multiMaterial = scene.multiMaterials[index];
  98604. serializationObject.multiMaterials.push(multiMaterial.serialize());
  98605. }
  98606. // Environment texture
  98607. if (scene.environmentTexture) {
  98608. serializationObject.environmentTexture = scene.environmentTexture.name;
  98609. }
  98610. // Skeletons
  98611. serializationObject.skeletons = [];
  98612. for (index = 0; index < scene.skeletons.length; index++) {
  98613. var skeleton = scene.skeletons[index];
  98614. if (!skeleton.doNotSerialize) {
  98615. serializationObject.skeletons.push(skeleton.serialize());
  98616. }
  98617. }
  98618. // Transform nodes
  98619. serializationObject.transformNodes = [];
  98620. for (index = 0; index < scene.transformNodes.length; index++) {
  98621. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  98622. }
  98623. // Geometries
  98624. serializationObject.geometries = {};
  98625. serializationObject.geometries.boxes = [];
  98626. serializationObject.geometries.spheres = [];
  98627. serializationObject.geometries.cylinders = [];
  98628. serializationObject.geometries.toruses = [];
  98629. serializationObject.geometries.grounds = [];
  98630. serializationObject.geometries.planes = [];
  98631. serializationObject.geometries.torusKnots = [];
  98632. serializationObject.geometries.vertexData = [];
  98633. serializedGeometries = [];
  98634. var geometries = scene.getGeometries();
  98635. for (index = 0; index < geometries.length; index++) {
  98636. var geometry = geometries[index];
  98637. if (geometry.isReady()) {
  98638. serializeGeometry(geometry, serializationObject.geometries);
  98639. }
  98640. }
  98641. // Meshes
  98642. serializationObject.meshes = [];
  98643. for (index = 0; index < scene.meshes.length; index++) {
  98644. var abstractMesh = scene.meshes[index];
  98645. if (abstractMesh instanceof BABYLON.Mesh) {
  98646. var mesh = abstractMesh;
  98647. if (!mesh.doNotSerialize) {
  98648. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98649. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98650. }
  98651. }
  98652. }
  98653. }
  98654. // Particles Systems
  98655. serializationObject.particleSystems = [];
  98656. for (index = 0; index < scene.particleSystems.length; index++) {
  98657. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  98658. }
  98659. // Shadows
  98660. serializationObject.shadowGenerators = [];
  98661. for (index = 0; index < scene.lights.length; index++) {
  98662. light = scene.lights[index];
  98663. var shadowGenerator = light.getShadowGenerator();
  98664. if (shadowGenerator) {
  98665. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  98666. }
  98667. }
  98668. // Action Manager
  98669. if (scene.actionManager) {
  98670. serializationObject.actions = scene.actionManager.serialize("scene");
  98671. }
  98672. // Audio
  98673. serializationObject.sounds = [];
  98674. for (index = 0; index < scene.soundTracks.length; index++) {
  98675. var soundtrack = scene.soundTracks[index];
  98676. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  98677. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  98678. }
  98679. }
  98680. // Components
  98681. for (var _b = 0, _c = scene._components; _b < _c.length; _b++) {
  98682. var component = _c[_b];
  98683. component.serialize(serializationObject);
  98684. }
  98685. return serializationObject;
  98686. };
  98687. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  98688. if (withParents === void 0) { withParents = false; }
  98689. if (withChildren === void 0) { withChildren = false; }
  98690. var serializationObject = {};
  98691. SceneSerializer.ClearCache();
  98692. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  98693. if (withParents || withChildren) {
  98694. //deliberate for loop! not for each, appended should be processed as well.
  98695. for (var i = 0; i < toSerialize.length; ++i) {
  98696. if (withChildren) {
  98697. toSerialize[i].getDescendants().forEach(function (node) {
  98698. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  98699. toSerialize.push(node);
  98700. }
  98701. });
  98702. }
  98703. //make sure the array doesn't contain the object already
  98704. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  98705. toSerialize.push(toSerialize[i].parent);
  98706. }
  98707. }
  98708. }
  98709. toSerialize.forEach(function (mesh) {
  98710. finalizeSingleMesh(mesh, serializationObject);
  98711. });
  98712. return serializationObject;
  98713. };
  98714. return SceneSerializer;
  98715. }());
  98716. BABYLON.SceneSerializer = SceneSerializer;
  98717. })(BABYLON || (BABYLON = {}));
  98718. //# sourceMappingURL=babylon.sceneSerializer.js.map
  98719. var BABYLON;
  98720. (function (BABYLON) {
  98721. var ReflectionProbe = /** @class */ (function () {
  98722. function ReflectionProbe(name, size, scene, generateMipMaps) {
  98723. if (generateMipMaps === void 0) { generateMipMaps = true; }
  98724. var _this = this;
  98725. this.name = name;
  98726. this._viewMatrix = BABYLON.Matrix.Identity();
  98727. this._target = BABYLON.Vector3.Zero();
  98728. this._add = BABYLON.Vector3.Zero();
  98729. this._invertYAxis = false;
  98730. this.position = BABYLON.Vector3.Zero();
  98731. this._scene = scene;
  98732. this._scene.reflectionProbes.push(this);
  98733. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  98734. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  98735. switch (faceIndex) {
  98736. case 0:
  98737. _this._add.copyFromFloats(1, 0, 0);
  98738. break;
  98739. case 1:
  98740. _this._add.copyFromFloats(-1, 0, 0);
  98741. break;
  98742. case 2:
  98743. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  98744. break;
  98745. case 3:
  98746. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  98747. break;
  98748. case 4:
  98749. _this._add.copyFromFloats(0, 0, 1);
  98750. break;
  98751. case 5:
  98752. _this._add.copyFromFloats(0, 0, -1);
  98753. break;
  98754. }
  98755. if (_this._attachedMesh) {
  98756. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  98757. }
  98758. _this.position.addToRef(_this._add, _this._target);
  98759. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  98760. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  98761. scene._forcedViewPosition = _this.position;
  98762. });
  98763. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  98764. scene._forcedViewPosition = null;
  98765. scene.updateTransformMatrix(true);
  98766. });
  98767. if (scene.activeCamera) {
  98768. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  98769. }
  98770. }
  98771. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  98772. get: function () {
  98773. return this._renderTargetTexture.samples;
  98774. },
  98775. set: function (value) {
  98776. this._renderTargetTexture.samples = value;
  98777. },
  98778. enumerable: true,
  98779. configurable: true
  98780. });
  98781. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  98782. get: function () {
  98783. return this._renderTargetTexture.refreshRate;
  98784. },
  98785. set: function (value) {
  98786. this._renderTargetTexture.refreshRate = value;
  98787. },
  98788. enumerable: true,
  98789. configurable: true
  98790. });
  98791. ReflectionProbe.prototype.getScene = function () {
  98792. return this._scene;
  98793. };
  98794. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  98795. get: function () {
  98796. return this._renderTargetTexture;
  98797. },
  98798. enumerable: true,
  98799. configurable: true
  98800. });
  98801. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  98802. get: function () {
  98803. return this._renderTargetTexture.renderList;
  98804. },
  98805. enumerable: true,
  98806. configurable: true
  98807. });
  98808. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  98809. this._attachedMesh = mesh;
  98810. };
  98811. /**
  98812. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  98813. *
  98814. * @param renderingGroupId The rendering group id corresponding to its index
  98815. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  98816. */
  98817. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  98818. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  98819. };
  98820. ReflectionProbe.prototype.dispose = function () {
  98821. var index = this._scene.reflectionProbes.indexOf(this);
  98822. if (index !== -1) {
  98823. // Remove from the scene if found
  98824. this._scene.reflectionProbes.splice(index, 1);
  98825. }
  98826. if (this._renderTargetTexture) {
  98827. this._renderTargetTexture.dispose();
  98828. this._renderTargetTexture = null;
  98829. }
  98830. };
  98831. return ReflectionProbe;
  98832. }());
  98833. BABYLON.ReflectionProbe = ReflectionProbe;
  98834. })(BABYLON || (BABYLON = {}));
  98835. //# sourceMappingURL=babylon.reflectionProbe.js.map
  98836. var BABYLON;
  98837. (function (BABYLON) {
  98838. /**
  98839. * Defines the layer scene component responsible to manage any layers
  98840. * in a given scene.
  98841. */
  98842. var LayerSceneComponent = /** @class */ (function () {
  98843. /**
  98844. * Creates a new instance of the component for the given scene
  98845. * @param scene Defines the scene to register the component in
  98846. */
  98847. function LayerSceneComponent(scene) {
  98848. /**
  98849. * The component name helpfull to identify the component in the list of scene components.
  98850. */
  98851. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  98852. this.scene = scene;
  98853. this._engine = scene.getEngine();
  98854. this._layers = scene.layers = new Array();
  98855. }
  98856. /**
  98857. * Registers the component in a given scene
  98858. */
  98859. LayerSceneComponent.prototype.register = function () {
  98860. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  98861. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  98862. };
  98863. /**
  98864. * Rebuilds the elements related to this component in case of
  98865. * context lost for instance.
  98866. */
  98867. LayerSceneComponent.prototype.rebuild = function () {
  98868. for (var _i = 0, _a = this._layers; _i < _a.length; _i++) {
  98869. var layer = _a[_i];
  98870. layer._rebuild();
  98871. }
  98872. };
  98873. /**
  98874. * Serializes the component data to the specified json object
  98875. * @param serializationObject The object to serialize to
  98876. */
  98877. LayerSceneComponent.prototype.serialize = function (serializationObject) {
  98878. // TODO. Implement layer serialization
  98879. // serializationObject.layers = [];
  98880. // for (let layer of this._layers) {
  98881. // if (layer.serialize) {
  98882. // serializationObject.layers.push(layer.serialize());
  98883. // }
  98884. // }
  98885. };
  98886. /**
  98887. * Adds all the element from the container to the scene
  98888. * @param container the container holding the elements
  98889. */
  98890. LayerSceneComponent.prototype.addFromContainer = function (container) {
  98891. if (!container.layers) {
  98892. return;
  98893. }
  98894. // container.layers.forEach((o) => {
  98895. // this.scene.addLayer(o);
  98896. // });
  98897. };
  98898. /**
  98899. * Removes all the elements in the container from the scene
  98900. * @param container contains the elements to remove
  98901. */
  98902. LayerSceneComponent.prototype.removeFromContainer = function (container) {
  98903. if (!container.layers) {
  98904. return;
  98905. }
  98906. // container.layers.forEach((o) => {
  98907. // this.scene.removeLayer(o);
  98908. // });
  98909. };
  98910. /**
  98911. * Disposes the component and the associated ressources.
  98912. */
  98913. LayerSceneComponent.prototype.dispose = function () {
  98914. while (this._layers.length) {
  98915. this._layers[0].dispose();
  98916. }
  98917. };
  98918. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  98919. if (this._layers.length) {
  98920. this._engine.setDepthBuffer(false);
  98921. var cameraLayerMask = camera.layerMask;
  98922. for (var _i = 0, _a = this._layers; _i < _a.length; _i++) {
  98923. var layer = _a[_i];
  98924. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  98925. layer.render();
  98926. }
  98927. }
  98928. this._engine.setDepthBuffer(true);
  98929. }
  98930. };
  98931. LayerSceneComponent.prototype._drawBackground = function (camera) {
  98932. this._draw(camera, true);
  98933. };
  98934. LayerSceneComponent.prototype._drawForeground = function (camera) {
  98935. this._draw(camera, false);
  98936. };
  98937. return LayerSceneComponent;
  98938. }());
  98939. BABYLON.LayerSceneComponent = LayerSceneComponent;
  98940. })(BABYLON || (BABYLON = {}));
  98941. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  98942. var BABYLON;
  98943. (function (BABYLON) {
  98944. var Layer = /** @class */ (function () {
  98945. function Layer(name, imgUrl, scene, isBackground, color) {
  98946. this.name = name;
  98947. this.scale = new BABYLON.Vector2(1, 1);
  98948. this.offset = new BABYLON.Vector2(0, 0);
  98949. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  98950. this.layerMask = 0x0FFFFFFF;
  98951. this._vertexBuffers = {};
  98952. // Events
  98953. /**
  98954. * An event triggered when the layer is disposed.
  98955. */
  98956. this.onDisposeObservable = new BABYLON.Observable();
  98957. /**
  98958. * An event triggered before rendering the scene
  98959. */
  98960. this.onBeforeRenderObservable = new BABYLON.Observable();
  98961. /**
  98962. * An event triggered after rendering the scene
  98963. */
  98964. this.onAfterRenderObservable = new BABYLON.Observable();
  98965. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  98966. this.isBackground = isBackground === undefined ? true : isBackground;
  98967. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  98968. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  98969. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  98970. if (!layerComponent) {
  98971. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  98972. this._scene._addComponent(layerComponent);
  98973. }
  98974. this._scene.layers.push(this);
  98975. var engine = this._scene.getEngine();
  98976. // VBO
  98977. var vertices = [];
  98978. vertices.push(1, 1);
  98979. vertices.push(-1, 1);
  98980. vertices.push(-1, -1);
  98981. vertices.push(1, -1);
  98982. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  98983. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  98984. this._createIndexBuffer();
  98985. // Effects
  98986. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  98987. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  98988. }
  98989. Object.defineProperty(Layer.prototype, "onDispose", {
  98990. set: function (callback) {
  98991. if (this._onDisposeObserver) {
  98992. this.onDisposeObservable.remove(this._onDisposeObserver);
  98993. }
  98994. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  98995. },
  98996. enumerable: true,
  98997. configurable: true
  98998. });
  98999. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  99000. set: function (callback) {
  99001. if (this._onBeforeRenderObserver) {
  99002. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  99003. }
  99004. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  99005. },
  99006. enumerable: true,
  99007. configurable: true
  99008. });
  99009. Object.defineProperty(Layer.prototype, "onAfterRender", {
  99010. set: function (callback) {
  99011. if (this._onAfterRenderObserver) {
  99012. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99013. }
  99014. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  99015. },
  99016. enumerable: true,
  99017. configurable: true
  99018. });
  99019. Layer.prototype._createIndexBuffer = function () {
  99020. var engine = this._scene.getEngine();
  99021. // Indices
  99022. var indices = [];
  99023. indices.push(0);
  99024. indices.push(1);
  99025. indices.push(2);
  99026. indices.push(0);
  99027. indices.push(2);
  99028. indices.push(3);
  99029. this._indexBuffer = engine.createIndexBuffer(indices);
  99030. };
  99031. Layer.prototype._rebuild = function () {
  99032. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99033. if (vb) {
  99034. vb._rebuild();
  99035. }
  99036. this._createIndexBuffer();
  99037. };
  99038. Layer.prototype.render = function () {
  99039. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  99040. // Check
  99041. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  99042. return;
  99043. var engine = this._scene.getEngine();
  99044. this.onBeforeRenderObservable.notifyObservers(this);
  99045. // Render
  99046. engine.enableEffect(currentEffect);
  99047. engine.setState(false);
  99048. // Texture
  99049. currentEffect.setTexture("textureSampler", this.texture);
  99050. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  99051. // Color
  99052. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  99053. // Scale / offset
  99054. currentEffect.setVector2("offset", this.offset);
  99055. currentEffect.setVector2("scale", this.scale);
  99056. // VBOs
  99057. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  99058. // Draw order
  99059. if (!this.alphaTest) {
  99060. engine.setAlphaMode(this.alphaBlendingMode);
  99061. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99062. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99063. }
  99064. else {
  99065. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99066. }
  99067. this.onAfterRenderObservable.notifyObservers(this);
  99068. };
  99069. Layer.prototype.dispose = function () {
  99070. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99071. if (vertexBuffer) {
  99072. vertexBuffer.dispose();
  99073. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  99074. }
  99075. if (this._indexBuffer) {
  99076. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  99077. this._indexBuffer = null;
  99078. }
  99079. if (this.texture) {
  99080. this.texture.dispose();
  99081. this.texture = null;
  99082. }
  99083. // Remove from scene
  99084. var index = this._scene.layers.indexOf(this);
  99085. this._scene.layers.splice(index, 1);
  99086. // Callback
  99087. this.onDisposeObservable.notifyObservers(this);
  99088. this.onDisposeObservable.clear();
  99089. this.onAfterRenderObservable.clear();
  99090. this.onBeforeRenderObservable.clear();
  99091. };
  99092. return Layer;
  99093. }());
  99094. BABYLON.Layer = Layer;
  99095. })(BABYLON || (BABYLON = {}));
  99096. //# sourceMappingURL=babylon.layer.js.map
  99097. var BABYLON;
  99098. (function (BABYLON) {
  99099. var TextureTools = /** @class */ (function () {
  99100. function TextureTools() {
  99101. }
  99102. /**
  99103. * Uses the GPU to create a copy texture rescaled at a given size
  99104. * @param texture Texture to copy from
  99105. * @param width Desired width
  99106. * @param height Desired height
  99107. * @return Generated texture
  99108. */
  99109. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  99110. if (useBilinearMode === void 0) { useBilinearMode = true; }
  99111. var scene = texture.getScene();
  99112. var engine = scene.getEngine();
  99113. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  99114. rtt.wrapU = texture.wrapU;
  99115. rtt.wrapV = texture.wrapV;
  99116. rtt.uOffset = texture.uOffset;
  99117. rtt.vOffset = texture.vOffset;
  99118. rtt.uScale = texture.uScale;
  99119. rtt.vScale = texture.vScale;
  99120. rtt.uAng = texture.uAng;
  99121. rtt.vAng = texture.vAng;
  99122. rtt.wAng = texture.wAng;
  99123. rtt.coordinatesIndex = texture.coordinatesIndex;
  99124. rtt.level = texture.level;
  99125. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  99126. rtt._texture.isReady = false;
  99127. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99128. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99129. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99130. passPostProcess.getEffect().executeWhenCompiled(function () {
  99131. passPostProcess.onApply = function (effect) {
  99132. effect.setTexture("textureSampler", texture);
  99133. };
  99134. var internalTexture = rtt.getInternalTexture();
  99135. if (internalTexture) {
  99136. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  99137. engine.unBindFramebuffer(internalTexture);
  99138. rtt.disposeFramebufferObjects();
  99139. passPostProcess.dispose();
  99140. internalTexture.isReady = true;
  99141. }
  99142. });
  99143. return rtt;
  99144. };
  99145. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  99146. if (!scene._environmentBRDFTexture) {
  99147. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99148. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99149. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99150. scene._environmentBRDFTexture = texture;
  99151. }
  99152. return scene._environmentBRDFTexture;
  99153. };
  99154. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUU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QLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  99155. return TextureTools;
  99156. }());
  99157. BABYLON.TextureTools = TextureTools;
  99158. })(BABYLON || (BABYLON = {}));
  99159. //# sourceMappingURL=babylon.textureTools.js.map
  99160. var BABYLON;
  99161. (function (BABYLON) {
  99162. var FramingBehavior = /** @class */ (function () {
  99163. function FramingBehavior() {
  99164. this._mode = FramingBehavior.FitFrustumSidesMode;
  99165. this._radiusScale = 1.0;
  99166. this._positionScale = 0.5;
  99167. this._defaultElevation = 0.3;
  99168. this._elevationReturnTime = 1500;
  99169. this._elevationReturnWaitTime = 1000;
  99170. this._zoomStopsAnimation = false;
  99171. this._framingTime = 1500;
  99172. this._isPointerDown = false;
  99173. this._lastInteractionTime = -Infinity;
  99174. // Framing control
  99175. this._animatables = new Array();
  99176. this._betaIsAnimating = false;
  99177. }
  99178. Object.defineProperty(FramingBehavior.prototype, "name", {
  99179. get: function () {
  99180. return "Framing";
  99181. },
  99182. enumerable: true,
  99183. configurable: true
  99184. });
  99185. Object.defineProperty(FramingBehavior.prototype, "mode", {
  99186. /**
  99187. * Gets current mode used by the behavior.
  99188. */
  99189. get: function () {
  99190. return this._mode;
  99191. },
  99192. /**
  99193. * Sets the current mode used by the behavior
  99194. */
  99195. set: function (mode) {
  99196. this._mode = mode;
  99197. },
  99198. enumerable: true,
  99199. configurable: true
  99200. });
  99201. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  99202. /**
  99203. * Gets the scale applied to the radius
  99204. */
  99205. get: function () {
  99206. return this._radiusScale;
  99207. },
  99208. /**
  99209. * Sets the scale applied to the radius (1 by default)
  99210. */
  99211. set: function (radius) {
  99212. this._radiusScale = radius;
  99213. },
  99214. enumerable: true,
  99215. configurable: true
  99216. });
  99217. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  99218. /**
  99219. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99220. */
  99221. get: function () {
  99222. return this._positionScale;
  99223. },
  99224. /**
  99225. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99226. */
  99227. set: function (scale) {
  99228. this._positionScale = scale;
  99229. },
  99230. enumerable: true,
  99231. configurable: true
  99232. });
  99233. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  99234. /**
  99235. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99236. * behaviour is triggered, in radians.
  99237. */
  99238. get: function () {
  99239. return this._defaultElevation;
  99240. },
  99241. /**
  99242. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99243. * behaviour is triggered, in radians.
  99244. */
  99245. set: function (elevation) {
  99246. this._defaultElevation = elevation;
  99247. },
  99248. enumerable: true,
  99249. configurable: true
  99250. });
  99251. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  99252. /**
  99253. * Gets the time (in milliseconds) taken to return to the default beta position.
  99254. * Negative value indicates camera should not return to default.
  99255. */
  99256. get: function () {
  99257. return this._elevationReturnTime;
  99258. },
  99259. /**
  99260. * Sets the time (in milliseconds) taken to return to the default beta position.
  99261. * Negative value indicates camera should not return to default.
  99262. */
  99263. set: function (speed) {
  99264. this._elevationReturnTime = speed;
  99265. },
  99266. enumerable: true,
  99267. configurable: true
  99268. });
  99269. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  99270. /**
  99271. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99272. */
  99273. get: function () {
  99274. return this._elevationReturnWaitTime;
  99275. },
  99276. /**
  99277. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99278. */
  99279. set: function (time) {
  99280. this._elevationReturnWaitTime = time;
  99281. },
  99282. enumerable: true,
  99283. configurable: true
  99284. });
  99285. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  99286. /**
  99287. * Gets the flag that indicates if user zooming should stop animation.
  99288. */
  99289. get: function () {
  99290. return this._zoomStopsAnimation;
  99291. },
  99292. /**
  99293. * Sets the flag that indicates if user zooming should stop animation.
  99294. */
  99295. set: function (flag) {
  99296. this._zoomStopsAnimation = flag;
  99297. },
  99298. enumerable: true,
  99299. configurable: true
  99300. });
  99301. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  99302. /**
  99303. * Gets the transition time when framing the mesh, in milliseconds
  99304. */
  99305. get: function () {
  99306. return this._framingTime;
  99307. },
  99308. /**
  99309. * Sets the transition time when framing the mesh, in milliseconds
  99310. */
  99311. set: function (time) {
  99312. this._framingTime = time;
  99313. },
  99314. enumerable: true,
  99315. configurable: true
  99316. });
  99317. FramingBehavior.prototype.init = function () {
  99318. // Do notihng
  99319. };
  99320. FramingBehavior.prototype.attach = function (camera) {
  99321. var _this = this;
  99322. this._attachedCamera = camera;
  99323. var scene = this._attachedCamera.getScene();
  99324. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  99325. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99326. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99327. _this._isPointerDown = true;
  99328. return;
  99329. }
  99330. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99331. _this._isPointerDown = false;
  99332. }
  99333. });
  99334. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99335. if (mesh) {
  99336. _this.zoomOnMesh(mesh);
  99337. }
  99338. });
  99339. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99340. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99341. _this._applyUserInteraction();
  99342. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  99343. // back to the default position after a given timeout
  99344. _this._maintainCameraAboveGround();
  99345. });
  99346. };
  99347. FramingBehavior.prototype.detach = function () {
  99348. if (!this._attachedCamera) {
  99349. return;
  99350. }
  99351. var scene = this._attachedCamera.getScene();
  99352. if (this._onPrePointerObservableObserver) {
  99353. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99354. }
  99355. if (this._onAfterCheckInputsObserver) {
  99356. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99357. }
  99358. if (this._onMeshTargetChangedObserver) {
  99359. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99360. }
  99361. this._attachedCamera = null;
  99362. };
  99363. /**
  99364. * Targets the given mesh and updates zoom level accordingly.
  99365. * @param mesh The mesh to target.
  99366. * @param radius Optional. If a cached radius position already exists, overrides default.
  99367. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99368. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99369. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99370. */
  99371. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99372. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99373. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99374. mesh.computeWorldMatrix(true);
  99375. var boundingBox = mesh.getBoundingInfo().boundingBox;
  99376. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  99377. };
  99378. /**
  99379. * Targets the given mesh with its children and updates zoom level accordingly.
  99380. * @param mesh The mesh to target.
  99381. * @param radius Optional. If a cached radius position already exists, overrides default.
  99382. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99383. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99384. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99385. */
  99386. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99387. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99388. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99389. mesh.computeWorldMatrix(true);
  99390. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  99391. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  99392. };
  99393. /**
  99394. * Targets the given meshes with their children and updates zoom level accordingly.
  99395. * @param meshes The mesh to target.
  99396. * @param radius Optional. If a cached radius position already exists, overrides default.
  99397. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99398. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99399. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99400. */
  99401. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  99402. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99403. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99404. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  99405. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  99406. for (var i = 0; i < meshes.length; i++) {
  99407. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  99408. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  99409. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  99410. }
  99411. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  99412. };
  99413. /**
  99414. * Targets the given mesh and updates zoom level accordingly.
  99415. * @param mesh The mesh to target.
  99416. * @param radius Optional. If a cached radius position already exists, overrides default.
  99417. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99418. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99419. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99420. */
  99421. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  99422. var _this = this;
  99423. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99424. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99425. var zoomTarget;
  99426. if (!this._attachedCamera) {
  99427. return;
  99428. }
  99429. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  99430. var bottom = minimumWorld.y;
  99431. var top = maximumWorld.y;
  99432. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  99433. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  99434. if (focusOnOriginXZ) {
  99435. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  99436. }
  99437. else {
  99438. var centerWorld = minimumWorld.add(radiusWorld);
  99439. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  99440. }
  99441. if (!this._vectorTransition) {
  99442. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  99443. }
  99444. this._betaIsAnimating = true;
  99445. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  99446. if (animatable) {
  99447. this._animatables.push(animatable);
  99448. }
  99449. // sets the radius and lower radius bounds
  99450. // Small delta ensures camera is not always at lower zoom limit.
  99451. var radius = 0;
  99452. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  99453. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99454. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  99455. radius = position;
  99456. }
  99457. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99458. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99459. if (this._attachedCamera.lowerRadiusLimit === null) {
  99460. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  99461. }
  99462. }
  99463. // Set sensibilities
  99464. var extend = maximumWorld.subtract(minimumWorld).length();
  99465. this._attachedCamera.panningSensibility = 5000 / extend;
  99466. this._attachedCamera.wheelPrecision = 100 / radius;
  99467. // transition to new radius
  99468. if (!this._radiusTransition) {
  99469. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99470. }
  99471. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  99472. _this.stopAllAnimations();
  99473. if (onAnimationEnd) {
  99474. onAnimationEnd();
  99475. }
  99476. if (_this._attachedCamera) {
  99477. _this._attachedCamera.storeState();
  99478. }
  99479. });
  99480. if (animatable) {
  99481. this._animatables.push(animatable);
  99482. }
  99483. };
  99484. /**
  99485. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  99486. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  99487. * frustum width.
  99488. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  99489. * to fully enclose the mesh in the viewing frustum.
  99490. */
  99491. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  99492. var size = maximumWorld.subtract(minimumWorld);
  99493. var boxVectorGlobalDiagonal = size.length();
  99494. var frustumSlope = this._getFrustumSlope();
  99495. // Formula for setting distance
  99496. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  99497. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  99498. // Horizon distance
  99499. var radius = radiusWithoutFraming * this._radiusScale;
  99500. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  99501. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  99502. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  99503. var camera = this._attachedCamera;
  99504. if (!camera) {
  99505. return 0;
  99506. }
  99507. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99508. // Don't exceed the requested limit
  99509. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  99510. }
  99511. // Don't exceed the upper radius limit
  99512. if (camera.upperRadiusLimit) {
  99513. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  99514. }
  99515. return distance;
  99516. };
  99517. /**
  99518. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  99519. * is automatically returned to its default position (expected to be above ground plane).
  99520. */
  99521. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  99522. var _this = this;
  99523. if (this._elevationReturnTime < 0) {
  99524. return;
  99525. }
  99526. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  99527. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  99528. var limitBeta = Math.PI * 0.5;
  99529. // Bring the camera back up if below the ground plane
  99530. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  99531. this._betaIsAnimating = true;
  99532. //Transition to new position
  99533. this.stopAllAnimations();
  99534. if (!this._betaTransition) {
  99535. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99536. }
  99537. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  99538. _this._clearAnimationLocks();
  99539. _this.stopAllAnimations();
  99540. });
  99541. if (animatabe) {
  99542. this._animatables.push(animatabe);
  99543. }
  99544. }
  99545. };
  99546. /**
  99547. * Returns the frustum slope based on the canvas ratio and camera FOV
  99548. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  99549. */
  99550. FramingBehavior.prototype._getFrustumSlope = function () {
  99551. // Calculate the viewport ratio
  99552. // Aspect Ratio is Height/Width.
  99553. var camera = this._attachedCamera;
  99554. if (!camera) {
  99555. return BABYLON.Vector2.Zero();
  99556. }
  99557. var engine = camera.getScene().getEngine();
  99558. var aspectRatio = engine.getAspectRatio(camera);
  99559. // Camera FOV is the vertical field of view (top-bottom) in radians.
  99560. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  99561. var frustumSlopeY = Math.tan(camera.fov / 2);
  99562. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  99563. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  99564. // along the forward vector.
  99565. var frustumSlopeX = frustumSlopeY * aspectRatio;
  99566. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  99567. };
  99568. /**
  99569. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  99570. */
  99571. FramingBehavior.prototype._clearAnimationLocks = function () {
  99572. this._betaIsAnimating = false;
  99573. };
  99574. /**
  99575. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99576. */
  99577. FramingBehavior.prototype._applyUserInteraction = function () {
  99578. if (this.isUserIsMoving) {
  99579. this._lastInteractionTime = BABYLON.Tools.Now;
  99580. this.stopAllAnimations();
  99581. this._clearAnimationLocks();
  99582. }
  99583. };
  99584. /**
  99585. * Stops and removes all animations that have been applied to the camera
  99586. */
  99587. FramingBehavior.prototype.stopAllAnimations = function () {
  99588. if (this._attachedCamera) {
  99589. this._attachedCamera.animations = [];
  99590. }
  99591. while (this._animatables.length) {
  99592. if (this._animatables[0]) {
  99593. this._animatables[0].onAnimationEnd = null;
  99594. this._animatables[0].stop();
  99595. }
  99596. this._animatables.shift();
  99597. }
  99598. };
  99599. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  99600. /**
  99601. * Gets a value indicating if the user is moving the camera
  99602. */
  99603. get: function () {
  99604. if (!this._attachedCamera) {
  99605. return false;
  99606. }
  99607. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99608. this._attachedCamera.inertialBetaOffset !== 0 ||
  99609. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99610. this._attachedCamera.inertialPanningX !== 0 ||
  99611. this._attachedCamera.inertialPanningY !== 0 ||
  99612. this._isPointerDown;
  99613. },
  99614. enumerable: true,
  99615. configurable: true
  99616. });
  99617. /**
  99618. * The easing function used by animations
  99619. */
  99620. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  99621. /**
  99622. * The easing mode used by animations
  99623. */
  99624. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  99625. // Statics
  99626. /**
  99627. * The camera can move all the way towards the mesh.
  99628. */
  99629. FramingBehavior.IgnoreBoundsSizeMode = 0;
  99630. /**
  99631. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  99632. */
  99633. FramingBehavior.FitFrustumSidesMode = 1;
  99634. return FramingBehavior;
  99635. }());
  99636. BABYLON.FramingBehavior = FramingBehavior;
  99637. })(BABYLON || (BABYLON = {}));
  99638. //# sourceMappingURL=babylon.framingBehavior.js.map
  99639. var BABYLON;
  99640. (function (BABYLON) {
  99641. /**
  99642. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  99643. */
  99644. var BouncingBehavior = /** @class */ (function () {
  99645. function BouncingBehavior() {
  99646. /**
  99647. * The duration of the animation, in milliseconds
  99648. */
  99649. this.transitionDuration = 450;
  99650. /**
  99651. * Length of the distance animated by the transition when lower radius is reached
  99652. */
  99653. this.lowerRadiusTransitionRange = 2;
  99654. /**
  99655. * Length of the distance animated by the transition when upper radius is reached
  99656. */
  99657. this.upperRadiusTransitionRange = -2;
  99658. this._autoTransitionRange = false;
  99659. // Animations
  99660. this._radiusIsAnimating = false;
  99661. this._radiusBounceTransition = null;
  99662. this._animatables = new Array();
  99663. }
  99664. Object.defineProperty(BouncingBehavior.prototype, "name", {
  99665. get: function () {
  99666. return "Bouncing";
  99667. },
  99668. enumerable: true,
  99669. configurable: true
  99670. });
  99671. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  99672. /**
  99673. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99674. */
  99675. get: function () {
  99676. return this._autoTransitionRange;
  99677. },
  99678. /**
  99679. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99680. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  99681. */
  99682. set: function (value) {
  99683. var _this = this;
  99684. if (this._autoTransitionRange === value) {
  99685. return;
  99686. }
  99687. this._autoTransitionRange = value;
  99688. var camera = this._attachedCamera;
  99689. if (!camera) {
  99690. return;
  99691. }
  99692. if (value) {
  99693. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99694. if (!mesh) {
  99695. return;
  99696. }
  99697. mesh.computeWorldMatrix(true);
  99698. var diagonal = mesh.getBoundingInfo().diagonalLength;
  99699. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  99700. _this.upperRadiusTransitionRange = diagonal * 0.05;
  99701. });
  99702. }
  99703. else if (this._onMeshTargetChangedObserver) {
  99704. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99705. }
  99706. },
  99707. enumerable: true,
  99708. configurable: true
  99709. });
  99710. BouncingBehavior.prototype.init = function () {
  99711. // Do notihng
  99712. };
  99713. BouncingBehavior.prototype.attach = function (camera) {
  99714. var _this = this;
  99715. this._attachedCamera = camera;
  99716. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99717. if (!_this._attachedCamera) {
  99718. return;
  99719. }
  99720. // Add the bounce animation to the lower radius limit
  99721. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  99722. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  99723. }
  99724. // Add the bounce animation to the upper radius limit
  99725. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  99726. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  99727. }
  99728. });
  99729. };
  99730. BouncingBehavior.prototype.detach = function () {
  99731. if (!this._attachedCamera) {
  99732. return;
  99733. }
  99734. if (this._onAfterCheckInputsObserver) {
  99735. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99736. }
  99737. if (this._onMeshTargetChangedObserver) {
  99738. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99739. }
  99740. this._attachedCamera = null;
  99741. };
  99742. /**
  99743. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  99744. * @param radiusLimit The limit to check against.
  99745. * @return Bool to indicate if at limit.
  99746. */
  99747. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  99748. if (!this._attachedCamera) {
  99749. return false;
  99750. }
  99751. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  99752. return true;
  99753. }
  99754. return false;
  99755. };
  99756. /**
  99757. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  99758. * @param radiusDelta The delta by which to animate to. Can be negative.
  99759. */
  99760. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  99761. var _this = this;
  99762. if (!this._attachedCamera) {
  99763. return;
  99764. }
  99765. if (!this._radiusBounceTransition) {
  99766. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  99767. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  99768. }
  99769. // Prevent zoom until bounce has completed
  99770. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  99771. this._attachedCamera.wheelPrecision = Infinity;
  99772. this._attachedCamera.inertialRadiusOffset = 0;
  99773. // Animate to the radius limit
  99774. this.stopAllAnimations();
  99775. this._radiusIsAnimating = true;
  99776. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  99777. if (animatable) {
  99778. this._animatables.push(animatable);
  99779. }
  99780. };
  99781. /**
  99782. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  99783. */
  99784. BouncingBehavior.prototype._clearAnimationLocks = function () {
  99785. this._radiusIsAnimating = false;
  99786. if (this._attachedCamera) {
  99787. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  99788. }
  99789. };
  99790. /**
  99791. * Stops and removes all animations that have been applied to the camera
  99792. */
  99793. BouncingBehavior.prototype.stopAllAnimations = function () {
  99794. if (this._attachedCamera) {
  99795. this._attachedCamera.animations = [];
  99796. }
  99797. while (this._animatables.length) {
  99798. this._animatables[0].onAnimationEnd = null;
  99799. this._animatables[0].stop();
  99800. this._animatables.shift();
  99801. }
  99802. };
  99803. /**
  99804. * The easing function used by animations
  99805. */
  99806. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  99807. /**
  99808. * The easing mode used by animations
  99809. */
  99810. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  99811. return BouncingBehavior;
  99812. }());
  99813. BABYLON.BouncingBehavior = BouncingBehavior;
  99814. })(BABYLON || (BABYLON = {}));
  99815. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  99816. var BABYLON;
  99817. (function (BABYLON) {
  99818. var AutoRotationBehavior = /** @class */ (function () {
  99819. function AutoRotationBehavior() {
  99820. this._zoomStopsAnimation = false;
  99821. this._idleRotationSpeed = 0.05;
  99822. this._idleRotationWaitTime = 2000;
  99823. this._idleRotationSpinupTime = 2000;
  99824. this._isPointerDown = false;
  99825. this._lastFrameTime = null;
  99826. this._lastInteractionTime = -Infinity;
  99827. this._cameraRotationSpeed = 0;
  99828. this._lastFrameRadius = 0;
  99829. }
  99830. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  99831. get: function () {
  99832. return "AutoRotation";
  99833. },
  99834. enumerable: true,
  99835. configurable: true
  99836. });
  99837. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  99838. /**
  99839. * Gets the flag that indicates if user zooming should stop animation.
  99840. */
  99841. get: function () {
  99842. return this._zoomStopsAnimation;
  99843. },
  99844. /**
  99845. * Sets the flag that indicates if user zooming should stop animation.
  99846. */
  99847. set: function (flag) {
  99848. this._zoomStopsAnimation = flag;
  99849. },
  99850. enumerable: true,
  99851. configurable: true
  99852. });
  99853. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  99854. /**
  99855. * Gets the default speed at which the camera rotates around the model.
  99856. */
  99857. get: function () {
  99858. return this._idleRotationSpeed;
  99859. },
  99860. /**
  99861. * Sets the default speed at which the camera rotates around the model.
  99862. */
  99863. set: function (speed) {
  99864. this._idleRotationSpeed = speed;
  99865. },
  99866. enumerable: true,
  99867. configurable: true
  99868. });
  99869. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  99870. /**
  99871. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  99872. */
  99873. get: function () {
  99874. return this._idleRotationWaitTime;
  99875. },
  99876. /**
  99877. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  99878. */
  99879. set: function (time) {
  99880. this._idleRotationWaitTime = time;
  99881. },
  99882. enumerable: true,
  99883. configurable: true
  99884. });
  99885. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  99886. /**
  99887. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  99888. */
  99889. get: function () {
  99890. return this._idleRotationSpinupTime;
  99891. },
  99892. /**
  99893. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  99894. */
  99895. set: function (time) {
  99896. this._idleRotationSpinupTime = time;
  99897. },
  99898. enumerable: true,
  99899. configurable: true
  99900. });
  99901. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  99902. /**
  99903. * Gets a value indicating if the camera is currently rotating because of this behavior
  99904. */
  99905. get: function () {
  99906. return Math.abs(this._cameraRotationSpeed) > 0;
  99907. },
  99908. enumerable: true,
  99909. configurable: true
  99910. });
  99911. AutoRotationBehavior.prototype.init = function () {
  99912. // Do notihng
  99913. };
  99914. AutoRotationBehavior.prototype.attach = function (camera) {
  99915. var _this = this;
  99916. this._attachedCamera = camera;
  99917. var scene = this._attachedCamera.getScene();
  99918. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99919. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99920. _this._isPointerDown = true;
  99921. return;
  99922. }
  99923. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99924. _this._isPointerDown = false;
  99925. }
  99926. });
  99927. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99928. var now = BABYLON.Tools.Now;
  99929. var dt = 0;
  99930. if (_this._lastFrameTime != null) {
  99931. dt = now - _this._lastFrameTime;
  99932. }
  99933. _this._lastFrameTime = now;
  99934. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99935. _this._applyUserInteraction();
  99936. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  99937. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  99938. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  99939. // Step camera rotation by rotation speed
  99940. if (_this._attachedCamera) {
  99941. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  99942. }
  99943. });
  99944. };
  99945. AutoRotationBehavior.prototype.detach = function () {
  99946. if (!this._attachedCamera) {
  99947. return;
  99948. }
  99949. var scene = this._attachedCamera.getScene();
  99950. if (this._onPrePointerObservableObserver) {
  99951. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99952. }
  99953. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99954. this._attachedCamera = null;
  99955. };
  99956. /**
  99957. * Returns true if user is scrolling.
  99958. * @return true if user is scrolling.
  99959. */
  99960. AutoRotationBehavior.prototype._userIsZooming = function () {
  99961. if (!this._attachedCamera) {
  99962. return false;
  99963. }
  99964. return this._attachedCamera.inertialRadiusOffset !== 0;
  99965. };
  99966. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  99967. if (!this._attachedCamera) {
  99968. return false;
  99969. }
  99970. var zoomHasHitLimit = false;
  99971. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  99972. zoomHasHitLimit = true;
  99973. }
  99974. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  99975. this._lastFrameRadius = this._attachedCamera.radius;
  99976. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  99977. };
  99978. /**
  99979. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99980. */
  99981. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  99982. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  99983. this._lastInteractionTime = BABYLON.Tools.Now;
  99984. }
  99985. };
  99986. // Tools
  99987. AutoRotationBehavior.prototype._userIsMoving = function () {
  99988. if (!this._attachedCamera) {
  99989. return false;
  99990. }
  99991. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99992. this._attachedCamera.inertialBetaOffset !== 0 ||
  99993. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99994. this._attachedCamera.inertialPanningX !== 0 ||
  99995. this._attachedCamera.inertialPanningY !== 0 ||
  99996. this._isPointerDown;
  99997. };
  99998. return AutoRotationBehavior;
  99999. }());
  100000. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  100001. })(BABYLON || (BABYLON = {}));
  100002. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  100003. var BABYLON;
  100004. (function (BABYLON) {
  100005. var NullEngineOptions = /** @class */ (function () {
  100006. function NullEngineOptions() {
  100007. this.renderWidth = 512;
  100008. this.renderHeight = 256;
  100009. this.textureSize = 512;
  100010. this.deterministicLockstep = false;
  100011. this.lockstepMaxSteps = 4;
  100012. }
  100013. return NullEngineOptions;
  100014. }());
  100015. BABYLON.NullEngineOptions = NullEngineOptions;
  100016. /**
  100017. * The null engine class provides support for headless version of babylon.js.
  100018. * This can be used in server side scenario or for testing purposes
  100019. */
  100020. var NullEngine = /** @class */ (function (_super) {
  100021. __extends(NullEngine, _super);
  100022. function NullEngine(options) {
  100023. if (options === void 0) { options = new NullEngineOptions(); }
  100024. var _this = _super.call(this, null) || this;
  100025. if (options.deterministicLockstep === undefined) {
  100026. options.deterministicLockstep = false;
  100027. }
  100028. if (options.lockstepMaxSteps === undefined) {
  100029. options.lockstepMaxSteps = 4;
  100030. }
  100031. _this._options = options;
  100032. // Init caps
  100033. // We consider we are on a webgl1 capable device
  100034. _this._caps = new BABYLON.EngineCapabilities();
  100035. _this._caps.maxTexturesImageUnits = 16;
  100036. _this._caps.maxVertexTextureImageUnits = 16;
  100037. _this._caps.maxTextureSize = 512;
  100038. _this._caps.maxCubemapTextureSize = 512;
  100039. _this._caps.maxRenderTextureSize = 512;
  100040. _this._caps.maxVertexAttribs = 16;
  100041. _this._caps.maxVaryingVectors = 16;
  100042. _this._caps.maxFragmentUniformVectors = 16;
  100043. _this._caps.maxVertexUniformVectors = 16;
  100044. // Extensions
  100045. _this._caps.standardDerivatives = false;
  100046. _this._caps.astc = null;
  100047. _this._caps.s3tc = null;
  100048. _this._caps.pvrtc = null;
  100049. _this._caps.etc1 = null;
  100050. _this._caps.etc2 = null;
  100051. _this._caps.textureAnisotropicFilterExtension = null;
  100052. _this._caps.maxAnisotropy = 0;
  100053. _this._caps.uintIndices = false;
  100054. _this._caps.fragmentDepthSupported = false;
  100055. _this._caps.highPrecisionShaderSupported = true;
  100056. _this._caps.colorBufferFloat = false;
  100057. _this._caps.textureFloat = false;
  100058. _this._caps.textureFloatLinearFiltering = false;
  100059. _this._caps.textureFloatRender = false;
  100060. _this._caps.textureHalfFloat = false;
  100061. _this._caps.textureHalfFloatLinearFiltering = false;
  100062. _this._caps.textureHalfFloatRender = false;
  100063. _this._caps.textureLOD = false;
  100064. _this._caps.drawBuffersExtension = false;
  100065. _this._caps.depthTextureExtension = false;
  100066. _this._caps.vertexArrayObject = false;
  100067. _this._caps.instancedArrays = false;
  100068. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  100069. // Wrappers
  100070. if (typeof URL === "undefined") {
  100071. URL = {
  100072. createObjectURL: function () { },
  100073. revokeObjectURL: function () { }
  100074. };
  100075. }
  100076. if (typeof Blob === "undefined") {
  100077. Blob = function () { };
  100078. }
  100079. return _this;
  100080. }
  100081. NullEngine.prototype.isDeterministicLockStep = function () {
  100082. return this._options.deterministicLockstep;
  100083. };
  100084. NullEngine.prototype.getLockstepMaxSteps = function () {
  100085. return this._options.lockstepMaxSteps;
  100086. };
  100087. NullEngine.prototype.getHardwareScalingLevel = function () {
  100088. return 1.0;
  100089. };
  100090. NullEngine.prototype.createVertexBuffer = function (vertices) {
  100091. return {
  100092. capacity: 0,
  100093. references: 1,
  100094. is32Bits: false
  100095. };
  100096. };
  100097. NullEngine.prototype.createIndexBuffer = function (indices) {
  100098. return {
  100099. capacity: 0,
  100100. references: 1,
  100101. is32Bits: false
  100102. };
  100103. };
  100104. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  100105. if (stencil === void 0) { stencil = false; }
  100106. };
  100107. NullEngine.prototype.getRenderWidth = function (useScreen) {
  100108. if (useScreen === void 0) { useScreen = false; }
  100109. if (!useScreen && this._currentRenderTarget) {
  100110. return this._currentRenderTarget.width;
  100111. }
  100112. return this._options.renderWidth;
  100113. };
  100114. NullEngine.prototype.getRenderHeight = function (useScreen) {
  100115. if (useScreen === void 0) { useScreen = false; }
  100116. if (!useScreen && this._currentRenderTarget) {
  100117. return this._currentRenderTarget.height;
  100118. }
  100119. return this._options.renderHeight;
  100120. };
  100121. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  100122. this._cachedViewport = viewport;
  100123. };
  100124. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  100125. return {
  100126. transformFeedback: null,
  100127. __SPECTOR_rebuildProgram: null
  100128. };
  100129. };
  100130. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  100131. return [];
  100132. };
  100133. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  100134. return [];
  100135. };
  100136. NullEngine.prototype.bindSamplers = function (effect) {
  100137. this._currentEffect = null;
  100138. };
  100139. NullEngine.prototype.enableEffect = function (effect) {
  100140. this._currentEffect = effect;
  100141. if (effect.onBind) {
  100142. effect.onBind(effect);
  100143. }
  100144. effect.onBindObservable.notifyObservers(effect);
  100145. };
  100146. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  100147. if (zOffset === void 0) { zOffset = 0; }
  100148. if (reverseSide === void 0) { reverseSide = false; }
  100149. };
  100150. NullEngine.prototype.setIntArray = function (uniform, array) {
  100151. };
  100152. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  100153. };
  100154. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  100155. };
  100156. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  100157. };
  100158. NullEngine.prototype.setFloatArray = function (uniform, array) {
  100159. };
  100160. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  100161. };
  100162. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  100163. };
  100164. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  100165. };
  100166. NullEngine.prototype.setArray = function (uniform, array) {
  100167. };
  100168. NullEngine.prototype.setArray2 = function (uniform, array) {
  100169. };
  100170. NullEngine.prototype.setArray3 = function (uniform, array) {
  100171. };
  100172. NullEngine.prototype.setArray4 = function (uniform, array) {
  100173. };
  100174. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  100175. };
  100176. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  100177. };
  100178. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  100179. };
  100180. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  100181. };
  100182. NullEngine.prototype.setFloat = function (uniform, value) {
  100183. };
  100184. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  100185. };
  100186. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  100187. };
  100188. NullEngine.prototype.setBool = function (uniform, bool) {
  100189. };
  100190. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  100191. };
  100192. NullEngine.prototype.setColor3 = function (uniform, color3) {
  100193. };
  100194. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  100195. };
  100196. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  100197. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  100198. if (this._alphaMode === mode) {
  100199. return;
  100200. }
  100201. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  100202. if (!noDepthWriteChange) {
  100203. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  100204. }
  100205. this._alphaMode = mode;
  100206. };
  100207. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  100208. };
  100209. NullEngine.prototype.wipeCaches = function (bruteForce) {
  100210. if (this.preventCacheWipeBetweenFrames) {
  100211. return;
  100212. }
  100213. this.resetTextureCache();
  100214. this._currentEffect = null;
  100215. if (bruteForce) {
  100216. this._currentProgram = null;
  100217. this._stencilState.reset();
  100218. this._depthCullingState.reset();
  100219. this._alphaState.reset();
  100220. }
  100221. this._cachedVertexBuffers = null;
  100222. this._cachedIndexBuffer = null;
  100223. this._cachedEffectForVertexBuffers = null;
  100224. };
  100225. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  100226. };
  100227. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  100228. };
  100229. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  100230. };
  100231. NullEngine.prototype._createTexture = function () {
  100232. return {};
  100233. };
  100234. NullEngine.prototype._releaseTexture = function (texture) {
  100235. };
  100236. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  100237. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100238. if (onLoad === void 0) { onLoad = null; }
  100239. if (onError === void 0) { onError = null; }
  100240. if (buffer === void 0) { buffer = null; }
  100241. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  100242. var url = String(urlArg);
  100243. texture.url = url;
  100244. texture.generateMipMaps = !noMipmap;
  100245. texture.samplingMode = samplingMode;
  100246. texture.invertY = invertY;
  100247. texture.baseWidth = this._options.textureSize;
  100248. texture.baseHeight = this._options.textureSize;
  100249. texture.width = this._options.textureSize;
  100250. texture.height = this._options.textureSize;
  100251. if (format) {
  100252. texture.format = format;
  100253. }
  100254. texture.isReady = true;
  100255. if (onLoad) {
  100256. onLoad();
  100257. }
  100258. this._internalTexturesCache.push(texture);
  100259. return texture;
  100260. };
  100261. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  100262. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  100263. if (options !== undefined && typeof options === "object") {
  100264. fullOptions.generateMipMaps = options.generateMipMaps;
  100265. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  100266. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  100267. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  100268. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  100269. }
  100270. else {
  100271. fullOptions.generateMipMaps = options;
  100272. fullOptions.generateDepthBuffer = true;
  100273. fullOptions.generateStencilBuffer = false;
  100274. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100275. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100276. }
  100277. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  100278. var width = size.width || size;
  100279. var height = size.height || size;
  100280. texture._depthStencilBuffer = {};
  100281. texture._framebuffer = {};
  100282. texture.baseWidth = width;
  100283. texture.baseHeight = height;
  100284. texture.width = width;
  100285. texture.height = height;
  100286. texture.isReady = true;
  100287. texture.samples = 1;
  100288. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  100289. texture.samplingMode = fullOptions.samplingMode;
  100290. texture.type = fullOptions.type;
  100291. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  100292. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  100293. this._internalTexturesCache.push(texture);
  100294. return texture;
  100295. };
  100296. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  100297. texture.samplingMode = samplingMode;
  100298. };
  100299. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  100300. if (this._currentRenderTarget) {
  100301. this.unBindFramebuffer(this._currentRenderTarget);
  100302. }
  100303. this._currentRenderTarget = texture;
  100304. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  100305. if (this._cachedViewport && !forceFullscreenViewport) {
  100306. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  100307. }
  100308. };
  100309. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  100310. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  100311. this._currentRenderTarget = null;
  100312. if (onBeforeUnbind) {
  100313. if (texture._MSAAFramebuffer) {
  100314. this._currentFramebuffer = texture._framebuffer;
  100315. }
  100316. onBeforeUnbind();
  100317. }
  100318. this._currentFramebuffer = null;
  100319. };
  100320. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  100321. var vbo = {
  100322. capacity: 1,
  100323. references: 1,
  100324. is32Bits: false
  100325. };
  100326. return vbo;
  100327. };
  100328. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  100329. if (premulAlpha === void 0) { premulAlpha = false; }
  100330. };
  100331. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  100332. if (offset === void 0) { offset = 0; }
  100333. };
  100334. /**
  100335. * Updates a dynamic vertex buffer.
  100336. * @param vertexBuffer the vertex buffer to update
  100337. * @param data the data used to update the vertex buffer
  100338. * @param byteOffset the byte offset of the data (optional)
  100339. * @param byteLength the byte length of the data (optional)
  100340. */
  100341. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  100342. };
  100343. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  100344. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  100345. this._boundTexturesCache[this._activeChannel] = texture;
  100346. return true;
  100347. }
  100348. return false;
  100349. };
  100350. NullEngine.prototype._bindTexture = function (channel, texture) {
  100351. if (channel < 0) {
  100352. return;
  100353. }
  100354. this._bindTextureDirectly(0, texture);
  100355. };
  100356. NullEngine.prototype._releaseBuffer = function (buffer) {
  100357. buffer.references--;
  100358. if (buffer.references === 0) {
  100359. return true;
  100360. }
  100361. return false;
  100362. };
  100363. NullEngine.prototype.releaseEffects = function () {
  100364. };
  100365. NullEngine.prototype.displayLoadingUI = function () {
  100366. };
  100367. NullEngine.prototype.hideLoadingUI = function () {
  100368. };
  100369. return NullEngine;
  100370. }(BABYLON.Engine));
  100371. BABYLON.NullEngine = NullEngine;
  100372. })(BABYLON || (BABYLON = {}));
  100373. //# sourceMappingURL=babylon.nullEngine.js.map
  100374. var BABYLON;
  100375. (function (BABYLON) {
  100376. /**
  100377. * This class can be used to get instrumentation data from a Babylon engine
  100378. */
  100379. var EngineInstrumentation = /** @class */ (function () {
  100380. function EngineInstrumentation(engine) {
  100381. this.engine = engine;
  100382. this._captureGPUFrameTime = false;
  100383. this._gpuFrameTime = new BABYLON.PerfCounter();
  100384. this._captureShaderCompilationTime = false;
  100385. this._shaderCompilationTime = new BABYLON.PerfCounter();
  100386. // Observers
  100387. this._onBeginFrameObserver = null;
  100388. this._onEndFrameObserver = null;
  100389. this._onBeforeShaderCompilationObserver = null;
  100390. this._onAfterShaderCompilationObserver = null;
  100391. }
  100392. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  100393. // Properties
  100394. /**
  100395. * Gets the perf counter used for GPU frame time
  100396. */
  100397. get: function () {
  100398. return this._gpuFrameTime;
  100399. },
  100400. enumerable: true,
  100401. configurable: true
  100402. });
  100403. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  100404. /**
  100405. * Gets the GPU frame time capture status
  100406. */
  100407. get: function () {
  100408. return this._captureGPUFrameTime;
  100409. },
  100410. /**
  100411. * Enable or disable the GPU frame time capture
  100412. */
  100413. set: function (value) {
  100414. var _this = this;
  100415. if (value === this._captureGPUFrameTime) {
  100416. return;
  100417. }
  100418. this._captureGPUFrameTime = value;
  100419. if (value) {
  100420. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  100421. if (!_this._gpuFrameTimeToken) {
  100422. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  100423. }
  100424. });
  100425. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  100426. if (!_this._gpuFrameTimeToken) {
  100427. return;
  100428. }
  100429. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  100430. if (time > -1) {
  100431. _this._gpuFrameTimeToken = null;
  100432. _this._gpuFrameTime.fetchNewFrame();
  100433. _this._gpuFrameTime.addCount(time, true);
  100434. }
  100435. });
  100436. }
  100437. else {
  100438. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100439. this._onBeginFrameObserver = null;
  100440. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100441. this._onEndFrameObserver = null;
  100442. }
  100443. },
  100444. enumerable: true,
  100445. configurable: true
  100446. });
  100447. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  100448. /**
  100449. * Gets the perf counter used for shader compilation time
  100450. */
  100451. get: function () {
  100452. return this._shaderCompilationTime;
  100453. },
  100454. enumerable: true,
  100455. configurable: true
  100456. });
  100457. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  100458. /**
  100459. * Gets the shader compilation time capture status
  100460. */
  100461. get: function () {
  100462. return this._captureShaderCompilationTime;
  100463. },
  100464. /**
  100465. * Enable or disable the shader compilation time capture
  100466. */
  100467. set: function (value) {
  100468. var _this = this;
  100469. if (value === this._captureShaderCompilationTime) {
  100470. return;
  100471. }
  100472. this._captureShaderCompilationTime = value;
  100473. if (value) {
  100474. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  100475. _this._shaderCompilationTime.fetchNewFrame();
  100476. _this._shaderCompilationTime.beginMonitoring();
  100477. });
  100478. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  100479. _this._shaderCompilationTime.endMonitoring();
  100480. });
  100481. }
  100482. else {
  100483. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100484. this._onBeforeShaderCompilationObserver = null;
  100485. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100486. this._onAfterShaderCompilationObserver = null;
  100487. }
  100488. },
  100489. enumerable: true,
  100490. configurable: true
  100491. });
  100492. EngineInstrumentation.prototype.dispose = function () {
  100493. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100494. this._onBeginFrameObserver = null;
  100495. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100496. this._onEndFrameObserver = null;
  100497. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100498. this._onBeforeShaderCompilationObserver = null;
  100499. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100500. this._onAfterShaderCompilationObserver = null;
  100501. this.engine = null;
  100502. };
  100503. return EngineInstrumentation;
  100504. }());
  100505. BABYLON.EngineInstrumentation = EngineInstrumentation;
  100506. })(BABYLON || (BABYLON = {}));
  100507. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  100508. var BABYLON;
  100509. (function (BABYLON) {
  100510. /**
  100511. * This class can be used to get instrumentation data from a Babylon engine
  100512. */
  100513. var SceneInstrumentation = /** @class */ (function () {
  100514. function SceneInstrumentation(scene) {
  100515. var _this = this;
  100516. this.scene = scene;
  100517. this._captureActiveMeshesEvaluationTime = false;
  100518. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  100519. this._captureRenderTargetsRenderTime = false;
  100520. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  100521. this._captureFrameTime = false;
  100522. this._frameTime = new BABYLON.PerfCounter();
  100523. this._captureRenderTime = false;
  100524. this._renderTime = new BABYLON.PerfCounter();
  100525. this._captureInterFrameTime = false;
  100526. this._interFrameTime = new BABYLON.PerfCounter();
  100527. this._captureParticlesRenderTime = false;
  100528. this._particlesRenderTime = new BABYLON.PerfCounter();
  100529. this._captureSpritesRenderTime = false;
  100530. this._spritesRenderTime = new BABYLON.PerfCounter();
  100531. this._capturePhysicsTime = false;
  100532. this._physicsTime = new BABYLON.PerfCounter();
  100533. this._captureAnimationsTime = false;
  100534. this._animationsTime = new BABYLON.PerfCounter();
  100535. this._captureCameraRenderTime = false;
  100536. this._cameraRenderTime = new BABYLON.PerfCounter();
  100537. // Observers
  100538. this._onBeforeActiveMeshesEvaluationObserver = null;
  100539. this._onAfterActiveMeshesEvaluationObserver = null;
  100540. this._onBeforeRenderTargetsRenderObserver = null;
  100541. this._onAfterRenderTargetsRenderObserver = null;
  100542. this._onAfterRenderObserver = null;
  100543. this._onBeforeDrawPhaseObserver = null;
  100544. this._onAfterDrawPhaseObserver = null;
  100545. this._onBeforeAnimationsObserver = null;
  100546. this._onBeforeParticlesRenderingObserver = null;
  100547. this._onAfterParticlesRenderingObserver = null;
  100548. this._onBeforeSpritesRenderingObserver = null;
  100549. this._onAfterSpritesRenderingObserver = null;
  100550. this._onBeforePhysicsObserver = null;
  100551. this._onAfterPhysicsObserver = null;
  100552. this._onAfterAnimationsObserver = null;
  100553. this._onBeforeCameraRenderObserver = null;
  100554. this._onAfterCameraRenderObserver = null;
  100555. // Before render
  100556. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  100557. if (_this._captureActiveMeshesEvaluationTime) {
  100558. _this._activeMeshesEvaluationTime.fetchNewFrame();
  100559. }
  100560. if (_this._captureRenderTargetsRenderTime) {
  100561. _this._renderTargetsRenderTime.fetchNewFrame();
  100562. }
  100563. if (_this._captureFrameTime) {
  100564. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  100565. _this._frameTime.beginMonitoring();
  100566. }
  100567. if (_this._captureInterFrameTime) {
  100568. _this._interFrameTime.endMonitoring();
  100569. }
  100570. if (_this._captureParticlesRenderTime) {
  100571. _this._particlesRenderTime.fetchNewFrame();
  100572. }
  100573. if (_this._captureSpritesRenderTime) {
  100574. _this._spritesRenderTime.fetchNewFrame();
  100575. }
  100576. if (_this._captureAnimationsTime) {
  100577. _this._animationsTime.beginMonitoring();
  100578. }
  100579. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  100580. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  100581. });
  100582. // After render
  100583. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  100584. if (_this._captureFrameTime) {
  100585. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  100586. _this._frameTime.endMonitoring();
  100587. }
  100588. if (_this._captureRenderTime) {
  100589. _this._renderTime.endMonitoring(false);
  100590. }
  100591. if (_this._captureInterFrameTime) {
  100592. _this._interFrameTime.beginMonitoring();
  100593. }
  100594. });
  100595. }
  100596. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  100597. // Properties
  100598. /**
  100599. * Gets the perf counter used for active meshes evaluation time
  100600. */
  100601. get: function () {
  100602. return this._activeMeshesEvaluationTime;
  100603. },
  100604. enumerable: true,
  100605. configurable: true
  100606. });
  100607. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  100608. /**
  100609. * Gets the active meshes evaluation time capture status
  100610. */
  100611. get: function () {
  100612. return this._captureActiveMeshesEvaluationTime;
  100613. },
  100614. /**
  100615. * Enable or disable the active meshes evaluation time capture
  100616. */
  100617. set: function (value) {
  100618. var _this = this;
  100619. if (value === this._captureActiveMeshesEvaluationTime) {
  100620. return;
  100621. }
  100622. this._captureActiveMeshesEvaluationTime = value;
  100623. if (value) {
  100624. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  100625. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  100626. _this._activeMeshesEvaluationTime.beginMonitoring();
  100627. });
  100628. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  100629. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  100630. _this._activeMeshesEvaluationTime.endMonitoring();
  100631. });
  100632. }
  100633. else {
  100634. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100635. this._onBeforeActiveMeshesEvaluationObserver = null;
  100636. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100637. this._onAfterActiveMeshesEvaluationObserver = null;
  100638. }
  100639. },
  100640. enumerable: true,
  100641. configurable: true
  100642. });
  100643. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  100644. /**
  100645. * Gets the perf counter used for render targets render time
  100646. */
  100647. get: function () {
  100648. return this._renderTargetsRenderTime;
  100649. },
  100650. enumerable: true,
  100651. configurable: true
  100652. });
  100653. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  100654. /**
  100655. * Gets the render targets render time capture status
  100656. */
  100657. get: function () {
  100658. return this._captureRenderTargetsRenderTime;
  100659. },
  100660. /**
  100661. * Enable or disable the render targets render time capture
  100662. */
  100663. set: function (value) {
  100664. var _this = this;
  100665. if (value === this._captureRenderTargetsRenderTime) {
  100666. return;
  100667. }
  100668. this._captureRenderTargetsRenderTime = value;
  100669. if (value) {
  100670. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  100671. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  100672. _this._renderTargetsRenderTime.beginMonitoring();
  100673. });
  100674. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  100675. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  100676. _this._renderTargetsRenderTime.endMonitoring(false);
  100677. });
  100678. }
  100679. else {
  100680. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100681. this._onBeforeRenderTargetsRenderObserver = null;
  100682. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100683. this._onAfterRenderTargetsRenderObserver = null;
  100684. }
  100685. },
  100686. enumerable: true,
  100687. configurable: true
  100688. });
  100689. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  100690. /**
  100691. * Gets the perf counter used for particles render time
  100692. */
  100693. get: function () {
  100694. return this._particlesRenderTime;
  100695. },
  100696. enumerable: true,
  100697. configurable: true
  100698. });
  100699. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  100700. /**
  100701. * Gets the particles render time capture status
  100702. */
  100703. get: function () {
  100704. return this._captureParticlesRenderTime;
  100705. },
  100706. /**
  100707. * Enable or disable the particles render time capture
  100708. */
  100709. set: function (value) {
  100710. var _this = this;
  100711. if (value === this._captureParticlesRenderTime) {
  100712. return;
  100713. }
  100714. this._captureParticlesRenderTime = value;
  100715. if (value) {
  100716. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  100717. BABYLON.Tools.StartPerformanceCounter("Particles");
  100718. _this._particlesRenderTime.beginMonitoring();
  100719. });
  100720. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  100721. BABYLON.Tools.EndPerformanceCounter("Particles");
  100722. _this._particlesRenderTime.endMonitoring(false);
  100723. });
  100724. }
  100725. else {
  100726. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100727. this._onBeforeParticlesRenderingObserver = null;
  100728. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100729. this._onAfterParticlesRenderingObserver = null;
  100730. }
  100731. },
  100732. enumerable: true,
  100733. configurable: true
  100734. });
  100735. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  100736. /**
  100737. * Gets the perf counter used for sprites render time
  100738. */
  100739. get: function () {
  100740. return this._spritesRenderTime;
  100741. },
  100742. enumerable: true,
  100743. configurable: true
  100744. });
  100745. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  100746. /**
  100747. * Gets the sprites render time capture status
  100748. */
  100749. get: function () {
  100750. return this._captureSpritesRenderTime;
  100751. },
  100752. /**
  100753. * Enable or disable the sprites render time capture
  100754. */
  100755. set: function (value) {
  100756. var _this = this;
  100757. if (value === this._captureSpritesRenderTime) {
  100758. return;
  100759. }
  100760. this._captureSpritesRenderTime = value;
  100761. if (value) {
  100762. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  100763. BABYLON.Tools.StartPerformanceCounter("Sprites");
  100764. _this._spritesRenderTime.beginMonitoring();
  100765. });
  100766. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  100767. BABYLON.Tools.EndPerformanceCounter("Sprites");
  100768. _this._spritesRenderTime.endMonitoring(false);
  100769. });
  100770. }
  100771. else {
  100772. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  100773. this._onBeforeSpritesRenderingObserver = null;
  100774. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  100775. this._onAfterSpritesRenderingObserver = null;
  100776. }
  100777. },
  100778. enumerable: true,
  100779. configurable: true
  100780. });
  100781. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  100782. /**
  100783. * Gets the perf counter used for physics time
  100784. */
  100785. get: function () {
  100786. return this._physicsTime;
  100787. },
  100788. enumerable: true,
  100789. configurable: true
  100790. });
  100791. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  100792. /**
  100793. * Gets the physics time capture status
  100794. */
  100795. get: function () {
  100796. return this._capturePhysicsTime;
  100797. },
  100798. /**
  100799. * Enable or disable the physics time capture
  100800. */
  100801. set: function (value) {
  100802. var _this = this;
  100803. if (value === this._capturePhysicsTime) {
  100804. return;
  100805. }
  100806. this._capturePhysicsTime = value;
  100807. if (value) {
  100808. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  100809. BABYLON.Tools.StartPerformanceCounter("Physics");
  100810. _this._physicsTime.beginMonitoring();
  100811. });
  100812. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  100813. BABYLON.Tools.EndPerformanceCounter("Physics");
  100814. _this._physicsTime.endMonitoring();
  100815. });
  100816. }
  100817. else {
  100818. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  100819. this._onBeforePhysicsObserver = null;
  100820. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  100821. this._onAfterPhysicsObserver = null;
  100822. }
  100823. },
  100824. enumerable: true,
  100825. configurable: true
  100826. });
  100827. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  100828. /**
  100829. * Gets the perf counter used for animations time
  100830. */
  100831. get: function () {
  100832. return this._animationsTime;
  100833. },
  100834. enumerable: true,
  100835. configurable: true
  100836. });
  100837. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  100838. /**
  100839. * Gets the animations time capture status
  100840. */
  100841. get: function () {
  100842. return this._captureAnimationsTime;
  100843. },
  100844. /**
  100845. * Enable or disable the animations time capture
  100846. */
  100847. set: function (value) {
  100848. var _this = this;
  100849. if (value === this._captureAnimationsTime) {
  100850. return;
  100851. }
  100852. this._captureAnimationsTime = value;
  100853. if (value) {
  100854. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  100855. _this._animationsTime.endMonitoring();
  100856. });
  100857. }
  100858. else {
  100859. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  100860. this._onAfterAnimationsObserver = null;
  100861. }
  100862. },
  100863. enumerable: true,
  100864. configurable: true
  100865. });
  100866. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  100867. /**
  100868. * Gets the perf counter used for frame time capture
  100869. */
  100870. get: function () {
  100871. return this._frameTime;
  100872. },
  100873. enumerable: true,
  100874. configurable: true
  100875. });
  100876. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  100877. /**
  100878. * Gets the frame time capture status
  100879. */
  100880. get: function () {
  100881. return this._captureFrameTime;
  100882. },
  100883. /**
  100884. * Enable or disable the frame time capture
  100885. */
  100886. set: function (value) {
  100887. this._captureFrameTime = value;
  100888. },
  100889. enumerable: true,
  100890. configurable: true
  100891. });
  100892. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  100893. /**
  100894. * Gets the perf counter used for inter-frames time capture
  100895. */
  100896. get: function () {
  100897. return this._interFrameTime;
  100898. },
  100899. enumerable: true,
  100900. configurable: true
  100901. });
  100902. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  100903. /**
  100904. * Gets the inter-frames time capture status
  100905. */
  100906. get: function () {
  100907. return this._captureInterFrameTime;
  100908. },
  100909. /**
  100910. * Enable or disable the inter-frames time capture
  100911. */
  100912. set: function (value) {
  100913. this._captureInterFrameTime = value;
  100914. },
  100915. enumerable: true,
  100916. configurable: true
  100917. });
  100918. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  100919. /**
  100920. * Gets the perf counter used for render time capture
  100921. */
  100922. get: function () {
  100923. return this._renderTime;
  100924. },
  100925. enumerable: true,
  100926. configurable: true
  100927. });
  100928. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  100929. /**
  100930. * Gets the render time capture status
  100931. */
  100932. get: function () {
  100933. return this._captureRenderTime;
  100934. },
  100935. /**
  100936. * Enable or disable the render time capture
  100937. */
  100938. set: function (value) {
  100939. var _this = this;
  100940. if (value === this._captureRenderTime) {
  100941. return;
  100942. }
  100943. this._captureRenderTime = value;
  100944. if (value) {
  100945. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  100946. _this._renderTime.beginMonitoring();
  100947. BABYLON.Tools.StartPerformanceCounter("Main render");
  100948. });
  100949. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  100950. _this._renderTime.endMonitoring(false);
  100951. BABYLON.Tools.EndPerformanceCounter("Main render");
  100952. });
  100953. }
  100954. else {
  100955. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100956. this._onBeforeDrawPhaseObserver = null;
  100957. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100958. this._onAfterDrawPhaseObserver = null;
  100959. }
  100960. },
  100961. enumerable: true,
  100962. configurable: true
  100963. });
  100964. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  100965. /**
  100966. * Gets the perf counter used for camera render time capture
  100967. */
  100968. get: function () {
  100969. return this._cameraRenderTime;
  100970. },
  100971. enumerable: true,
  100972. configurable: true
  100973. });
  100974. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  100975. /**
  100976. * Gets the camera render time capture status
  100977. */
  100978. get: function () {
  100979. return this._captureCameraRenderTime;
  100980. },
  100981. /**
  100982. * Enable or disable the camera render time capture
  100983. */
  100984. set: function (value) {
  100985. var _this = this;
  100986. if (value === this._captureCameraRenderTime) {
  100987. return;
  100988. }
  100989. this._captureCameraRenderTime = value;
  100990. if (value) {
  100991. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  100992. _this._cameraRenderTime.beginMonitoring();
  100993. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  100994. });
  100995. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  100996. _this._cameraRenderTime.endMonitoring(false);
  100997. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  100998. });
  100999. }
  101000. else {
  101001. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101002. this._onBeforeCameraRenderObserver = null;
  101003. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101004. this._onAfterCameraRenderObserver = null;
  101005. }
  101006. },
  101007. enumerable: true,
  101008. configurable: true
  101009. });
  101010. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  101011. /**
  101012. * Gets the perf counter used for draw calls
  101013. */
  101014. get: function () {
  101015. return this.scene.getEngine()._drawCalls;
  101016. },
  101017. enumerable: true,
  101018. configurable: true
  101019. });
  101020. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  101021. /**
  101022. * Gets the perf counter used for texture collisions
  101023. */
  101024. get: function () {
  101025. return this.scene.getEngine()._textureCollisions;
  101026. },
  101027. enumerable: true,
  101028. configurable: true
  101029. });
  101030. SceneInstrumentation.prototype.dispose = function () {
  101031. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  101032. this._onAfterRenderObserver = null;
  101033. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101034. this._onBeforeActiveMeshesEvaluationObserver = null;
  101035. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101036. this._onAfterActiveMeshesEvaluationObserver = null;
  101037. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101038. this._onBeforeRenderTargetsRenderObserver = null;
  101039. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101040. this._onAfterRenderTargetsRenderObserver = null;
  101041. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  101042. this._onBeforeAnimationsObserver = null;
  101043. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101044. this._onBeforeParticlesRenderingObserver = null;
  101045. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101046. this._onAfterParticlesRenderingObserver = null;
  101047. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101048. this._onBeforeSpritesRenderingObserver = null;
  101049. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101050. this._onAfterSpritesRenderingObserver = null;
  101051. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101052. this._onBeforeDrawPhaseObserver = null;
  101053. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101054. this._onAfterDrawPhaseObserver = null;
  101055. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101056. this._onBeforePhysicsObserver = null;
  101057. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101058. this._onAfterPhysicsObserver = null;
  101059. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101060. this._onAfterAnimationsObserver = null;
  101061. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101062. this._onBeforeCameraRenderObserver = null;
  101063. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101064. this._onAfterCameraRenderObserver = null;
  101065. this.scene = null;
  101066. };
  101067. return SceneInstrumentation;
  101068. }());
  101069. BABYLON.SceneInstrumentation = SceneInstrumentation;
  101070. })(BABYLON || (BABYLON = {}));
  101071. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  101072. var BABYLON;
  101073. (function (BABYLON) {
  101074. /**
  101075. * @hidden
  101076. **/
  101077. var _TimeToken = /** @class */ (function () {
  101078. function _TimeToken() {
  101079. this._timeElapsedQueryEnded = false;
  101080. }
  101081. return _TimeToken;
  101082. }());
  101083. BABYLON._TimeToken = _TimeToken;
  101084. })(BABYLON || (BABYLON = {}));
  101085. //# sourceMappingURL=babylon.timeToken.js.map
  101086. var BABYLON;
  101087. (function (BABYLON) {
  101088. /**
  101089. * Background material defines definition.
  101090. * @hidden Mainly internal Use
  101091. */
  101092. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  101093. __extends(BackgroundMaterialDefines, _super);
  101094. /**
  101095. * Constructor of the defines.
  101096. */
  101097. function BackgroundMaterialDefines() {
  101098. var _this = _super.call(this) || this;
  101099. /**
  101100. * True if the diffuse texture is in use.
  101101. */
  101102. _this.DIFFUSE = false;
  101103. /**
  101104. * The direct UV channel to use.
  101105. */
  101106. _this.DIFFUSEDIRECTUV = 0;
  101107. /**
  101108. * True if the diffuse texture is in gamma space.
  101109. */
  101110. _this.GAMMADIFFUSE = false;
  101111. /**
  101112. * True if the diffuse texture has opacity in the alpha channel.
  101113. */
  101114. _this.DIFFUSEHASALPHA = false;
  101115. /**
  101116. * True if you want the material to fade to transparent at grazing angle.
  101117. */
  101118. _this.OPACITYFRESNEL = false;
  101119. /**
  101120. * True if an extra blur needs to be added in the reflection.
  101121. */
  101122. _this.REFLECTIONBLUR = false;
  101123. /**
  101124. * True if you want the material to fade to reflection at grazing angle.
  101125. */
  101126. _this.REFLECTIONFRESNEL = false;
  101127. /**
  101128. * True if you want the material to falloff as far as you move away from the scene center.
  101129. */
  101130. _this.REFLECTIONFALLOFF = false;
  101131. /**
  101132. * False if the current Webgl implementation does not support the texture lod extension.
  101133. */
  101134. _this.TEXTURELODSUPPORT = false;
  101135. /**
  101136. * True to ensure the data are premultiplied.
  101137. */
  101138. _this.PREMULTIPLYALPHA = false;
  101139. /**
  101140. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  101141. */
  101142. _this.USERGBCOLOR = false;
  101143. /**
  101144. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  101145. * stays aligned with the desired configuration.
  101146. */
  101147. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  101148. /**
  101149. * True to add noise in order to reduce the banding effect.
  101150. */
  101151. _this.NOISE = false;
  101152. /**
  101153. * is the reflection texture in BGR color scheme?
  101154. * Mainly used to solve a bug in ios10 video tag
  101155. */
  101156. _this.REFLECTIONBGR = false;
  101157. _this.IMAGEPROCESSING = false;
  101158. _this.VIGNETTE = false;
  101159. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  101160. _this.VIGNETTEBLENDMODEOPAQUE = false;
  101161. _this.TONEMAPPING = false;
  101162. _this.CONTRAST = false;
  101163. _this.COLORCURVES = false;
  101164. _this.COLORGRADING = false;
  101165. _this.COLORGRADING3D = false;
  101166. _this.SAMPLER3DGREENDEPTH = false;
  101167. _this.SAMPLER3DBGRMAP = false;
  101168. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  101169. _this.EXPOSURE = false;
  101170. // Reflection.
  101171. _this.REFLECTION = false;
  101172. _this.REFLECTIONMAP_3D = false;
  101173. _this.REFLECTIONMAP_SPHERICAL = false;
  101174. _this.REFLECTIONMAP_PLANAR = false;
  101175. _this.REFLECTIONMAP_CUBIC = false;
  101176. _this.REFLECTIONMAP_PROJECTION = false;
  101177. _this.REFLECTIONMAP_SKYBOX = false;
  101178. _this.REFLECTIONMAP_EXPLICIT = false;
  101179. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101180. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101181. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101182. _this.INVERTCUBICMAP = false;
  101183. _this.REFLECTIONMAP_OPPOSITEZ = false;
  101184. _this.LODINREFLECTIONALPHA = false;
  101185. _this.GAMMAREFLECTION = false;
  101186. _this.RGBDREFLECTION = false;
  101187. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  101188. // Default BJS.
  101189. _this.MAINUV1 = false;
  101190. _this.MAINUV2 = false;
  101191. _this.UV1 = false;
  101192. _this.UV2 = false;
  101193. _this.CLIPPLANE = false;
  101194. _this.POINTSIZE = false;
  101195. _this.FOG = false;
  101196. _this.NORMAL = false;
  101197. _this.NUM_BONE_INFLUENCERS = 0;
  101198. _this.BonesPerMesh = 0;
  101199. _this.INSTANCES = false;
  101200. _this.SHADOWFLOAT = false;
  101201. _this.rebuild();
  101202. return _this;
  101203. }
  101204. return BackgroundMaterialDefines;
  101205. }(BABYLON.MaterialDefines));
  101206. /**
  101207. * Background material used to create an efficient environement around your scene.
  101208. */
  101209. var BackgroundMaterial = /** @class */ (function (_super) {
  101210. __extends(BackgroundMaterial, _super);
  101211. /**
  101212. * Instantiates a Background Material in the given scene
  101213. * @param name The friendly name of the material
  101214. * @param scene The scene to add the material to
  101215. */
  101216. function BackgroundMaterial(name, scene) {
  101217. var _this = _super.call(this, name, scene) || this;
  101218. /**
  101219. * Key light Color (multiply against the environement texture)
  101220. */
  101221. _this.primaryColor = BABYLON.Color3.White();
  101222. _this._primaryColorShadowLevel = 0;
  101223. _this._primaryColorHighlightLevel = 0;
  101224. /**
  101225. * Reflection Texture used in the material.
  101226. * Should be author in a specific way for the best result (refer to the documentation).
  101227. */
  101228. _this.reflectionTexture = null;
  101229. /**
  101230. * Reflection Texture level of blur.
  101231. *
  101232. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  101233. * texture twice.
  101234. */
  101235. _this.reflectionBlur = 0;
  101236. /**
  101237. * Diffuse Texture used in the material.
  101238. * Should be author in a specific way for the best result (refer to the documentation).
  101239. */
  101240. _this.diffuseTexture = null;
  101241. _this._shadowLights = null;
  101242. /**
  101243. * Specify the list of lights casting shadow on the material.
  101244. * All scene shadow lights will be included if null.
  101245. */
  101246. _this.shadowLights = null;
  101247. /**
  101248. * Helps adjusting the shadow to a softer level if required.
  101249. * 0 means black shadows and 1 means no shadows.
  101250. */
  101251. _this.shadowLevel = 0;
  101252. /**
  101253. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  101254. * It is usually zero but might be interesting to modify according to your setup.
  101255. */
  101256. _this.sceneCenter = BABYLON.Vector3.Zero();
  101257. /**
  101258. * This helps specifying that the material is falling off to the sky box at grazing angle.
  101259. * This helps ensuring a nice transition when the camera goes under the ground.
  101260. */
  101261. _this.opacityFresnel = true;
  101262. /**
  101263. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  101264. * This helps adding a mirror texture on the ground.
  101265. */
  101266. _this.reflectionFresnel = false;
  101267. /**
  101268. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  101269. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  101270. */
  101271. _this.reflectionFalloffDistance = 0.0;
  101272. /**
  101273. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  101274. */
  101275. _this.reflectionAmount = 1.0;
  101276. /**
  101277. * This specifies the weight of the reflection at grazing angle.
  101278. */
  101279. _this.reflectionReflectance0 = 0.05;
  101280. /**
  101281. * This specifies the weight of the reflection at a perpendicular point of view.
  101282. */
  101283. _this.reflectionReflectance90 = 0.5;
  101284. /**
  101285. * Helps to directly use the maps channels instead of their level.
  101286. */
  101287. _this.useRGBColor = true;
  101288. /**
  101289. * This helps reducing the banding effect that could occur on the background.
  101290. */
  101291. _this.enableNoise = false;
  101292. _this._fovMultiplier = 1.0;
  101293. /**
  101294. * Enable the FOV adjustment feature controlled by fovMultiplier.
  101295. */
  101296. _this.useEquirectangularFOV = false;
  101297. _this._maxSimultaneousLights = 4;
  101298. /**
  101299. * Number of Simultaneous lights allowed on the material.
  101300. */
  101301. _this.maxSimultaneousLights = 4;
  101302. /**
  101303. * Keep track of the image processing observer to allow dispose and replace.
  101304. */
  101305. _this._imageProcessingObserver = null;
  101306. /**
  101307. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  101308. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  101309. */
  101310. _this.switchToBGR = false;
  101311. // Temp values kept as cache in the material.
  101312. _this._renderTargets = new BABYLON.SmartArray(16);
  101313. _this._reflectionControls = BABYLON.Vector4.Zero();
  101314. _this._white = BABYLON.Color3.White();
  101315. _this._primaryShadowColor = BABYLON.Color3.Black();
  101316. _this._primaryHighlightColor = BABYLON.Color3.Black();
  101317. // Setup the default processing configuration to the scene.
  101318. _this._attachImageProcessingConfiguration(null);
  101319. _this.getRenderTargetTextures = function () {
  101320. _this._renderTargets.reset();
  101321. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  101322. _this._renderTargets.push(_this._diffuseTexture);
  101323. }
  101324. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  101325. _this._renderTargets.push(_this._reflectionTexture);
  101326. }
  101327. return _this._renderTargets;
  101328. };
  101329. return _this;
  101330. }
  101331. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  101332. /**
  101333. * Experimental Internal Use Only.
  101334. *
  101335. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  101336. * This acts as a helper to set the primary color to a more "human friendly" value.
  101337. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  101338. * output color as close as possible from the chosen value.
  101339. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  101340. * part of lighting setup.)
  101341. */
  101342. get: function () {
  101343. return this.__perceptualColor;
  101344. },
  101345. set: function (value) {
  101346. this.__perceptualColor = value;
  101347. this._computePrimaryColorFromPerceptualColor();
  101348. this._markAllSubMeshesAsLightsDirty();
  101349. },
  101350. enumerable: true,
  101351. configurable: true
  101352. });
  101353. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  101354. /**
  101355. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  101356. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  101357. */
  101358. get: function () {
  101359. return this._primaryColorShadowLevel;
  101360. },
  101361. set: function (value) {
  101362. this._primaryColorShadowLevel = value;
  101363. this._computePrimaryColors();
  101364. this._markAllSubMeshesAsLightsDirty();
  101365. },
  101366. enumerable: true,
  101367. configurable: true
  101368. });
  101369. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  101370. /**
  101371. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  101372. * The primary color is used at the level chosen to define what the white area would look.
  101373. */
  101374. get: function () {
  101375. return this._primaryColorHighlightLevel;
  101376. },
  101377. set: function (value) {
  101378. this._primaryColorHighlightLevel = value;
  101379. this._computePrimaryColors();
  101380. this._markAllSubMeshesAsLightsDirty();
  101381. },
  101382. enumerable: true,
  101383. configurable: true
  101384. });
  101385. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  101386. /**
  101387. * Sets the reflection reflectance fresnel values according to the default standard
  101388. * empirically know to work well :-)
  101389. */
  101390. set: function (value) {
  101391. var reflectionWeight = value;
  101392. if (reflectionWeight < 0.5) {
  101393. reflectionWeight = reflectionWeight * 2.0;
  101394. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  101395. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  101396. }
  101397. else {
  101398. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  101399. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  101400. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  101401. }
  101402. },
  101403. enumerable: true,
  101404. configurable: true
  101405. });
  101406. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  101407. /**
  101408. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101409. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  101410. * Recommended to be keep at 1.0 except for special cases.
  101411. */
  101412. get: function () {
  101413. return this._fovMultiplier;
  101414. },
  101415. set: function (value) {
  101416. if (isNaN(value)) {
  101417. value = 1.0;
  101418. }
  101419. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  101420. },
  101421. enumerable: true,
  101422. configurable: true
  101423. });
  101424. /**
  101425. * Attaches a new image processing configuration to the PBR Material.
  101426. * @param configuration (if null the scene configuration will be use)
  101427. */
  101428. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  101429. var _this = this;
  101430. if (configuration === this._imageProcessingConfiguration) {
  101431. return;
  101432. }
  101433. // Detaches observer.
  101434. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101435. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101436. }
  101437. // Pick the scene configuration if needed.
  101438. if (!configuration) {
  101439. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  101440. }
  101441. else {
  101442. this._imageProcessingConfiguration = configuration;
  101443. }
  101444. // Attaches observer.
  101445. if (this._imageProcessingConfiguration) {
  101446. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  101447. _this._computePrimaryColorFromPerceptualColor();
  101448. _this._markAllSubMeshesAsImageProcessingDirty();
  101449. });
  101450. }
  101451. };
  101452. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  101453. /**
  101454. * Gets the image processing configuration used either in this material.
  101455. */
  101456. get: function () {
  101457. return this._imageProcessingConfiguration;
  101458. },
  101459. /**
  101460. * Sets the Default image processing configuration used either in the this material.
  101461. *
  101462. * If sets to null, the scene one is in use.
  101463. */
  101464. set: function (value) {
  101465. this._attachImageProcessingConfiguration(value);
  101466. // Ensure the effect will be rebuilt.
  101467. this._markAllSubMeshesAsTexturesDirty();
  101468. },
  101469. enumerable: true,
  101470. configurable: true
  101471. });
  101472. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  101473. /**
  101474. * Gets wether the color curves effect is enabled.
  101475. */
  101476. get: function () {
  101477. return this.imageProcessingConfiguration.colorCurvesEnabled;
  101478. },
  101479. /**
  101480. * Sets wether the color curves effect is enabled.
  101481. */
  101482. set: function (value) {
  101483. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  101484. },
  101485. enumerable: true,
  101486. configurable: true
  101487. });
  101488. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  101489. /**
  101490. * Gets wether the color grading effect is enabled.
  101491. */
  101492. get: function () {
  101493. return this.imageProcessingConfiguration.colorGradingEnabled;
  101494. },
  101495. /**
  101496. * Gets wether the color grading effect is enabled.
  101497. */
  101498. set: function (value) {
  101499. this.imageProcessingConfiguration.colorGradingEnabled = value;
  101500. },
  101501. enumerable: true,
  101502. configurable: true
  101503. });
  101504. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  101505. /**
  101506. * Gets wether tonemapping is enabled or not.
  101507. */
  101508. get: function () {
  101509. return this._imageProcessingConfiguration.toneMappingEnabled;
  101510. },
  101511. /**
  101512. * Sets wether tonemapping is enabled or not
  101513. */
  101514. set: function (value) {
  101515. this._imageProcessingConfiguration.toneMappingEnabled = value;
  101516. },
  101517. enumerable: true,
  101518. configurable: true
  101519. });
  101520. ;
  101521. ;
  101522. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  101523. /**
  101524. * The camera exposure used on this material.
  101525. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101526. * This corresponds to a photographic exposure.
  101527. */
  101528. get: function () {
  101529. return this._imageProcessingConfiguration.exposure;
  101530. },
  101531. /**
  101532. * The camera exposure used on this material.
  101533. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101534. * This corresponds to a photographic exposure.
  101535. */
  101536. set: function (value) {
  101537. this._imageProcessingConfiguration.exposure = value;
  101538. },
  101539. enumerable: true,
  101540. configurable: true
  101541. });
  101542. ;
  101543. ;
  101544. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  101545. /**
  101546. * Gets The camera contrast used on this material.
  101547. */
  101548. get: function () {
  101549. return this._imageProcessingConfiguration.contrast;
  101550. },
  101551. /**
  101552. * Sets The camera contrast used on this material.
  101553. */
  101554. set: function (value) {
  101555. this._imageProcessingConfiguration.contrast = value;
  101556. },
  101557. enumerable: true,
  101558. configurable: true
  101559. });
  101560. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  101561. /**
  101562. * Gets the Color Grading 2D Lookup Texture.
  101563. */
  101564. get: function () {
  101565. return this._imageProcessingConfiguration.colorGradingTexture;
  101566. },
  101567. /**
  101568. * Sets the Color Grading 2D Lookup Texture.
  101569. */
  101570. set: function (value) {
  101571. this.imageProcessingConfiguration.colorGradingTexture = value;
  101572. },
  101573. enumerable: true,
  101574. configurable: true
  101575. });
  101576. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  101577. /**
  101578. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101579. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101580. * 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;
  101581. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101582. */
  101583. get: function () {
  101584. return this.imageProcessingConfiguration.colorCurves;
  101585. },
  101586. /**
  101587. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101588. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101589. * 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;
  101590. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101591. */
  101592. set: function (value) {
  101593. this.imageProcessingConfiguration.colorCurves = value;
  101594. },
  101595. enumerable: true,
  101596. configurable: true
  101597. });
  101598. /**
  101599. * The entire material has been created in order to prevent overdraw.
  101600. * @returns false
  101601. */
  101602. BackgroundMaterial.prototype.needAlphaTesting = function () {
  101603. return true;
  101604. };
  101605. /**
  101606. * The entire material has been created in order to prevent overdraw.
  101607. * @returns true if blending is enable
  101608. */
  101609. BackgroundMaterial.prototype.needAlphaBlending = function () {
  101610. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  101611. };
  101612. /**
  101613. * Checks wether the material is ready to be rendered for a given mesh.
  101614. * @param mesh The mesh to render
  101615. * @param subMesh The submesh to check against
  101616. * @param useInstances Specify wether or not the material is used with instances
  101617. * @returns true if all the dependencies are ready (Textures, Effects...)
  101618. */
  101619. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  101620. var _this = this;
  101621. if (useInstances === void 0) { useInstances = false; }
  101622. if (subMesh.effect && this.isFrozen) {
  101623. if (this._wasPreviouslyReady) {
  101624. return true;
  101625. }
  101626. }
  101627. if (!subMesh._materialDefines) {
  101628. subMesh._materialDefines = new BackgroundMaterialDefines();
  101629. }
  101630. var scene = this.getScene();
  101631. var defines = subMesh._materialDefines;
  101632. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  101633. if (defines._renderId === scene.getRenderId()) {
  101634. return true;
  101635. }
  101636. }
  101637. var engine = scene.getEngine();
  101638. // Lights
  101639. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  101640. defines._needNormals = true;
  101641. // Textures
  101642. if (defines._areTexturesDirty) {
  101643. defines._needUVs = false;
  101644. if (scene.texturesEnabled) {
  101645. if (scene.getEngine().getCaps().textureLOD) {
  101646. defines.TEXTURELODSUPPORT = true;
  101647. }
  101648. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101649. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  101650. return false;
  101651. }
  101652. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  101653. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  101654. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  101655. defines.OPACITYFRESNEL = this._opacityFresnel;
  101656. }
  101657. else {
  101658. defines.DIFFUSE = false;
  101659. defines.DIFFUSEHASALPHA = false;
  101660. defines.GAMMADIFFUSE = false;
  101661. defines.OPACITYFRESNEL = false;
  101662. }
  101663. var reflectionTexture = this._reflectionTexture;
  101664. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101665. if (!reflectionTexture.isReadyOrNotBlocking()) {
  101666. return false;
  101667. }
  101668. defines.REFLECTION = true;
  101669. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  101670. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  101671. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  101672. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  101673. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  101674. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  101675. defines.REFLECTIONBGR = this.switchToBGR;
  101676. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  101677. defines.INVERTCUBICMAP = true;
  101678. }
  101679. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  101680. switch (reflectionTexture.coordinatesMode) {
  101681. case BABYLON.Texture.EXPLICIT_MODE:
  101682. defines.REFLECTIONMAP_EXPLICIT = true;
  101683. break;
  101684. case BABYLON.Texture.PLANAR_MODE:
  101685. defines.REFLECTIONMAP_PLANAR = true;
  101686. break;
  101687. case BABYLON.Texture.PROJECTION_MODE:
  101688. defines.REFLECTIONMAP_PROJECTION = true;
  101689. break;
  101690. case BABYLON.Texture.SKYBOX_MODE:
  101691. defines.REFLECTIONMAP_SKYBOX = true;
  101692. break;
  101693. case BABYLON.Texture.SPHERICAL_MODE:
  101694. defines.REFLECTIONMAP_SPHERICAL = true;
  101695. break;
  101696. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  101697. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  101698. break;
  101699. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  101700. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  101701. break;
  101702. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  101703. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  101704. break;
  101705. case BABYLON.Texture.CUBIC_MODE:
  101706. case BABYLON.Texture.INVCUBIC_MODE:
  101707. default:
  101708. defines.REFLECTIONMAP_CUBIC = true;
  101709. break;
  101710. }
  101711. if (this.reflectionFresnel) {
  101712. defines.REFLECTIONFRESNEL = true;
  101713. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  101714. this._reflectionControls.x = this.reflectionAmount;
  101715. this._reflectionControls.y = this.reflectionReflectance0;
  101716. this._reflectionControls.z = this.reflectionReflectance90;
  101717. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  101718. }
  101719. else {
  101720. defines.REFLECTIONFRESNEL = false;
  101721. defines.REFLECTIONFALLOFF = false;
  101722. }
  101723. }
  101724. else {
  101725. defines.REFLECTION = false;
  101726. defines.REFLECTIONFRESNEL = false;
  101727. defines.REFLECTIONFALLOFF = false;
  101728. defines.REFLECTIONBLUR = false;
  101729. defines.REFLECTIONMAP_3D = false;
  101730. defines.REFLECTIONMAP_SPHERICAL = false;
  101731. defines.REFLECTIONMAP_PLANAR = false;
  101732. defines.REFLECTIONMAP_CUBIC = false;
  101733. defines.REFLECTIONMAP_PROJECTION = false;
  101734. defines.REFLECTIONMAP_SKYBOX = false;
  101735. defines.REFLECTIONMAP_EXPLICIT = false;
  101736. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101737. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101738. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101739. defines.INVERTCUBICMAP = false;
  101740. defines.REFLECTIONMAP_OPPOSITEZ = false;
  101741. defines.LODINREFLECTIONALPHA = false;
  101742. defines.GAMMAREFLECTION = false;
  101743. defines.RGBDREFLECTION = false;
  101744. }
  101745. }
  101746. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  101747. defines.USERGBCOLOR = this._useRGBColor;
  101748. defines.NOISE = this._enableNoise;
  101749. }
  101750. if (defines._areLightsDirty) {
  101751. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  101752. }
  101753. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  101754. if (!this._imageProcessingConfiguration.isReady()) {
  101755. return false;
  101756. }
  101757. this._imageProcessingConfiguration.prepareDefines(defines);
  101758. }
  101759. // Misc.
  101760. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  101761. // Values that need to be evaluated on every frame
  101762. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  101763. // Attribs
  101764. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  101765. if (mesh) {
  101766. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  101767. mesh.createNormals(true);
  101768. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  101769. }
  101770. }
  101771. }
  101772. // Get correct effect
  101773. if (defines.isDirty) {
  101774. defines.markAsProcessed();
  101775. scene.resetCachedMaterial();
  101776. // Fallbacks
  101777. var fallbacks = new BABYLON.EffectFallbacks();
  101778. if (defines.FOG) {
  101779. fallbacks.addFallback(0, "FOG");
  101780. }
  101781. if (defines.POINTSIZE) {
  101782. fallbacks.addFallback(1, "POINTSIZE");
  101783. }
  101784. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  101785. if (defines.NUM_BONE_INFLUENCERS > 0) {
  101786. fallbacks.addCPUSkinningFallback(0, mesh);
  101787. }
  101788. //Attributes
  101789. var attribs = [BABYLON.VertexBuffer.PositionKind];
  101790. if (defines.NORMAL) {
  101791. attribs.push(BABYLON.VertexBuffer.NormalKind);
  101792. }
  101793. if (defines.UV1) {
  101794. attribs.push(BABYLON.VertexBuffer.UVKind);
  101795. }
  101796. if (defines.UV2) {
  101797. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101798. }
  101799. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  101800. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  101801. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  101802. "vFogInfos", "vFogColor", "pointSize",
  101803. "vClipPlane", "mBones",
  101804. "vPrimaryColor", "vPrimaryColorShadow",
  101805. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  101806. "shadowLevel", "alpha",
  101807. "vBackgroundCenter", "vReflectionControl",
  101808. "vDiffuseInfos", "diffuseMatrix",
  101809. ];
  101810. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  101811. var uniformBuffers = ["Material", "Scene"];
  101812. if (BABYLON.ImageProcessingConfiguration) {
  101813. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  101814. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  101815. }
  101816. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  101817. uniformsNames: uniforms,
  101818. uniformBuffersNames: uniformBuffers,
  101819. samplers: samplers,
  101820. defines: defines,
  101821. maxSimultaneousLights: this._maxSimultaneousLights
  101822. });
  101823. var onCompiled = function (effect) {
  101824. if (_this.onCompiled) {
  101825. _this.onCompiled(effect);
  101826. }
  101827. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  101828. };
  101829. var join = defines.toString();
  101830. subMesh.setEffect(scene.getEngine().createEffect("background", {
  101831. attributes: attribs,
  101832. uniformsNames: uniforms,
  101833. uniformBuffersNames: uniformBuffers,
  101834. samplers: samplers,
  101835. defines: join,
  101836. fallbacks: fallbacks,
  101837. onCompiled: onCompiled,
  101838. onError: this.onError,
  101839. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  101840. }, engine), defines);
  101841. this.buildUniformLayout();
  101842. }
  101843. if (!subMesh.effect || !subMesh.effect.isReady()) {
  101844. return false;
  101845. }
  101846. defines._renderId = scene.getRenderId();
  101847. this._wasPreviouslyReady = true;
  101848. return true;
  101849. };
  101850. /**
  101851. * Compute the primary color according to the chosen perceptual color.
  101852. */
  101853. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  101854. if (!this.__perceptualColor) {
  101855. return;
  101856. }
  101857. this._primaryColor.copyFrom(this.__perceptualColor);
  101858. // Revert gamma space.
  101859. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  101860. // Revert image processing configuration.
  101861. if (this._imageProcessingConfiguration) {
  101862. // Revert Exposure.
  101863. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  101864. }
  101865. this._computePrimaryColors();
  101866. };
  101867. /**
  101868. * Compute the highlights and shadow colors according to their chosen levels.
  101869. */
  101870. BackgroundMaterial.prototype._computePrimaryColors = function () {
  101871. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  101872. return;
  101873. }
  101874. // Find the highlight color based on the configuration.
  101875. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  101876. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  101877. // Find the shadow color based on the configuration.
  101878. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  101879. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  101880. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  101881. };
  101882. /**
  101883. * Build the uniform buffer used in the material.
  101884. */
  101885. BackgroundMaterial.prototype.buildUniformLayout = function () {
  101886. // Order is important !
  101887. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  101888. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  101889. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  101890. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  101891. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  101892. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  101893. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  101894. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  101895. this._uniformBuffer.addUniform("pointSize", 1);
  101896. this._uniformBuffer.addUniform("shadowLevel", 1);
  101897. this._uniformBuffer.addUniform("alpha", 1);
  101898. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  101899. this._uniformBuffer.addUniform("vReflectionControl", 4);
  101900. this._uniformBuffer.create();
  101901. };
  101902. /**
  101903. * Unbind the material.
  101904. */
  101905. BackgroundMaterial.prototype.unbind = function () {
  101906. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  101907. this._uniformBuffer.setTexture("diffuseSampler", null);
  101908. }
  101909. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  101910. this._uniformBuffer.setTexture("reflectionSampler", null);
  101911. }
  101912. _super.prototype.unbind.call(this);
  101913. };
  101914. /**
  101915. * Bind only the world matrix to the material.
  101916. * @param world The world matrix to bind.
  101917. */
  101918. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  101919. this._activeEffect.setMatrix("world", world);
  101920. };
  101921. /**
  101922. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  101923. * @param world The world matrix to bind.
  101924. * @param subMesh The submesh to bind for.
  101925. */
  101926. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  101927. var scene = this.getScene();
  101928. var defines = subMesh._materialDefines;
  101929. if (!defines) {
  101930. return;
  101931. }
  101932. var effect = subMesh.effect;
  101933. if (!effect) {
  101934. return;
  101935. }
  101936. this._activeEffect = effect;
  101937. // Matrices
  101938. this.bindOnlyWorldMatrix(world);
  101939. // Bones
  101940. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  101941. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  101942. if (mustRebind) {
  101943. this._uniformBuffer.bindToEffect(effect, "Material");
  101944. this.bindViewProjection(effect);
  101945. var reflectionTexture = this._reflectionTexture;
  101946. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  101947. // Texture uniforms
  101948. if (scene.texturesEnabled) {
  101949. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101950. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  101951. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  101952. }
  101953. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101954. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  101955. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  101956. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  101957. }
  101958. }
  101959. if (this.shadowLevel > 0) {
  101960. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  101961. }
  101962. this._uniformBuffer.updateFloat("alpha", this.alpha);
  101963. // Point size
  101964. if (this.pointsCloud) {
  101965. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  101966. }
  101967. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  101968. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  101969. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  101970. }
  101971. else {
  101972. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  101973. }
  101974. }
  101975. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  101976. // Textures
  101977. if (scene.texturesEnabled) {
  101978. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101979. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  101980. }
  101981. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101982. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  101983. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101984. }
  101985. else if (!defines.REFLECTIONBLUR) {
  101986. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101987. }
  101988. else {
  101989. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  101990. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  101991. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  101992. }
  101993. if (defines.REFLECTIONFRESNEL) {
  101994. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  101995. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  101996. }
  101997. }
  101998. }
  101999. // Clip plane
  102000. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  102001. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  102002. }
  102003. if (mustRebind || !this.isFrozen) {
  102004. if (scene.lightsEnabled) {
  102005. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  102006. }
  102007. // View
  102008. this.bindView(effect);
  102009. // Fog
  102010. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  102011. // image processing
  102012. if (this._imageProcessingConfiguration) {
  102013. this._imageProcessingConfiguration.bind(this._activeEffect);
  102014. }
  102015. }
  102016. this._uniformBuffer.update();
  102017. this._afterBind(mesh, this._activeEffect);
  102018. };
  102019. /**
  102020. * Dispose the material.
  102021. * @param forceDisposeEffect Force disposal of the associated effect.
  102022. * @param forceDisposeTextures Force disposal of the associated textures.
  102023. */
  102024. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  102025. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  102026. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  102027. if (forceDisposeTextures) {
  102028. if (this.diffuseTexture) {
  102029. this.diffuseTexture.dispose();
  102030. }
  102031. if (this.reflectionTexture) {
  102032. this.reflectionTexture.dispose();
  102033. }
  102034. }
  102035. this._renderTargets.dispose();
  102036. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102037. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102038. }
  102039. _super.prototype.dispose.call(this, forceDisposeEffect);
  102040. };
  102041. /**
  102042. * Clones the material.
  102043. * @param name The cloned name.
  102044. * @returns The cloned material.
  102045. */
  102046. BackgroundMaterial.prototype.clone = function (name) {
  102047. var _this = this;
  102048. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  102049. };
  102050. /**
  102051. * Serializes the current material to its JSON representation.
  102052. * @returns The JSON representation.
  102053. */
  102054. BackgroundMaterial.prototype.serialize = function () {
  102055. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102056. serializationObject.customType = "BABYLON.BackgroundMaterial";
  102057. return serializationObject;
  102058. };
  102059. /**
  102060. * Gets the class name of the material
  102061. * @returns "BackgroundMaterial"
  102062. */
  102063. BackgroundMaterial.prototype.getClassName = function () {
  102064. return "BackgroundMaterial";
  102065. };
  102066. /**
  102067. * Parse a JSON input to create back a background material.
  102068. * @param source The JSON data to parse
  102069. * @param scene The scene to create the parsed material in
  102070. * @param rootUrl The root url of the assets the material depends upon
  102071. * @returns the instantiated BackgroundMaterial.
  102072. */
  102073. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  102074. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  102075. };
  102076. /**
  102077. * Standard reflectance value at parallel view angle.
  102078. */
  102079. BackgroundMaterial.StandardReflectance0 = 0.05;
  102080. /**
  102081. * Standard reflectance value at grazing angle.
  102082. */
  102083. BackgroundMaterial.StandardReflectance90 = 0.5;
  102084. __decorate([
  102085. BABYLON.serializeAsColor3()
  102086. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  102087. __decorate([
  102088. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102089. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  102090. __decorate([
  102091. BABYLON.serializeAsColor3()
  102092. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  102093. __decorate([
  102094. BABYLON.serialize()
  102095. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  102096. __decorate([
  102097. BABYLON.serialize()
  102098. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  102099. __decorate([
  102100. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102101. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  102102. __decorate([
  102103. BABYLON.serializeAsTexture()
  102104. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  102105. __decorate([
  102106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102107. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  102108. __decorate([
  102109. BABYLON.serialize()
  102110. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  102111. __decorate([
  102112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102113. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  102114. __decorate([
  102115. BABYLON.serializeAsTexture()
  102116. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  102117. __decorate([
  102118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102119. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  102120. __decorate([
  102121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102122. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  102123. __decorate([
  102124. BABYLON.serialize()
  102125. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  102126. __decorate([
  102127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102128. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  102129. __decorate([
  102130. BABYLON.serializeAsVector3()
  102131. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  102132. __decorate([
  102133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102134. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  102135. __decorate([
  102136. BABYLON.serialize()
  102137. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  102138. __decorate([
  102139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102140. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  102141. __decorate([
  102142. BABYLON.serialize()
  102143. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  102144. __decorate([
  102145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102146. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  102147. __decorate([
  102148. BABYLON.serialize()
  102149. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  102150. __decorate([
  102151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102152. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  102153. __decorate([
  102154. BABYLON.serialize()
  102155. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  102156. __decorate([
  102157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102158. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  102159. __decorate([
  102160. BABYLON.serialize()
  102161. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  102162. __decorate([
  102163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102164. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  102165. __decorate([
  102166. BABYLON.serialize()
  102167. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  102168. __decorate([
  102169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102170. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  102171. __decorate([
  102172. BABYLON.serialize()
  102173. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  102174. __decorate([
  102175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102176. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  102177. __decorate([
  102178. BABYLON.serialize()
  102179. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  102180. __decorate([
  102181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102182. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  102183. __decorate([
  102184. BABYLON.serialize()
  102185. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  102186. __decorate([
  102187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102188. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  102189. __decorate([
  102190. BABYLON.serializeAsImageProcessingConfiguration()
  102191. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  102192. return BackgroundMaterial;
  102193. }(BABYLON.PushMaterial));
  102194. BABYLON.BackgroundMaterial = BackgroundMaterial;
  102195. })(BABYLON || (BABYLON = {}));
  102196. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  102197. var __assign = (this && this.__assign) || Object.assign || function(t) {
  102198. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102199. s = arguments[i];
  102200. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102201. t[p] = s[p];
  102202. }
  102203. return t;
  102204. };
  102205. var BABYLON;
  102206. (function (BABYLON) {
  102207. /**
  102208. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  102209. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  102210. * It also helps with the default setup of your imageProcessing configuration.
  102211. */
  102212. var EnvironmentHelper = /** @class */ (function () {
  102213. /**
  102214. * constructor
  102215. * @param options
  102216. * @param scene The scene to add the material to
  102217. */
  102218. function EnvironmentHelper(options, scene) {
  102219. var _this = this;
  102220. this._errorHandler = function (message, exception) {
  102221. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  102222. };
  102223. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  102224. this._scene = scene;
  102225. this.onErrorObservable = new BABYLON.Observable();
  102226. this._setupBackground();
  102227. this._setupImageProcessing();
  102228. }
  102229. /**
  102230. * Creates the default options for the helper.
  102231. */
  102232. EnvironmentHelper._getDefaultOptions = function () {
  102233. return {
  102234. createGround: true,
  102235. groundSize: 15,
  102236. groundTexture: this._groundTextureCDNUrl,
  102237. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102238. groundOpacity: 0.9,
  102239. enableGroundShadow: true,
  102240. groundShadowLevel: 0.5,
  102241. enableGroundMirror: false,
  102242. groundMirrorSizeRatio: 0.3,
  102243. groundMirrorBlurKernel: 64,
  102244. groundMirrorAmount: 1,
  102245. groundMirrorFresnelWeight: 1,
  102246. groundMirrorFallOffDistance: 0,
  102247. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  102248. groundYBias: 0.00001,
  102249. createSkybox: true,
  102250. skyboxSize: 20,
  102251. skyboxTexture: this._skyboxTextureCDNUrl,
  102252. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102253. backgroundYRotation: 0,
  102254. sizeAuto: true,
  102255. rootPosition: BABYLON.Vector3.Zero(),
  102256. setupImageProcessing: true,
  102257. environmentTexture: this._environmentTextureCDNUrl,
  102258. cameraExposure: 0.8,
  102259. cameraContrast: 1.2,
  102260. toneMappingEnabled: true,
  102261. };
  102262. };
  102263. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  102264. /**
  102265. * Gets the root mesh created by the helper.
  102266. */
  102267. get: function () {
  102268. return this._rootMesh;
  102269. },
  102270. enumerable: true,
  102271. configurable: true
  102272. });
  102273. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  102274. /**
  102275. * Gets the skybox created by the helper.
  102276. */
  102277. get: function () {
  102278. return this._skybox;
  102279. },
  102280. enumerable: true,
  102281. configurable: true
  102282. });
  102283. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  102284. /**
  102285. * Gets the skybox texture created by the helper.
  102286. */
  102287. get: function () {
  102288. return this._skyboxTexture;
  102289. },
  102290. enumerable: true,
  102291. configurable: true
  102292. });
  102293. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  102294. /**
  102295. * Gets the skybox material created by the helper.
  102296. */
  102297. get: function () {
  102298. return this._skyboxMaterial;
  102299. },
  102300. enumerable: true,
  102301. configurable: true
  102302. });
  102303. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  102304. /**
  102305. * Gets the ground mesh created by the helper.
  102306. */
  102307. get: function () {
  102308. return this._ground;
  102309. },
  102310. enumerable: true,
  102311. configurable: true
  102312. });
  102313. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  102314. /**
  102315. * Gets the ground texture created by the helper.
  102316. */
  102317. get: function () {
  102318. return this._groundTexture;
  102319. },
  102320. enumerable: true,
  102321. configurable: true
  102322. });
  102323. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  102324. /**
  102325. * Gets the ground mirror created by the helper.
  102326. */
  102327. get: function () {
  102328. return this._groundMirror;
  102329. },
  102330. enumerable: true,
  102331. configurable: true
  102332. });
  102333. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  102334. /**
  102335. * Gets the ground mirror render list to helps pushing the meshes
  102336. * you wish in the ground reflection.
  102337. */
  102338. get: function () {
  102339. if (this._groundMirror) {
  102340. return this._groundMirror.renderList;
  102341. }
  102342. return null;
  102343. },
  102344. enumerable: true,
  102345. configurable: true
  102346. });
  102347. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  102348. /**
  102349. * Gets the ground material created by the helper.
  102350. */
  102351. get: function () {
  102352. return this._groundMaterial;
  102353. },
  102354. enumerable: true,
  102355. configurable: true
  102356. });
  102357. /**
  102358. * Updates the background according to the new options
  102359. * @param options
  102360. */
  102361. EnvironmentHelper.prototype.updateOptions = function (options) {
  102362. var newOptions = __assign({}, this._options, options);
  102363. if (this._ground && !newOptions.createGround) {
  102364. this._ground.dispose();
  102365. this._ground = null;
  102366. }
  102367. if (this._groundMaterial && !newOptions.createGround) {
  102368. this._groundMaterial.dispose();
  102369. this._groundMaterial = null;
  102370. }
  102371. if (this._groundTexture) {
  102372. if (this._options.groundTexture != newOptions.groundTexture) {
  102373. this._groundTexture.dispose();
  102374. this._groundTexture = null;
  102375. }
  102376. }
  102377. if (this._skybox && !newOptions.createSkybox) {
  102378. this._skybox.dispose();
  102379. this._skybox = null;
  102380. }
  102381. if (this._skyboxMaterial && !newOptions.createSkybox) {
  102382. this._skyboxMaterial.dispose();
  102383. this._skyboxMaterial = null;
  102384. }
  102385. if (this._skyboxTexture) {
  102386. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  102387. this._skyboxTexture.dispose();
  102388. this._skyboxTexture = null;
  102389. }
  102390. }
  102391. if (this._groundMirror && !newOptions.enableGroundMirror) {
  102392. this._groundMirror.dispose();
  102393. this._groundMirror = null;
  102394. }
  102395. if (this._scene.environmentTexture) {
  102396. if (this._options.environmentTexture != newOptions.environmentTexture) {
  102397. this._scene.environmentTexture.dispose();
  102398. }
  102399. }
  102400. this._options = newOptions;
  102401. this._setupBackground();
  102402. this._setupImageProcessing();
  102403. };
  102404. /**
  102405. * Sets the primary color of all the available elements.
  102406. * @param color the main color to affect to the ground and the background
  102407. */
  102408. EnvironmentHelper.prototype.setMainColor = function (color) {
  102409. if (this.groundMaterial) {
  102410. this.groundMaterial.primaryColor = color;
  102411. }
  102412. if (this.skyboxMaterial) {
  102413. this.skyboxMaterial.primaryColor = color;
  102414. }
  102415. if (this.groundMirror) {
  102416. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  102417. }
  102418. };
  102419. /**
  102420. * Setup the image processing according to the specified options.
  102421. */
  102422. EnvironmentHelper.prototype._setupImageProcessing = function () {
  102423. if (this._options.setupImageProcessing) {
  102424. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  102425. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  102426. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  102427. this._setupEnvironmentTexture();
  102428. }
  102429. };
  102430. /**
  102431. * Setup the environment texture according to the specified options.
  102432. */
  102433. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  102434. if (this._scene.environmentTexture) {
  102435. return;
  102436. }
  102437. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  102438. this._scene.environmentTexture = this._options.environmentTexture;
  102439. return;
  102440. }
  102441. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  102442. this._scene.environmentTexture = environmentTexture;
  102443. };
  102444. /**
  102445. * Setup the background according to the specified options.
  102446. */
  102447. EnvironmentHelper.prototype._setupBackground = function () {
  102448. if (!this._rootMesh) {
  102449. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  102450. }
  102451. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  102452. var sceneSize = this._getSceneSize();
  102453. if (this._options.createGround) {
  102454. this._setupGround(sceneSize);
  102455. this._setupGroundMaterial();
  102456. this._setupGroundDiffuseTexture();
  102457. if (this._options.enableGroundMirror) {
  102458. this._setupGroundMirrorTexture(sceneSize);
  102459. }
  102460. this._setupMirrorInGroundMaterial();
  102461. }
  102462. if (this._options.createSkybox) {
  102463. this._setupSkybox(sceneSize);
  102464. this._setupSkyboxMaterial();
  102465. this._setupSkyboxReflectionTexture();
  102466. }
  102467. this._rootMesh.position.x = sceneSize.rootPosition.x;
  102468. this._rootMesh.position.z = sceneSize.rootPosition.z;
  102469. this._rootMesh.position.y = sceneSize.rootPosition.y;
  102470. };
  102471. /**
  102472. * Get the scene sizes according to the setup.
  102473. */
  102474. EnvironmentHelper.prototype._getSceneSize = function () {
  102475. var _this = this;
  102476. var groundSize = this._options.groundSize;
  102477. var skyboxSize = this._options.skyboxSize;
  102478. var rootPosition = this._options.rootPosition;
  102479. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  102480. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102481. }
  102482. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  102483. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  102484. });
  102485. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  102486. if (this._options.sizeAuto) {
  102487. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  102488. this._scene.activeCamera.upperRadiusLimit) {
  102489. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  102490. skyboxSize = groundSize;
  102491. }
  102492. var sceneDiagonalLenght = sceneDiagonal.length();
  102493. if (sceneDiagonalLenght > groundSize) {
  102494. groundSize = sceneDiagonalLenght * 2;
  102495. skyboxSize = groundSize;
  102496. }
  102497. // 10 % bigger.
  102498. groundSize *= 1.1;
  102499. skyboxSize *= 1.5;
  102500. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  102501. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  102502. }
  102503. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102504. };
  102505. /**
  102506. * Setup the ground according to the specified options.
  102507. */
  102508. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  102509. var _this = this;
  102510. if (!this._ground || this._ground.isDisposed()) {
  102511. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  102512. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  102513. this._ground.parent = this._rootMesh;
  102514. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  102515. }
  102516. this._ground.receiveShadows = this._options.enableGroundShadow;
  102517. };
  102518. /**
  102519. * Setup the ground material according to the specified options.
  102520. */
  102521. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  102522. if (!this._groundMaterial) {
  102523. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  102524. }
  102525. this._groundMaterial.alpha = this._options.groundOpacity;
  102526. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  102527. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  102528. this._groundMaterial.primaryColor = this._options.groundColor;
  102529. this._groundMaterial.useRGBColor = false;
  102530. this._groundMaterial.enableNoise = true;
  102531. if (this._ground) {
  102532. this._ground.material = this._groundMaterial;
  102533. }
  102534. };
  102535. /**
  102536. * Setup the ground diffuse texture according to the specified options.
  102537. */
  102538. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  102539. if (!this._groundMaterial) {
  102540. return;
  102541. }
  102542. if (this._groundTexture) {
  102543. return;
  102544. }
  102545. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  102546. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  102547. return;
  102548. }
  102549. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102550. diffuseTexture.gammaSpace = false;
  102551. diffuseTexture.hasAlpha = true;
  102552. this._groundMaterial.diffuseTexture = diffuseTexture;
  102553. };
  102554. /**
  102555. * Setup the ground mirror texture according to the specified options.
  102556. */
  102557. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  102558. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102559. if (!this._groundMirror) {
  102560. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  102561. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  102562. this._groundMirror.anisotropicFilteringLevel = 1;
  102563. this._groundMirror.wrapU = wrapping;
  102564. this._groundMirror.wrapV = wrapping;
  102565. this._groundMirror.gammaSpace = false;
  102566. if (this._groundMirror.renderList) {
  102567. for (var i = 0; i < this._scene.meshes.length; i++) {
  102568. var mesh = this._scene.meshes[i];
  102569. if (mesh !== this._ground &&
  102570. mesh !== this._skybox &&
  102571. mesh !== this._rootMesh) {
  102572. this._groundMirror.renderList.push(mesh);
  102573. }
  102574. }
  102575. }
  102576. }
  102577. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  102578. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  102579. };
  102580. /**
  102581. * Setup the ground to receive the mirror texture.
  102582. */
  102583. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  102584. if (this._groundMaterial) {
  102585. this._groundMaterial.reflectionTexture = this._groundMirror;
  102586. this._groundMaterial.reflectionFresnel = true;
  102587. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  102588. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  102589. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  102590. }
  102591. };
  102592. /**
  102593. * Setup the skybox according to the specified options.
  102594. */
  102595. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  102596. var _this = this;
  102597. if (!this._skybox || this._skybox.isDisposed()) {
  102598. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  102599. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  102600. }
  102601. this._skybox.parent = this._rootMesh;
  102602. };
  102603. /**
  102604. * Setup the skybox material according to the specified options.
  102605. */
  102606. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  102607. if (!this._skybox) {
  102608. return;
  102609. }
  102610. if (!this._skyboxMaterial) {
  102611. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  102612. }
  102613. this._skyboxMaterial.useRGBColor = false;
  102614. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  102615. this._skyboxMaterial.enableNoise = true;
  102616. this._skybox.material = this._skyboxMaterial;
  102617. };
  102618. /**
  102619. * Setup the skybox reflection texture according to the specified options.
  102620. */
  102621. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  102622. if (!this._skyboxMaterial) {
  102623. return;
  102624. }
  102625. if (this._skyboxTexture) {
  102626. return;
  102627. }
  102628. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  102629. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  102630. return;
  102631. }
  102632. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102633. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  102634. this._skyboxTexture.gammaSpace = false;
  102635. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  102636. };
  102637. /**
  102638. * Dispose all the elements created by the Helper.
  102639. */
  102640. EnvironmentHelper.prototype.dispose = function () {
  102641. if (this._groundMaterial) {
  102642. this._groundMaterial.dispose(true, true);
  102643. }
  102644. if (this._skyboxMaterial) {
  102645. this._skyboxMaterial.dispose(true, true);
  102646. }
  102647. this._rootMesh.dispose(false);
  102648. };
  102649. /**
  102650. * Default ground texture URL.
  102651. */
  102652. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  102653. /**
  102654. * Default skybox texture URL.
  102655. */
  102656. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  102657. /**
  102658. * Default environment texture URL.
  102659. */
  102660. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  102661. return EnvironmentHelper;
  102662. }());
  102663. BABYLON.EnvironmentHelper = EnvironmentHelper;
  102664. })(BABYLON || (BABYLON = {}));
  102665. //# sourceMappingURL=babylon.environmentHelper.js.map
  102666. var BABYLON;
  102667. (function (BABYLON) {
  102668. /** Internal class used to store shapes for emitters */
  102669. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  102670. function ParticleSystemSetEmitterCreationOptions() {
  102671. }
  102672. return ParticleSystemSetEmitterCreationOptions;
  102673. }());
  102674. /**
  102675. * Represents a set of particle systems working together to create a specific effect
  102676. */
  102677. var ParticleSystemSet = /** @class */ (function () {
  102678. function ParticleSystemSet() {
  102679. /**
  102680. * Gets the particle system list
  102681. */
  102682. this.systems = new Array();
  102683. }
  102684. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  102685. /**
  102686. * Gets the emitter node used with this set
  102687. */
  102688. get: function () {
  102689. return this._emitterNode;
  102690. },
  102691. enumerable: true,
  102692. configurable: true
  102693. });
  102694. /**
  102695. * Creates a new emitter mesh as a sphere
  102696. * @param options defines the options used to create the sphere
  102697. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  102698. * @param scene defines the hosting scene
  102699. */
  102700. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  102701. if (this._emitterNode) {
  102702. this._emitterNode.dispose();
  102703. }
  102704. this._emitterCreationOptions = {
  102705. kind: "Sphere",
  102706. options: options,
  102707. renderingGroupId: renderingGroupId
  102708. };
  102709. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  102710. emitterMesh.renderingGroupId = renderingGroupId;
  102711. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  102712. material.emissiveColor = options.color;
  102713. emitterMesh.material = material;
  102714. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102715. var system = _a[_i];
  102716. system.emitter = emitterMesh;
  102717. }
  102718. this._emitterNode = emitterMesh;
  102719. };
  102720. /**
  102721. * Starts all particle systems of the set
  102722. * @param emitter defines an optional mesh to use as emitter for the particle systems
  102723. */
  102724. ParticleSystemSet.prototype.start = function (emitter) {
  102725. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102726. var system = _a[_i];
  102727. if (emitter) {
  102728. system.emitter = emitter;
  102729. }
  102730. system.start();
  102731. }
  102732. };
  102733. /**
  102734. * Release all associated resources
  102735. */
  102736. ParticleSystemSet.prototype.dispose = function () {
  102737. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102738. var system = _a[_i];
  102739. system.dispose();
  102740. }
  102741. this.systems = [];
  102742. if (this._emitterNode) {
  102743. this._emitterNode.dispose();
  102744. this._emitterNode = null;
  102745. }
  102746. };
  102747. /**
  102748. * Serialize the set into a JSON compatible object
  102749. * @returns a JSON compatible representation of the set
  102750. */
  102751. ParticleSystemSet.prototype.serialize = function () {
  102752. var result = {};
  102753. result.systems = [];
  102754. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102755. var system = _a[_i];
  102756. result.systems.push(system.serialize());
  102757. }
  102758. if (this._emitterNode) {
  102759. result.emitter = this._emitterCreationOptions;
  102760. }
  102761. return result;
  102762. };
  102763. /**
  102764. * Parse a new ParticleSystemSet from a serialized source
  102765. * @param data defines a JSON compatible representation of the set
  102766. * @param scene defines the hosting scene
  102767. * @param gpu defines if we want GPU particles or CPU particles
  102768. * @returns a new ParticleSystemSet
  102769. */
  102770. ParticleSystemSet.Parse = function (data, scene, gpu) {
  102771. if (gpu === void 0) { gpu = false; }
  102772. var result = new ParticleSystemSet();
  102773. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  102774. scene = scene || BABYLON.Engine.LastCreatedScene;
  102775. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  102776. var system = _a[_i];
  102777. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  102778. }
  102779. if (data.emitter) {
  102780. var options = data.emitter.options;
  102781. switch (data.emitter.kind) {
  102782. case "Sphere":
  102783. result.setEmitterAsSphere({
  102784. diameter: options.diameter,
  102785. segments: options.segments,
  102786. color: BABYLON.Color3.FromArray(options.color)
  102787. }, data.emitter.renderingGroupId, scene);
  102788. break;
  102789. }
  102790. }
  102791. return result;
  102792. };
  102793. return ParticleSystemSet;
  102794. }());
  102795. BABYLON.ParticleSystemSet = ParticleSystemSet;
  102796. })(BABYLON || (BABYLON = {}));
  102797. //# sourceMappingURL=babylon.particleSystemSet.js.map
  102798. var BABYLON;
  102799. (function (BABYLON) {
  102800. /**
  102801. * This class is made for on one-liner static method to help creating particle system set.
  102802. */
  102803. var ParticleHelper = /** @class */ (function () {
  102804. function ParticleHelper() {
  102805. }
  102806. /**
  102807. * This is the main static method (one-liner) of this helper to create different particle systems
  102808. * @param type This string represents the type to the particle system to create
  102809. * @param scene The scene where the particle system should live
  102810. * @param gpu If the system will use gpu
  102811. * @returns the ParticleSystemSet created
  102812. */
  102813. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  102814. if (gpu === void 0) { gpu = false; }
  102815. if (!scene) {
  102816. scene = BABYLON.Engine.LastCreatedScene;
  102817. ;
  102818. }
  102819. var token = {};
  102820. scene._addPendingData(token);
  102821. return new Promise(function (resolve, reject) {
  102822. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  102823. scene._removePendingData(token);
  102824. return reject("Particle system with GPU is not supported.");
  102825. }
  102826. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  102827. scene._removePendingData(token);
  102828. var newData = JSON.parse(data.toString());
  102829. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  102830. }, undefined, undefined, undefined, function (req, exception) {
  102831. scene._removePendingData(token);
  102832. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  102833. });
  102834. });
  102835. };
  102836. /**
  102837. * Static function used to export a particle system to a ParticleSystemSet variable.
  102838. * Please note that the emitter shape is not exported
  102839. * @param system defines the particle systems to export
  102840. */
  102841. ParticleHelper.ExportSet = function (systems) {
  102842. var set = new BABYLON.ParticleSystemSet();
  102843. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  102844. var system = systems_1[_i];
  102845. set.systems.push(system);
  102846. }
  102847. return set;
  102848. };
  102849. /**
  102850. * Gets or sets base Assets URL
  102851. */
  102852. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  102853. return ParticleHelper;
  102854. }());
  102855. BABYLON.ParticleHelper = ParticleHelper;
  102856. })(BABYLON || (BABYLON = {}));
  102857. //# sourceMappingURL=babylon.particleHelper.js.map
  102858. var BABYLON;
  102859. (function (BABYLON) {
  102860. /**
  102861. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  102862. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  102863. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  102864. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102865. */
  102866. var VideoDome = /** @class */ (function (_super) {
  102867. __extends(VideoDome, _super);
  102868. /**
  102869. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  102870. * @param name Element's name, child elements will append suffixes for their own names.
  102871. * @param urlsOrVideo defines the url(s) or the video element to use
  102872. * @param options An object containing optional or exposed sub element properties
  102873. */
  102874. function VideoDome(name, urlsOrVideo, options, scene) {
  102875. var _this = _super.call(this, name, scene) || this;
  102876. _this._useDirectMapping = false;
  102877. // set defaults and manage values
  102878. name = name || "videoDome";
  102879. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102880. options.clickToPlay = Boolean(options.clickToPlay);
  102881. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  102882. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  102883. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102884. if (options.useDirectMapping === undefined) {
  102885. _this._useDirectMapping = true;
  102886. }
  102887. else {
  102888. _this._useDirectMapping = options.useDirectMapping;
  102889. }
  102890. // create
  102891. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  102892. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102893. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  102894. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102895. // configure material
  102896. material.useEquirectangularFOV = true;
  102897. material.fovMultiplier = 1.0;
  102898. material.opacityFresnel = false;
  102899. if (_this._useDirectMapping) {
  102900. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102901. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102902. material.diffuseTexture = texture;
  102903. }
  102904. else {
  102905. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  102906. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102907. material.reflectionTexture = texture;
  102908. }
  102909. // configure mesh
  102910. _this._mesh.material = material;
  102911. _this._mesh.parent = _this;
  102912. // optional configuration
  102913. if (options.clickToPlay) {
  102914. scene.onPointerUp = function () {
  102915. _this._videoTexture.video.play();
  102916. };
  102917. }
  102918. return _this;
  102919. }
  102920. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  102921. /**
  102922. * Gets the video texture being displayed on the sphere
  102923. */
  102924. get: function () {
  102925. return this._videoTexture;
  102926. },
  102927. enumerable: true,
  102928. configurable: true
  102929. });
  102930. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  102931. /**
  102932. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102933. * Also see the options.resolution property.
  102934. */
  102935. get: function () {
  102936. return this._material.fovMultiplier;
  102937. },
  102938. set: function (value) {
  102939. this._material.fovMultiplier = value;
  102940. },
  102941. enumerable: true,
  102942. configurable: true
  102943. });
  102944. /**
  102945. * Releases resources associated with this node.
  102946. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  102947. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  102948. */
  102949. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  102950. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  102951. this._videoTexture.dispose();
  102952. this._mesh.dispose();
  102953. this._material.dispose();
  102954. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  102955. };
  102956. return VideoDome;
  102957. }(BABYLON.Node));
  102958. BABYLON.VideoDome = VideoDome;
  102959. })(BABYLON || (BABYLON = {}));
  102960. //# sourceMappingURL=babylon.videoDome.js.map
  102961. var BABYLON;
  102962. (function (BABYLON) {
  102963. /**
  102964. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  102965. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  102966. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  102967. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102968. */
  102969. var PhotoDome = /** @class */ (function (_super) {
  102970. __extends(PhotoDome, _super);
  102971. /**
  102972. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  102973. * @param name Element's name, child elements will append suffixes for their own names.
  102974. * @param urlsOfPhoto define the url of the photo to display
  102975. * @param options An object containing optional or exposed sub element properties
  102976. */
  102977. function PhotoDome(name, urlOfPhoto, options, scene) {
  102978. var _this = _super.call(this, name, scene) || this;
  102979. _this._useDirectMapping = false;
  102980. // set defaults and manage values
  102981. name = name || "photoDome";
  102982. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102983. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102984. if (options.useDirectMapping === undefined) {
  102985. _this._useDirectMapping = true;
  102986. }
  102987. else {
  102988. _this._useDirectMapping = options.useDirectMapping;
  102989. }
  102990. // create
  102991. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102992. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102993. // configure material
  102994. material.opacityFresnel = false;
  102995. material.useEquirectangularFOV = true;
  102996. material.fovMultiplier = 1.0;
  102997. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  102998. // configure mesh
  102999. _this._mesh.material = material;
  103000. _this._mesh.parent = _this;
  103001. return _this;
  103002. }
  103003. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  103004. /**
  103005. * Gets or sets the texture being displayed on the sphere
  103006. */
  103007. get: function () {
  103008. return this._photoTexture;
  103009. },
  103010. set: function (value) {
  103011. if (this._photoTexture === value) {
  103012. return;
  103013. }
  103014. this._photoTexture = value;
  103015. if (this._useDirectMapping) {
  103016. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103017. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103018. this._material.diffuseTexture = this._photoTexture;
  103019. }
  103020. else {
  103021. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103022. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103023. this._material.reflectionTexture = this._photoTexture;
  103024. }
  103025. },
  103026. enumerable: true,
  103027. configurable: true
  103028. });
  103029. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  103030. /**
  103031. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103032. * Also see the options.resolution property.
  103033. */
  103034. get: function () {
  103035. return this._material.fovMultiplier;
  103036. },
  103037. set: function (value) {
  103038. this._material.fovMultiplier = value;
  103039. },
  103040. enumerable: true,
  103041. configurable: true
  103042. });
  103043. /**
  103044. * Releases resources associated with this node.
  103045. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103046. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103047. */
  103048. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103049. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103050. this._photoTexture.dispose();
  103051. this._mesh.dispose();
  103052. this._material.dispose();
  103053. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103054. };
  103055. return PhotoDome;
  103056. }(BABYLON.Node));
  103057. BABYLON.PhotoDome = PhotoDome;
  103058. })(BABYLON || (BABYLON = {}));
  103059. //# sourceMappingURL=babylon.photoDome.js.map
  103060. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin 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 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(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(age/life,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(age/life,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","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  103061. 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};"};
  103062. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  103063. globalObject["BABYLON"] = BABYLON;
  103064. //backwards compatibility
  103065. if(typeof earcut !== 'undefined') {
  103066. globalObject["Earcut"] = {
  103067. earcut: earcut
  103068. };
  103069. }
  103070. return BABYLON;
  103071. });
  103072. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))
  103073. /***/ }),
  103074. /* 1 */
  103075. /***/ (function(module, exports, __webpack_require__) {
  103076. "use strict";
  103077. Object.defineProperty(exports, "__esModule", { value: true });
  103078. var deepmerge = __webpack_require__(23);
  103079. var expDm = deepmerge['default'];
  103080. exports.deepmerge = expDm;
  103081. /**
  103082. * Is the provided string a URL?
  103083. *
  103084. * @param urlToCheck the url to inspect
  103085. */
  103086. function isUrl(urlToCheck) {
  103087. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  103088. return true;
  103089. }
  103090. return false;
  103091. }
  103092. exports.isUrl = isUrl;
  103093. /**
  103094. * Convert a string from kebab-case to camelCase
  103095. * @param s string to convert
  103096. */
  103097. function kebabToCamel(s) {
  103098. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  103099. }
  103100. exports.kebabToCamel = kebabToCamel;
  103101. //https://gist.github.com/youssman/745578062609e8acac9f
  103102. /**
  103103. * Convert a string from camelCase to kebab-case
  103104. * @param str string to convert
  103105. */
  103106. function camelToKebab(str) {
  103107. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  103108. }
  103109. exports.camelToKebab = camelToKebab;
  103110. /**
  103111. * This will extend an object with configuration values.
  103112. * What it practically does it take the keys from the configuration and set them on the object.
  103113. * I the configuration is a tree, it will traverse into the tree.
  103114. * @param object the object to extend
  103115. * @param config the configuration object that will extend the object
  103116. */
  103117. function extendClassWithConfig(object, config) {
  103118. if (!config)
  103119. return;
  103120. Object.keys(config).forEach(function (key) {
  103121. if (key in object && typeof object[key] !== 'function') {
  103122. // if (typeof object[key] === 'function') return;
  103123. // if it is an object, iterate internally until reaching basic types
  103124. if (typeof object[key] === 'object') {
  103125. extendClassWithConfig(object[key], config[key]);
  103126. }
  103127. else {
  103128. if (config[key] !== undefined) {
  103129. object[key] = config[key];
  103130. }
  103131. }
  103132. }
  103133. });
  103134. }
  103135. exports.extendClassWithConfig = extendClassWithConfig;
  103136. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvaGVscGVyL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQXVDO0FBRXZDLElBQUksS0FBSyxHQUFHLFNBQVMsQ0FBQyxTQUFTLENBQUMsQ0FBQztBQUNmLDBCQUFTO0FBRTNCOzs7O0dBSUc7QUFDSCxlQUFzQixVQUFrQjtJQUNwQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FB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RyxDQUFDLEtBQUssUUFBUSxFQUFFO2dCQUNqQyxxQkFBcUIsQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLEVBQUUsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUM7YUFDbkQ7aUJBQU07Z0JBQ0gsSUFBSSxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO29CQUMzQixNQUFNLENBQUMsR0FBRyxDQUFDLEdBQUcsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDO2lCQUM3QjthQUNKO1NBQ0o7SUFDTCxDQUFDLENBQUMsQ0FBQztBQUNQLENBQUM7QUFmRCxzREFlQyJ9
  103137. /***/ }),
  103138. /* 2 */
  103139. /***/ (function(module, exports, __webpack_require__) {
  103140. "use strict";
  103141. function __export(m) {
  103142. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  103143. }
  103144. Object.defineProperty(exports, "__esModule", { value: true });
  103145. __export(__webpack_require__(33));
  103146. __export(__webpack_require__(35));
  103147. __export(__webpack_require__(41));
  103148. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvYXNzZXRzL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsNEJBQXVCO0FBQ3ZCLDJCQUFzQjtBQUN0QixpQ0FBNEIifQ==
  103149. /***/ }),
  103150. /* 3 */
  103151. /***/ (function(module, exports, __webpack_require__) {
  103152. "use strict";
  103153. Object.defineProperty(exports, "__esModule", { value: true });
  103154. var babylonjs_1 = __webpack_require__(0);
  103155. var _1 = __webpack_require__(1);
  103156. /**
  103157. * This is a simple HTML mapper.
  103158. * This mapper parses a single HTML element and returns the configuration from its attributes.
  103159. * it parses numbers and boolean values to the corresponding variable types.
  103160. * The following HTML element:
  103161. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  103162. *
  103163. * {
  103164. * test: 1, //a number!
  103165. * randomFlag: boolean, //camelCase and boolean
  103166. * a: {
  103167. * string: {
  103168. * object: "test" //dot-separated object levels
  103169. * }
  103170. * }
  103171. * }
  103172. */
  103173. var HTMLMapper = /** @class */ (function () {
  103174. function HTMLMapper() {
  103175. }
  103176. /**
  103177. * Map a specific element and get configuration from it
  103178. * @param element the HTML element to analyze.
  103179. */
  103180. HTMLMapper.prototype.map = function (element) {
  103181. var config = {};
  103182. var _loop_1 = function (attrIdx) {
  103183. var attr = element.attributes.item(attrIdx);
  103184. if (!attr) {
  103185. return "continue";
  103186. }
  103187. // map "object.property" to the right configuration place.
  103188. var split = attr.nodeName.split('.');
  103189. split.reduce(function (currentConfig, key, idx) {
  103190. //convert html-style to json-style
  103191. var camelKey = _1.kebabToCamel(key);
  103192. if (idx === split.length - 1) {
  103193. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  103194. if (val === "true") {
  103195. val = true;
  103196. }
  103197. else if (val === "false") {
  103198. val = false;
  103199. }
  103200. else if (val === "undefined") {
  103201. val = undefined;
  103202. }
  103203. else if (val === "null") {
  103204. val = null;
  103205. }
  103206. else {
  103207. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  103208. if (isnum) {
  103209. var number = parseFloat(val);
  103210. if (!isNaN(number)) {
  103211. val = number;
  103212. }
  103213. }
  103214. }
  103215. currentConfig[camelKey] = val;
  103216. }
  103217. else {
  103218. currentConfig[camelKey] = currentConfig[camelKey] || {};
  103219. }
  103220. return currentConfig[camelKey];
  103221. }, config);
  103222. };
  103223. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  103224. _loop_1(attrIdx);
  103225. }
  103226. return config;
  103227. };
  103228. return HTMLMapper;
  103229. }());
  103230. /**
  103231. * A simple string-to-JSON mapper.
  103232. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  103233. */
  103234. var JSONMapper = /** @class */ (function () {
  103235. function JSONMapper() {
  103236. }
  103237. JSONMapper.prototype.map = function (rawSource) {
  103238. return JSON.parse(rawSource);
  103239. };
  103240. return JSONMapper;
  103241. }());
  103242. /**
  103243. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  103244. * DOM elements and attributes.
  103245. */
  103246. var DOMMapper = /** @class */ (function () {
  103247. function DOMMapper() {
  103248. }
  103249. /**
  103250. * The mapping function that will convert HTML data to a viewer configuration object
  103251. * @param baseElement the baseElement from which to start traversing
  103252. * @returns a ViewerCOnfiguration object from the provided HTML Element
  103253. */
  103254. DOMMapper.prototype.map = function (baseElement) {
  103255. var htmlMapper = new HTMLMapper();
  103256. var config = htmlMapper.map(baseElement);
  103257. var traverseChildren = function (element, partConfig) {
  103258. var children = element.children;
  103259. if (children.length) {
  103260. for (var i = 0; i < children.length; ++i) {
  103261. var item = children.item(i);
  103262. // use the HTML Mapper to read configuration from a single element
  103263. var configMapped = htmlMapper.map(item);
  103264. var key = _1.kebabToCamel(item.nodeName.toLowerCase());
  103265. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  103266. partConfig[key] = [];
  103267. }
  103268. else {
  103269. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  103270. partConfig.push(configMapped);
  103271. }
  103272. else if (partConfig[key]) {
  103273. //exists already! probably an array
  103274. element.setAttribute('array', 'true');
  103275. var oldItem = partConfig[key];
  103276. partConfig = [oldItem, configMapped];
  103277. }
  103278. else {
  103279. partConfig[key] = configMapped;
  103280. }
  103281. }
  103282. traverseChildren(item, partConfig[key] || configMapped);
  103283. }
  103284. }
  103285. return partConfig;
  103286. };
  103287. traverseChildren(baseElement, config);
  103288. return config;
  103289. };
  103290. return DOMMapper;
  103291. }());
  103292. /**
  103293. * The MapperManager manages the different implemented mappers.
  103294. * It allows the user to register new mappers as well and use them to parse their own configuration data
  103295. */
  103296. var MapperManager = /** @class */ (function () {
  103297. function MapperManager() {
  103298. this._mappers = {
  103299. "html": new HTMLMapper(),
  103300. "json": new JSONMapper(),
  103301. "dom": new DOMMapper()
  103302. };
  103303. }
  103304. /**
  103305. * Get a specific configuration mapper.
  103306. *
  103307. * @param type the name of the mapper to load
  103308. */
  103309. MapperManager.prototype.getMapper = function (type) {
  103310. if (!this._mappers[type]) {
  103311. babylonjs_1.Tools.Error("No mapper defined for " + type);
  103312. }
  103313. return this._mappers[type];
  103314. };
  103315. /**
  103316. * Use this functio to register your own configuration mapper.
  103317. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  103318. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  103319. * @param mapper The implemented mapper
  103320. */
  103321. MapperManager.prototype.registerMapper = function (type, mapper) {
  103322. this._mappers[type] = mapper;
  103323. };
  103324. /**
  103325. * Dispose the mapper manager and all of its mappers.
  103326. */
  103327. MapperManager.prototype.dispose = function () {
  103328. this._mappers = {};
  103329. };
  103330. /**
  103331. * The default mapper is the JSON mapper.
  103332. */
  103333. MapperManager.DefaultMapper = 'json';
  103334. return MapperManager;
  103335. }());
  103336. exports.MapperManager = MapperManager;
  103337. /**
  103338. * mapperManager is a singleton of the type MapperManager.
  103339. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  103340. * or indirectly with using BabylonViewer.disposeAll()
  103341. */
  103342. exports.mapperManager = new MapperManager();
  103343. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFwcGVycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL21hcHBlcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBa0M7QUFHbEMsK0JBQTBDO0FBUzFDOzs7Ozs7Ozs7Ozs7Ozs7O0dBZ0JHO0FBQ0g7SUFBQTtJQWdEQS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Q0FBUyxHQUFoQixVQUFpQixJQUFZO1FBQ3pCLElBQUksQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxFQUFFO1lBQ3RCLGlCQUFLLENBQUMsS0FBSyxDQUFDLHdCQUF3QixHQUFHLElBQUksQ0FBQyxDQUFDO1NBQ2hEO1FBQ0QsT0FBTyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQy9CLENBQUM7SUFFRDs7Ozs7T0FLRztJQUNJLHNDQUFjLEdBQXJCLFVBQXNCLElBQVksRUFBRSxNQUFlO1FBQy9DLElBQUksQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLEdBQUcsTUFBTSxDQUFDO0lBQ2pDLENBQUM7SUFFRDs7T0FFRztJQUNJLCtCQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsUUFBUSxHQUFHLEVBQUUsQ0FBQztJQUN2QixDQUFDO0lBeENEOztPQUVHO0lBQ1csMkJBQWEsR0FBRyxNQUFNLENBQUM7SUF1Q3pDLG9CQUFDO0NBQUEsQUE3Q0QsSUE2Q0M7QUE3Q1ksc0NBQWE7QUErQzFCOzs7O0dBSUc7QUFDUSxRQUFBLGFBQWEsR0FBRyxJQUFJLGFBQWEsRUFBRSxDQUFDIn0=
  103344. /***/ }),
  103345. /* 4 */
  103346. /***/ (function(module, exports, __webpack_require__) {
  103347. "use strict";
  103348. Object.defineProperty(exports, "__esModule", { value: true });
  103349. var babylonjs_1 = __webpack_require__(0);
  103350. var ViewerGlobals = /** @class */ (function () {
  103351. function ViewerGlobals() {
  103352. this.disableInit = false;
  103353. this.disableWebGL2Support = false;
  103354. }
  103355. Object.defineProperty(ViewerGlobals.prototype, "version", {
  103356. get: function () {
  103357. return babylonjs_1.Engine.Version;
  103358. },
  103359. enumerable: true,
  103360. configurable: true
  103361. });
  103362. return ViewerGlobals;
  103363. }());
  103364. exports.ViewerGlobals = ViewerGlobals;
  103365. exports.viewerGlobals = new ViewerGlobals();
  103366. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFscy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2dsb2JhbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQUVXLGdCQUFXLEdBQVksS0FBSyxDQUFDO1FBQzdCLHlCQUFvQixHQUFZLEtBQUssQ0FBQztJQU1qRCxDQUFDO0lBSkcsc0JBQVcsa0NBQU87YUFBbEI7WUFDSSxPQUFPLGtCQUFNLENBQUMsT0FBTyxDQUFDO1FBQzFCLENBQUM7OztPQUFBO0lBRUwsb0JBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHNDQUFhO0FBV2YsUUFBQSxhQUFhLEdBQWtCLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  103367. /***/ }),
  103368. /* 5 */
  103369. /***/ (function(module, exports, __webpack_require__) {
  103370. "use strict";
  103371. Object.defineProperty(exports, "__esModule", { value: true });
  103372. var babylonjs_1 = __webpack_require__(0);
  103373. var modelAnimation_1 = __webpack_require__(25);
  103374. var _1 = __webpack_require__(1);
  103375. /**
  103376. * The current state of the model
  103377. */
  103378. var ModelState;
  103379. (function (ModelState) {
  103380. ModelState[ModelState["INIT"] = 0] = "INIT";
  103381. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  103382. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  103383. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  103384. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  103385. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  103386. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  103387. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  103388. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  103389. /**
  103390. * The viewer model is a container for all assets representing a sngle loaded model.
  103391. */
  103392. var ViewerModel = /** @class */ (function () {
  103393. function ViewerModel(_observablesManager, modelConfiguration, _configurationContainer) {
  103394. var _this = this;
  103395. this._observablesManager = _observablesManager;
  103396. this._configurationContainer = _configurationContainer;
  103397. /**
  103398. * the list of meshes that are a part of this model
  103399. */
  103400. this._meshes = [];
  103401. /**
  103402. * ParticleSystems connected to this model
  103403. */
  103404. this.particleSystems = [];
  103405. /**
  103406. * Skeletons defined in this model
  103407. */
  103408. this.skeletons = [];
  103409. this._loaderDone = false;
  103410. this._animatables = [];
  103411. this._frameRate = 60;
  103412. this._shadowsRenderedAfterLoad = false;
  103413. this.onLoadedObservable = new babylonjs_1.Observable();
  103414. this.onLoadErrorObservable = new babylonjs_1.Observable();
  103415. this.onLoadProgressObservable = new babylonjs_1.Observable();
  103416. this.onCompleteObservable = new babylonjs_1.Observable();
  103417. this.onAfterConfigure = new babylonjs_1.Observable();
  103418. this.state = ModelState.INIT;
  103419. var scene = this._configurationContainer && this._configurationContainer.scene;
  103420. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", scene);
  103421. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", scene);
  103422. this._pivotMesh.parent = this.rootMesh;
  103423. // rotate 180, gltf fun
  103424. this._pivotMesh.rotation.y += Math.PI;
  103425. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  103426. this._animations = [];
  103427. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  103428. this._modelConfiguration = _1.deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration);
  103429. if (this._observablesManager) {
  103430. this._observablesManager.onModelAddedObservable.notifyObservers(this);
  103431. }
  103432. if (this._modelConfiguration.entryAnimation) {
  103433. this.rootMesh.setEnabled(false);
  103434. }
  103435. this.onLoadedObservable.add(function () {
  103436. _this.updateConfiguration(_this._modelConfiguration);
  103437. if (_this._observablesManager) {
  103438. _this._observablesManager.onModelLoadedObservable.notifyObservers(_this);
  103439. }
  103440. _this._initAnimations();
  103441. });
  103442. this.onCompleteObservable.add(function () {
  103443. _this.state = ModelState.COMPLETE;
  103444. });
  103445. }
  103446. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  103447. get: function () {
  103448. return this._shadowsRenderedAfterLoad;
  103449. },
  103450. set: function (rendered) {
  103451. if (!rendered) {
  103452. throw new Error("can only be enabled");
  103453. }
  103454. else {
  103455. this._shadowsRenderedAfterLoad = rendered;
  103456. }
  103457. },
  103458. enumerable: true,
  103459. configurable: true
  103460. });
  103461. ViewerModel.prototype.getViewerId = function () {
  103462. return this._configurationContainer && this._configurationContainer.viewerId;
  103463. };
  103464. Object.defineProperty(ViewerModel.prototype, "enabled", {
  103465. /**
  103466. * Is this model enabled?
  103467. */
  103468. get: function () {
  103469. return this.rootMesh.isEnabled();
  103470. },
  103471. /**
  103472. * Set whether this model is enabled or not.
  103473. */
  103474. set: function (enable) {
  103475. this.rootMesh.setEnabled(enable);
  103476. },
  103477. enumerable: true,
  103478. configurable: true
  103479. });
  103480. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  103481. set: function (done) {
  103482. this._loaderDone = done;
  103483. this._checkCompleteState();
  103484. },
  103485. enumerable: true,
  103486. configurable: true
  103487. });
  103488. ViewerModel.prototype._checkCompleteState = function () {
  103489. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  103490. this._modelComplete();
  103491. }
  103492. };
  103493. /**
  103494. * Add a mesh to this model.
  103495. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  103496. *
  103497. * @param mesh the new mesh to add
  103498. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  103499. */
  103500. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  103501. if (!mesh.parent) {
  103502. mesh.parent = this._pivotMesh;
  103503. }
  103504. mesh.receiveShadows = !!this.configuration.receiveShadows;
  103505. this._meshes.push(mesh);
  103506. if (triggerLoaded) {
  103507. return this.onLoadedObservable.notifyObserversWithPromise(this);
  103508. }
  103509. };
  103510. Object.defineProperty(ViewerModel.prototype, "meshes", {
  103511. /**
  103512. * get the list of meshes (excluding the root mesh)
  103513. */
  103514. get: function () {
  103515. return this._meshes;
  103516. },
  103517. enumerable: true,
  103518. configurable: true
  103519. });
  103520. Object.defineProperty(ViewerModel.prototype, "configuration", {
  103521. /**
  103522. * Get the model's configuration
  103523. */
  103524. get: function () {
  103525. return this._modelConfiguration;
  103526. },
  103527. /**
  103528. * (Re-)set the model's entire configuration
  103529. * @param newConfiguration the new configuration to replace the new one
  103530. */
  103531. set: function (newConfiguration) {
  103532. this._modelConfiguration = newConfiguration;
  103533. this._configureModel();
  103534. },
  103535. enumerable: true,
  103536. configurable: true
  103537. });
  103538. /**
  103539. * Update the current configuration with new values.
  103540. * Configuration will not be overwritten, but merged with the new configuration.
  103541. * Priority is to the new configuration
  103542. * @param newConfiguration the configuration to be merged into the current configuration;
  103543. */
  103544. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  103545. this._modelConfiguration = _1.deepmerge(this._modelConfiguration, newConfiguration);
  103546. this._configureModel();
  103547. };
  103548. ViewerModel.prototype._initAnimations = function () {
  103549. var _this = this;
  103550. // check if this is not a gltf loader and init the animations
  103551. if (this.skeletons.length) {
  103552. this.skeletons.forEach(function (skeleton, idx) {
  103553. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._configurationContainer && _this._configurationContainer.scene);
  103554. var add = false;
  103555. skeleton.getAnimatables().forEach(function (a) {
  103556. if (a.animations[0]) {
  103557. ag.addTargetedAnimation(a.animations[0], a);
  103558. add = true;
  103559. }
  103560. });
  103561. if (add) {
  103562. _this.addAnimationGroup(ag);
  103563. }
  103564. });
  103565. }
  103566. var completeCallback = function () {
  103567. };
  103568. if (this._modelConfiguration.animation) {
  103569. if (this._modelConfiguration.animation.playOnce) {
  103570. this._animations.forEach(function (a) {
  103571. a.playMode = 0 /* ONCE */;
  103572. });
  103573. }
  103574. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  103575. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  103576. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  103577. completeCallback = function () {
  103578. _this.playAnimation(animationName_1);
  103579. };
  103580. }
  103581. }
  103582. this._enterScene(completeCallback);
  103583. };
  103584. /**
  103585. * Animates the model from the current position to the default position
  103586. * @param completeCallback A function to call when the animation has completed
  103587. */
  103588. ViewerModel.prototype._enterScene = function (completeCallback) {
  103589. var _this = this;
  103590. var scene = this.rootMesh.getScene();
  103591. var previousValue = scene.animationPropertiesOverride.enableBlending;
  103592. var callback = function () {
  103593. _this.state = ModelState.ENTRYDONE;
  103594. scene.animationPropertiesOverride.enableBlending = previousValue;
  103595. _this._checkCompleteState();
  103596. if (completeCallback)
  103597. completeCallback();
  103598. };
  103599. if (!this._entryAnimation) {
  103600. callback();
  103601. return;
  103602. }
  103603. this.rootMesh.setEnabled(true);
  103604. // disable blending for the sake of the entry animation;
  103605. scene.animationPropertiesOverride.enableBlending = false;
  103606. this._applyAnimation(this._entryAnimation, true, callback);
  103607. };
  103608. /**
  103609. * Animates the model from the current position to the exit-screen position
  103610. * @param completeCallback A function to call when the animation has completed
  103611. */
  103612. ViewerModel.prototype._exitScene = function (completeCallback) {
  103613. if (!this._exitAnimation) {
  103614. completeCallback();
  103615. return;
  103616. }
  103617. this._applyAnimation(this._exitAnimation, false, completeCallback);
  103618. };
  103619. ViewerModel.prototype._modelComplete = function () {
  103620. var _this = this;
  103621. //reapply material defines to be sure:
  103622. var meshes = this._pivotMesh.getChildMeshes(false);
  103623. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  103624. _this._applyModelMaterialConfiguration(mesh.material);
  103625. });
  103626. this.state = ModelState.COMPLETE;
  103627. this.onCompleteObservable.notifyObservers(this);
  103628. };
  103629. /**
  103630. * Add a new animation group to this model.
  103631. * @param animationGroup the new animation group to be added
  103632. */
  103633. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  103634. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  103635. };
  103636. /**
  103637. * Get the ModelAnimation array
  103638. */
  103639. ViewerModel.prototype.getAnimations = function () {
  103640. return this._animations;
  103641. };
  103642. /**
  103643. * Get the animations' names. Using the names you can play a specific animation.
  103644. */
  103645. ViewerModel.prototype.getAnimationNames = function () {
  103646. return this._animations.map(function (a) { return a.name; });
  103647. };
  103648. /**
  103649. * Get an animation by the provided name. Used mainly when playing n animation.
  103650. * @param name the name of the animation to find
  103651. */
  103652. ViewerModel.prototype._getAnimationByName = function (name) {
  103653. // can't use .find, noe available on IE
  103654. var filtered = this._animations.filter(function (a) { return a.name === name; });
  103655. // what the next line means - if two animations have the same name, they will not be returned!
  103656. if (filtered.length === 1) {
  103657. return filtered[0];
  103658. }
  103659. else {
  103660. return null;
  103661. }
  103662. };
  103663. /**
  103664. * Choose an initialized animation using its name and start playing it
  103665. * @param name the name of the animation to play
  103666. * @returns The model aniamtion to be played.
  103667. */
  103668. ViewerModel.prototype.playAnimation = function (name) {
  103669. var animation = this.setCurrentAnimationByName(name);
  103670. if (animation) {
  103671. animation.start();
  103672. }
  103673. return animation;
  103674. };
  103675. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  103676. var animation = this._getAnimationByName(name);
  103677. if (animation) {
  103678. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  103679. this.currentAnimation.stop();
  103680. }
  103681. this.currentAnimation = animation;
  103682. return animation;
  103683. }
  103684. else {
  103685. throw new Error("animation not found - " + name);
  103686. }
  103687. };
  103688. ViewerModel.prototype._configureModel = function () {
  103689. var _this = this;
  103690. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  103691. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  103692. var updateMeshesWithNoParent = function (variable, value, param) {
  103693. meshesWithNoParent.forEach(function (mesh) {
  103694. if (param) {
  103695. mesh[variable][param] = value;
  103696. }
  103697. else {
  103698. mesh[variable] = value;
  103699. }
  103700. });
  103701. };
  103702. var updateXYZ = function (variable, configValues) {
  103703. if (configValues.x !== undefined) {
  103704. updateMeshesWithNoParent(variable, configValues.x, 'x');
  103705. }
  103706. if (configValues.y !== undefined) {
  103707. updateMeshesWithNoParent(variable, configValues.y, 'y');
  103708. }
  103709. if (configValues.z !== undefined) {
  103710. updateMeshesWithNoParent(variable, configValues.z, 'z');
  103711. }
  103712. if (configValues.w !== undefined) {
  103713. updateMeshesWithNoParent(variable, configValues.w, 'w');
  103714. }
  103715. };
  103716. if (this._modelConfiguration.normalize) {
  103717. var center = false;
  103718. var unitSize = false;
  103719. var parentIndex = void 0;
  103720. if (this._modelConfiguration.normalize === true) {
  103721. center = true;
  103722. unitSize = true;
  103723. }
  103724. else {
  103725. center = !!this._modelConfiguration.normalize.center;
  103726. unitSize = !!this._modelConfiguration.normalize.unitSize;
  103727. parentIndex = this._modelConfiguration.normalize.parentIndex;
  103728. }
  103729. var meshesToNormalize = [];
  103730. if (parentIndex !== undefined) {
  103731. meshesToNormalize.push(this._meshes[parentIndex]);
  103732. }
  103733. else {
  103734. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  103735. }
  103736. if (unitSize) {
  103737. meshesToNormalize.forEach(function (mesh) {
  103738. mesh.normalizeToUnitCube(true);
  103739. mesh.computeWorldMatrix(true);
  103740. });
  103741. }
  103742. if (center) {
  103743. meshesToNormalize.forEach(function (mesh) {
  103744. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  103745. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  103746. var halfSizeVec = sizeVec.scale(0.5);
  103747. var center = boundingInfo.min.add(halfSizeVec);
  103748. mesh.position = center.scale(-1);
  103749. mesh.position.y += halfSizeVec.y;
  103750. // Recompute Info.
  103751. mesh.computeWorldMatrix(true);
  103752. });
  103753. }
  103754. }
  103755. else {
  103756. // if centered, should be done here
  103757. }
  103758. // position?
  103759. if (this._modelConfiguration.position) {
  103760. updateXYZ('position', this._modelConfiguration.position);
  103761. }
  103762. if (this._modelConfiguration.rotation) {
  103763. //quaternion?
  103764. if (this._modelConfiguration.rotation.w) {
  103765. meshesWithNoParent.forEach(function (mesh) {
  103766. if (!mesh.rotationQuaternion) {
  103767. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  103768. }
  103769. });
  103770. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  103771. }
  103772. else {
  103773. updateXYZ('rotation', this._modelConfiguration.rotation);
  103774. }
  103775. }
  103776. if (this._modelConfiguration.rotationOffsetAxis) {
  103777. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  103778. meshesWithNoParent.forEach(function (m) {
  103779. if (_this._modelConfiguration.rotationOffsetAngle) {
  103780. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  103781. }
  103782. });
  103783. }
  103784. if (this._modelConfiguration.scaling) {
  103785. updateXYZ('scaling', this._modelConfiguration.scaling);
  103786. }
  103787. if (this._modelConfiguration.castShadow) {
  103788. this._meshes.forEach(function (mesh) {
  103789. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  103790. });
  103791. }
  103792. var meshes = this._pivotMesh.getChildMeshes(false);
  103793. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  103794. _this._applyModelMaterialConfiguration(mesh.material);
  103795. });
  103796. if (this._modelConfiguration.entryAnimation) {
  103797. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  103798. }
  103799. if (this._modelConfiguration.exitAnimation) {
  103800. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  103801. }
  103802. this.onAfterConfigure.notifyObservers(this);
  103803. };
  103804. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  103805. var anim = {
  103806. time: 0.5
  103807. };
  103808. if (animConfig.scaling) {
  103809. anim.scaling = babylonjs_1.Vector3.Zero();
  103810. }
  103811. if (animConfig.easingFunction !== undefined) {
  103812. anim.easingFunction = animConfig.easingFunction;
  103813. }
  103814. if (animConfig.easingMode !== undefined) {
  103815. anim.easingMode = animConfig.easingMode;
  103816. }
  103817. _1.extendClassWithConfig(anim, animConfig);
  103818. return anim;
  103819. };
  103820. /**
  103821. * Apply a material configuration to a material
  103822. * @param material Material to apply configuration to
  103823. */
  103824. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  103825. if (!this._modelConfiguration.material)
  103826. return;
  103827. _1.extendClassWithConfig(material, this._modelConfiguration.material);
  103828. if (material instanceof babylonjs_1.PBRMaterial) {
  103829. if (this._modelConfiguration.material.directIntensity !== undefined) {
  103830. material.directIntensity = this._modelConfiguration.material.directIntensity;
  103831. }
  103832. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  103833. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  103834. }
  103835. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  103836. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  103837. }
  103838. if (this._modelConfiguration.material.directEnabled !== undefined) {
  103839. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  103840. }
  103841. if (this._configurationContainer && this._configurationContainer.reflectionColor) {
  103842. material.reflectionColor = this._configurationContainer.reflectionColor;
  103843. }
  103844. }
  103845. else if (material instanceof babylonjs_1.MultiMaterial) {
  103846. for (var i = 0; i < material.subMaterials.length; i++) {
  103847. var subMaterial = material.subMaterials[i];
  103848. if (subMaterial) {
  103849. this._applyModelMaterialConfiguration(subMaterial);
  103850. }
  103851. }
  103852. }
  103853. };
  103854. /**
  103855. * Start entry/exit animation given an animation configuration
  103856. * @param animationConfiguration Entry/Exit animation configuration
  103857. * @param isEntry Pass true if the animation is an entry animation
  103858. * @param completeCallback Callback to execute when the animation completes
  103859. */
  103860. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  103861. var animations = [];
  103862. //scale
  103863. if (animationConfiguration.scaling) {
  103864. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  103865. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  103866. if (!scaleStart.equals(scaleEnd)) {
  103867. this.rootMesh.scaling = scaleStart;
  103868. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  103869. animations.push(this._scaleTransition);
  103870. }
  103871. }
  103872. //Start the animation(s)
  103873. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  103874. completeCallback(); });
  103875. };
  103876. /**
  103877. * Begin @animations with the specified @easingFunction
  103878. * @param animations The BABYLON Animations to begin
  103879. * @param duration of transition, in seconds
  103880. * @param easingFunction An easing function to apply
  103881. * @param easingMode A easing mode to apply to the easingFunction
  103882. * @param onAnimationEnd Call back trigger at the end of the animation.
  103883. */
  103884. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  103885. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  103886. if (easingFunction) {
  103887. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  103888. var animation = animations_1[_i];
  103889. easingFunction.setEasingMode(easingMode);
  103890. animation.setEasingFunction(easingFunction);
  103891. }
  103892. }
  103893. //Stop any current animations before starting the new one - merging not yet supported.
  103894. this.stopAllAnimations();
  103895. this.rootMesh.animations = animations;
  103896. if (this.rootMesh.getScene().beginAnimation) {
  103897. var animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  103898. if (onAnimationEnd) {
  103899. onAnimationEnd();
  103900. }
  103901. });
  103902. this._animatables.push(animatable);
  103903. }
  103904. };
  103905. /**
  103906. * Sets key values on an Animation from first to last frame.
  103907. * @param animation The Babylon animation object to set keys on
  103908. * @param startValue The value of the first key
  103909. * @param endValue The value of the last key
  103910. * @param duration The duration of the animation, used to determine the end frame
  103911. */
  103912. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  103913. animation.setKeys([
  103914. {
  103915. frame: 0,
  103916. value: startValue
  103917. },
  103918. {
  103919. frame: this._frameRate * duration,
  103920. value: endValue
  103921. }
  103922. ]);
  103923. };
  103924. /**
  103925. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  103926. * @param easingFunctionID The enum of the easing funtion to create
  103927. * @return The newly created Babylon easing function object
  103928. */
  103929. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  103930. var easingFunction;
  103931. switch (easingFunctionID) {
  103932. case 1 /* CircleEase */:
  103933. easingFunction = new babylonjs_1.CircleEase();
  103934. break;
  103935. case 2 /* BackEase */:
  103936. easingFunction = new babylonjs_1.BackEase(0.3);
  103937. break;
  103938. case 3 /* BounceEase */:
  103939. easingFunction = new babylonjs_1.BounceEase();
  103940. break;
  103941. case 4 /* CubicEase */:
  103942. easingFunction = new babylonjs_1.CubicEase();
  103943. break;
  103944. case 5 /* ElasticEase */:
  103945. easingFunction = new babylonjs_1.ElasticEase();
  103946. break;
  103947. case 6 /* ExponentialEase */:
  103948. easingFunction = new babylonjs_1.ExponentialEase();
  103949. break;
  103950. case 7 /* PowerEase */:
  103951. easingFunction = new babylonjs_1.PowerEase();
  103952. break;
  103953. case 8 /* QuadraticEase */:
  103954. easingFunction = new babylonjs_1.QuadraticEase();
  103955. break;
  103956. case 9 /* QuarticEase */:
  103957. easingFunction = new babylonjs_1.QuarticEase();
  103958. break;
  103959. case 10 /* QuinticEase */:
  103960. easingFunction = new babylonjs_1.QuinticEase();
  103961. break;
  103962. case 11 /* SineEase */:
  103963. easingFunction = new babylonjs_1.SineEase();
  103964. break;
  103965. default:
  103966. babylonjs_1.Tools.Log("No ease function found");
  103967. break;
  103968. }
  103969. return easingFunction;
  103970. };
  103971. /**
  103972. * Stops and removes all animations that have been applied to the model
  103973. */
  103974. ViewerModel.prototype.stopAllAnimations = function () {
  103975. if (this.rootMesh) {
  103976. this.rootMesh.animations = [];
  103977. }
  103978. if (this.currentAnimation) {
  103979. this.currentAnimation.stop();
  103980. }
  103981. while (this._animatables.length) {
  103982. this._animatables[0].onAnimationEnd = null;
  103983. this._animatables[0].stop();
  103984. this._animatables.shift();
  103985. }
  103986. };
  103987. /**
  103988. * Will remove this model from the viewer (but NOT dispose it).
  103989. */
  103990. ViewerModel.prototype.remove = function () {
  103991. this.stopAllAnimations();
  103992. // hide it
  103993. this.rootMesh.isVisible = false;
  103994. if (this._observablesManager) {
  103995. this._observablesManager.onModelRemovedObservable.notifyObservers(this);
  103996. }
  103997. };
  103998. /**
  103999. * Dispose this model, including all of its associated assets.
  104000. */
  104001. ViewerModel.prototype.dispose = function () {
  104002. this.remove();
  104003. this.onAfterConfigure.clear();
  104004. this.onLoadedObservable.clear();
  104005. this.onLoadErrorObservable.clear();
  104006. this.onLoadProgressObservable.clear();
  104007. if (this.loader && this.loader.name === "gltf") {
  104008. this.loader.dispose();
  104009. }
  104010. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  104011. this.particleSystems.length = 0;
  104012. this.skeletons.forEach(function (s) { return s.dispose(); });
  104013. this.skeletons.length = 0;
  104014. this._animations.forEach(function (ag) { return ag.dispose(); });
  104015. this._animations.length = 0;
  104016. this.rootMesh.dispose(false, true);
  104017. };
  104018. return ViewerModel;
  104019. }());
  104020. exports.ViewerModel = ViewerModel;
  104021. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTW9kZWwuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvdmlld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UFBSSxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQyxDQUFDO0lBQ3ZDLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUFsdUJELElBa3VCQztBQWx1Qlksa0NBQVcifQ==
  104022. /***/ }),
  104023. /* 6 */
  104024. /***/ (function(module, exports, __webpack_require__) {
  104025. "use strict";
  104026. Object.defineProperty(exports, "__esModule", { value: true });
  104027. var babylonjs_1 = __webpack_require__(0);
  104028. /**
  104029. * Receives Telemetry events and raises events to the API
  104030. */
  104031. var TelemetryManager = /** @class */ (function () {
  104032. function TelemetryManager() {
  104033. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  104034. this._event = this._eventEnabled;
  104035. }
  104036. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  104037. /**
  104038. * Receives a telemetry event
  104039. * @param event The name of the Telemetry event
  104040. * @param details An additional value, or an object containing a list of property/value pairs
  104041. */
  104042. get: function () {
  104043. return this._event;
  104044. },
  104045. enumerable: true,
  104046. configurable: true
  104047. });
  104048. /**
  104049. * Log a Telemetry event for errors raised on the WebGL context.
  104050. * @param engine The Babylon engine with the WebGL context.
  104051. */
  104052. TelemetryManager.prototype.flushWebGLErrors = function (engine, viewerId) {
  104053. if (!engine) {
  104054. return;
  104055. }
  104056. var logErrors = true;
  104057. while (logErrors) {
  104058. var gl = engine._gl;
  104059. if (gl && gl.getError) {
  104060. var error = gl.getError();
  104061. if (error === gl.NO_ERROR) {
  104062. logErrors = false;
  104063. }
  104064. else {
  104065. this.broadcast("WebGL Error", viewerId, { error: error });
  104066. }
  104067. }
  104068. else {
  104069. logErrors = false;
  104070. }
  104071. }
  104072. };
  104073. Object.defineProperty(TelemetryManager.prototype, "enable", {
  104074. /**
  104075. * Enable or disable telemetry events
  104076. * @param enabled Boolan, true if events are enabled
  104077. */
  104078. set: function (enabled) {
  104079. if (enabled) {
  104080. this._event = this._eventEnabled;
  104081. }
  104082. else {
  104083. this._event = this._eventDisabled;
  104084. }
  104085. },
  104086. enumerable: true,
  104087. configurable: true
  104088. });
  104089. /**
  104090. * Called on event when disabled, typically do nothing here
  104091. */
  104092. TelemetryManager.prototype._eventDisabled = function () {
  104093. // nothing to do
  104094. };
  104095. /**
  104096. * Called on event when enabled
  104097. * @param event - The name of the Telemetry event
  104098. * @param details An additional value, or an object containing a list of property/value pairs
  104099. */
  104100. TelemetryManager.prototype._eventEnabled = function (event, viewerId, details) {
  104101. var telemetryData = {
  104102. viewerId: viewerId,
  104103. event: event,
  104104. session: this.session,
  104105. date: new Date(),
  104106. now: window.performance ? window.performance.now() : Date.now(),
  104107. detail: null
  104108. };
  104109. if (typeof details === "object") {
  104110. for (var attr in details) {
  104111. if (details.hasOwnProperty(attr)) {
  104112. telemetryData[attr] = details[attr];
  104113. }
  104114. }
  104115. }
  104116. else if (details) {
  104117. telemetryData.detail = details;
  104118. }
  104119. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  104120. };
  104121. Object.defineProperty(TelemetryManager.prototype, "session", {
  104122. /**
  104123. * Returns the current session ID or creates one if it doesn't exixt
  104124. * @return The current session ID
  104125. */
  104126. get: function () {
  104127. if (!this._currentSessionId) {
  104128. //String + Timestamp + Random Integer
  104129. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  104130. }
  104131. return this._currentSessionId;
  104132. },
  104133. enumerable: true,
  104134. configurable: true
  104135. });
  104136. /**
  104137. * Disposes the telemetry manager
  104138. */
  104139. TelemetryManager.prototype.dispose = function () {
  104140. this.onEventBroadcastedObservable.clear();
  104141. delete this.onEventBroadcastedObservable;
  104142. };
  104143. return TelemetryManager;
  104144. }());
  104145. exports.TelemetryManager = TelemetryManager;
  104146. exports.telemetryManager = new TelemetryManager();
  104147. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2Vz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FO1lBQ2hCLGFBQWEsQ0FBQyxNQUFNLEdBQUcsT0FBTyxDQUFDO1NBQ2xDO1FBRUQsSUFBSSxDQUFDLDRCQUE0QixDQUFDLGVBQWUsQ0FBQyxhQUFhLENBQUMsQ0FBQztJQUNyRSxDQUFDO0lBTUQsc0JBQVcscUNBQU87UUFKbEI7OztXQUdHO2FBQ0g7WUFDSSxJQUFJLENBQUMsSUFBSSxDQUFDLGlCQUFpQixFQUFFO2dCQUN6QixxQ0FBcUM7Z0JBQ3JDLElBQUksQ0FBQyxpQkFBaUIsR0FBRyxVQUFVLEdBQUcsSUFBSSxDQUFDLEdBQUcsRUFBRSxHQUFHLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLE1BQU0sRUFBRSxHQUFHLE9BQU8sQ0FBQyxDQUFDO2FBQzFGO1lBQ0QsT0FBTyxJQUFJLENBQUMsaUJBQWlCLENBQUM7UUFDbEMsQ0FBQzs7O09BQUE7SUFFRDs7T0FFRztJQUNJLGtDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsNEJBQTRCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDMUMsT0FBTyxJQUFJLENBQUMsNEJBQTRCLENBQUM7SUFDN0MsQ0FBQztJQUNMLHVCQUFDO0FBQUQsQ0FBQyxBQTVHRCxJQTRHQztBQTVHWSw0Q0FBZ0I7QUE4R2hCLFFBQUEsZ0JBQWdCLEdBQUcsSUFBSSxnQkFBZ0IsRUFBRSxDQUFDIn0=
  104148. /***/ }),
  104149. /* 7 */
  104150. /***/ (function(module, exports, __webpack_require__) {
  104151. "use strict";
  104152. Object.defineProperty(exports, "__esModule", { value: true });
  104153. var babylonjs_1 = __webpack_require__(0);
  104154. /**
  104155. * The viewer manager is the container for all viewers currently registered on this page.
  104156. * It is possible to have more than one viewer on a single page.
  104157. */
  104158. var ViewerManager = /** @class */ (function () {
  104159. function ViewerManager() {
  104160. this._viewers = {};
  104161. this.onViewerAddedObservable = new babylonjs_1.Observable();
  104162. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  104163. }
  104164. /**
  104165. * Adding a new viewer to the viewer manager and start tracking it.
  104166. * @param viewer the viewer to add
  104167. */
  104168. ViewerManager.prototype.addViewer = function (viewer) {
  104169. this._viewers[viewer.getBaseId()] = viewer;
  104170. this._onViewerAdded(viewer);
  104171. };
  104172. /**
  104173. * remove a viewer from the viewer manager
  104174. * @param viewer the viewer to remove
  104175. */
  104176. ViewerManager.prototype.removeViewer = function (viewer) {
  104177. var id = viewer.getBaseId();
  104178. delete this._viewers[id];
  104179. this.onViewerRemovedObservable.notifyObservers(id);
  104180. };
  104181. /**
  104182. * 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)
  104183. * @param id the id of the HTMl element (or the viewer's, if none provided)
  104184. */
  104185. ViewerManager.prototype.getViewerById = function (id) {
  104186. return this._viewers[id];
  104187. };
  104188. /**
  104189. * Get a viewer using a container element
  104190. * @param element the HTML element to search viewers associated with
  104191. */
  104192. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  104193. for (var id in this._viewers) {
  104194. if (this._viewers[id].containerElement === element) {
  104195. return this.getViewerById(id);
  104196. }
  104197. }
  104198. };
  104199. /**
  104200. * Get a promise that will fullfil when this viewer was initialized.
  104201. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  104202. * you will get the viewer after everything was already configured.
  104203. * @param id the viewer id to find
  104204. */
  104205. ViewerManager.prototype.getViewerPromiseById = function (id) {
  104206. var _this = this;
  104207. return new Promise(function (resolve, reject) {
  104208. var localViewer = _this.getViewerById(id);
  104209. if (localViewer) {
  104210. return resolve(localViewer);
  104211. }
  104212. var viewerFunction = function (viewer) {
  104213. if (viewer.getBaseId() === id) {
  104214. resolve(viewer);
  104215. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  104216. }
  104217. };
  104218. _this.onViewerAddedObservable.add(viewerFunction);
  104219. });
  104220. };
  104221. ViewerManager.prototype._onViewerAdded = function (viewer) {
  104222. this.onViewerAdded && this.onViewerAdded(viewer);
  104223. this.onViewerAddedObservable.notifyObservers(viewer);
  104224. };
  104225. /**
  104226. * dispose the manager and all of its associated viewers
  104227. */
  104228. ViewerManager.prototype.dispose = function () {
  104229. delete this._onViewerAdded;
  104230. for (var id in this._viewers) {
  104231. this._viewers[id].dispose();
  104232. }
  104233. this.onViewerAddedObservable.clear();
  104234. this.onViewerRemovedObservable.clear();
  104235. };
  104236. return ViewerManager;
  104237. }());
  104238. exports.ViewerManager = ViewerManager;
  104239. exports.viewerManager = new ViewerManager();
  104240. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvdmlld2VyTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUF1QztBQUd2Qzs7O0dBR0c7QUFDSDtJQWlCSTtRQUNJLElBQUksQ0FBQyxRQUFRLEdBQUcsRUFBRSxDQUFDO1FBQ25CLElBQUksQ0FBQyx1QkFBdUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUNoRCxJQUFJLENBQUMseUJBQXlCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7SUFDdEQsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGlDQUFTLEdBQWhCLFVBQWlCLE1BQXNCO1FBQ25DLElBQUksQ0FBQyxRQUFRLENBQUMsTUFBTSxDQUFDLFNBQVMsRUFBRSxDQUFDLEdBQUcsTUFBTSxDQUFDO1FBQzNDLElBQUksQ0FBQyxjQUFjLENBQUMsTUFBTSxDQUFDLENBQUM7SUFDaEMsQ0FBQztJQUVEOzs7T0FHRztJQUNJLG9DQUFZLEdBQW5CLFVBQW9CLE1BQXNCO1FBQ3RDLElBQUksRUFBRSxHQUFHLE1BQU0sQ0FBQyxTQUFTLEVB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yx1QkFBdUIsQ0FBQyxjQUFjLENBQUMsY0FBYyxDQUFDLENBQUM7aUJBQy9EO1lBQ0wsQ0FBQyxDQUFBO1lBQ0QsS0FBSSxDQUFDLHVCQUF1QixDQUFDLEdBQUcsQ0FBQyxjQUFjLENBQUMsQ0FBQztRQUNyRCxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFFTyxzQ0FBYyxHQUF0QixVQUF1QixNQUFzQjtRQUN6QyxJQUFJLENBQUMsYUFBYSxJQUFJLElBQUksQ0FBQyxhQUFhLENBQUMsTUFBTSxDQUFDLENBQUM7UUFDakQsSUFBSSxDQUFDLHVCQUF1QixDQUFDLGVBQWUsQ0FBQyxNQUFNLENBQUMsQ0FBQztJQUN6RCxDQUFDO0lBRUQ7O09BRUc7SUFDSSwrQkFBTyxHQUFkO1FBQ0ksT0FBTyxJQUFJLENBQUMsY0FBYyxDQUFDO1FBRTNCLEtBQUssSUFBSSxFQUFFLElBQUksSUFBSSxDQUFDLFFBQVEsRUFBRTtZQUMxQixJQUFJLENBQUMsUUFBUSxDQUFDLEVBQUUsQ0FBQyxDQUFDLE9BQU8sRUFBRSxDQUFDO1NBQy9CO1FBRUQsSUFBSSxDQUFDLHVCQUF1QixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3JDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBdEdELElBc0dDO0FBdEdZLHNDQUFhO0FBd0dmLFFBQUEsYUFBYSxHQUFHLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  104241. /***/ }),
  104242. /* 8 */
  104243. /***/ (function(module, exports, __webpack_require__) {
  104244. "use strict";
  104245. var __extends = (this && this.__extends) || (function () {
  104246. var extendStatics = Object.setPrototypeOf ||
  104247. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  104248. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  104249. return function (d, b) {
  104250. extendStatics(d, b);
  104251. function __() { this.constructor = d; }
  104252. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  104253. };
  104254. })();
  104255. Object.defineProperty(exports, "__esModule", { value: true });
  104256. var viewer_1 = __webpack_require__(9);
  104257. var babylonjs_1 = __webpack_require__(0);
  104258. var hdButtonPlugin_1 = __webpack_require__(65);
  104259. /**
  104260. * The Default viewer is the default implementation of the AbstractViewer.
  104261. * It uses the templating system to render a new canvas and controls.
  104262. */
  104263. var DefaultViewer = /** @class */ (function (_super) {
  104264. __extends(DefaultViewer, _super);
  104265. /**
  104266. * Create a new default viewer
  104267. * @param containerElement the element in which the templates will be rendered
  104268. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  104269. */
  104270. function DefaultViewer(containerElement, initialConfiguration) {
  104271. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  104272. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  104273. _this.containerElement = containerElement;
  104274. _this._registeredPlugins = [];
  104275. _this._handlePointerDown = function (event) {
  104276. var pointerDown = event.event;
  104277. if (pointerDown.button !== 0)
  104278. return;
  104279. var element = event.event.target;
  104280. if (!element) {
  104281. return;
  104282. }
  104283. var parentClasses = element.parentElement.classList;
  104284. var elementClasses = element.classList;
  104285. var elementName = "";
  104286. for (var i = 0; i < elementClasses.length; ++i) {
  104287. var className = elementClasses[i];
  104288. if (className.indexOf("-button") !== -1 || className.indexOf("-wrapper") !== -1) {
  104289. elementName = className;
  104290. break;
  104291. }
  104292. }
  104293. switch (elementName) {
  104294. case "speed-button":
  104295. case "types-button":
  104296. if (parentClasses.contains("open")) {
  104297. parentClasses.remove("open");
  104298. }
  104299. else {
  104300. parentClasses.add("open");
  104301. }
  104302. break;
  104303. case "play-pause-button":
  104304. _this._togglePlayPause();
  104305. break;
  104306. case "label-option-button":
  104307. var value = element.dataset["value"];
  104308. var label = element.querySelector("span.animation-label");
  104309. if (label && value) {
  104310. _this._updateAnimationType({ value: value, label: label.innerHTML });
  104311. }
  104312. break;
  104313. case "speed-option-button":
  104314. if (!_this._currentAnimation) {
  104315. return;
  104316. }
  104317. var speed = element.dataset["value"];
  104318. if (speed)
  104319. _this._updateAnimationSpeed(speed);
  104320. break;
  104321. case "progress-wrapper":
  104322. _this._resumePlay = !_this._isAnimationPaused;
  104323. if (_this._resumePlay) {
  104324. _this._togglePlayPause(true);
  104325. }
  104326. break;
  104327. case "fullscreen-button":
  104328. _this.toggleFullscreen();
  104329. break;
  104330. case "vr-button":
  104331. _this.toggleVR();
  104332. break;
  104333. default:
  104334. return;
  104335. }
  104336. };
  104337. /**
  104338. * Plays or Pauses animation
  104339. */
  104340. _this._togglePlayPause = function (noUiUpdate) {
  104341. if (!_this._currentAnimation) {
  104342. return;
  104343. }
  104344. if (_this._isAnimationPaused) {
  104345. _this._currentAnimation.restart();
  104346. }
  104347. else {
  104348. _this._currentAnimation.pause();
  104349. }
  104350. _this._isAnimationPaused = !_this._isAnimationPaused;
  104351. if (noUiUpdate)
  104352. return;
  104353. var navbar = _this.templateManager.getTemplate('navBar');
  104354. if (!navbar)
  104355. return;
  104356. navbar.updateParams({
  104357. paused: _this._isAnimationPaused,
  104358. });
  104359. };
  104360. /**
  104361. * Control progress bar position based on animation current frame
  104362. */
  104363. _this._updateProgressBar = function () {
  104364. var navbar = _this.templateManager.getTemplate('navBar');
  104365. if (!navbar)
  104366. return;
  104367. var progressSlider = navbar.parent.querySelector("input.progress-wrapper");
  104368. if (progressSlider && _this._currentAnimation) {
  104369. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  104370. var currentValue = progressSlider.valueAsNumber;
  104371. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  104372. progressSlider.value = '' + progress;
  104373. }
  104374. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  104375. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  104376. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  104377. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  104378. }
  104379. }
  104380. else {
  104381. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  104382. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  104383. _this._oldIdleRotationValue = 0;
  104384. }
  104385. }
  104386. }
  104387. };
  104388. /**
  104389. * Update Current Animation Speed
  104390. */
  104391. _this._updateAnimationSpeed = function (speed, paramsObject) {
  104392. var navbar = _this.templateManager.getTemplate('navBar');
  104393. if (!navbar)
  104394. return;
  104395. if (speed && _this._currentAnimation) {
  104396. _this._currentAnimation.speedRatio = parseFloat(speed);
  104397. if (!_this._isAnimationPaused) {
  104398. _this._currentAnimation.restart();
  104399. }
  104400. if (paramsObject) {
  104401. paramsObject.selectedSpeed = speed + "x";
  104402. }
  104403. else {
  104404. navbar.updateParams({
  104405. selectedSpeed: speed + "x",
  104406. });
  104407. }
  104408. }
  104409. };
  104410. /**
  104411. * Update Current Animation Type
  104412. */
  104413. _this._updateAnimationType = function (data, paramsObject) {
  104414. var navbar = _this.templateManager.getTemplate('navBar');
  104415. if (!navbar)
  104416. return;
  104417. if (data) {
  104418. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(data.value);
  104419. }
  104420. if (paramsObject) {
  104421. paramsObject.selectedAnimation = (_this._animationList.indexOf(data.value) + 1);
  104422. paramsObject.selectedAnimationName = data.label;
  104423. }
  104424. else {
  104425. navbar.updateParams({
  104426. selectedAnimation: (_this._animationList.indexOf(data.value) + 1),
  104427. selectedAnimationName: data.label
  104428. });
  104429. }
  104430. _this._updateAnimationSpeed("1.0", paramsObject);
  104431. };
  104432. /**
  104433. * Toggle fullscreen of the entire viewer
  104434. */
  104435. _this.toggleFullscreen = function () {
  104436. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  104437. var viewerElement = viewerTemplate && viewerTemplate.parent;
  104438. var fullscreenElement = _this.fullscreenElement || viewerElement;
  104439. if (fullscreenElement) {
  104440. var currentElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  104441. if (!currentElement) {
  104442. var requestFullScreen = fullscreenElement.requestFullscreen || fullscreenElement.webkitRequestFullscreen || fullscreenElement.msRequestFullscreen || fullscreenElement.mozRequestFullScreen;
  104443. requestFullScreen.call(fullscreenElement);
  104444. if (viewerElement) {
  104445. viewerElement.classList.add("in-fullscreen");
  104446. }
  104447. }
  104448. else {
  104449. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  104450. exitFullscreen.call(document);
  104451. if (viewerElement) {
  104452. viewerElement.classList.remove("in-fullscreen");
  104453. }
  104454. }
  104455. }
  104456. };
  104457. _this._onModelLoaded = function (model) {
  104458. _this._configureTemplate(model);
  104459. // with a short timeout, making sure everything is there already.
  104460. var hideLoadingDelay = 20;
  104461. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  104462. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  104463. }
  104464. setTimeout(function () {
  104465. _this.sceneManager.scene.executeWhenReady(function () {
  104466. _this.hideLoadingScreen();
  104467. });
  104468. }, hideLoadingDelay);
  104469. return;
  104470. };
  104471. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  104472. _this.onModelRemovedObservable.add(function () {
  104473. _this._configureTemplate();
  104474. });
  104475. _this.onEngineInitObservable.add(function () {
  104476. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  104477. _this._configureLights();
  104478. });
  104479. });
  104480. _this.onInitDoneObservable.add(function () {
  104481. if (!_this.sceneManager.models.length) {
  104482. _this.hideLoadingScreen();
  104483. }
  104484. });
  104485. return _this;
  104486. }
  104487. DefaultViewer.prototype.registerTemplatePlugin = function (plugin) {
  104488. var _this = this;
  104489. //validate
  104490. if (!plugin.templateName) {
  104491. throw new Error("No template name provided");
  104492. }
  104493. this._registeredPlugins.push(plugin);
  104494. var template = this.templateManager.getTemplate(plugin.templateName);
  104495. if (!template) {
  104496. throw new Error("Template " + plugin.templateName + " not found");
  104497. }
  104498. if (plugin.addHTMLTemplate) {
  104499. template.onHTMLRendered.add(function (tmpl) {
  104500. plugin.addHTMLTemplate(tmpl);
  104501. });
  104502. template.redraw();
  104503. }
  104504. if (plugin.eventsToAttach) {
  104505. plugin.eventsToAttach.forEach(function (eventName) {
  104506. plugin.onEvent && _this.templateManager.eventManager.registerCallback(plugin.templateName, function (event) {
  104507. if (plugin.onEvent && plugin.interactionPredicate(event)) {
  104508. plugin.onEvent(event);
  104509. }
  104510. }, eventName);
  104511. });
  104512. }
  104513. };
  104514. /**
  104515. * This will be executed when the templates initialize.
  104516. */
  104517. DefaultViewer.prototype._onTemplatesLoaded = function () {
  104518. var _this = this;
  104519. this.showLoadingScreen();
  104520. // navbar
  104521. this._initNavbar();
  104522. // close overlay button
  104523. var template = this.templateManager.getTemplate('overlay');
  104524. if (template) {
  104525. var closeButton = template.parent.querySelector('.close-button');
  104526. if (closeButton) {
  104527. closeButton.addEventListener('pointerdown', function () {
  104528. _this.hideOverlayScreen();
  104529. });
  104530. }
  104531. }
  104532. if (this.configuration.templates && this.configuration.templates.viewer) {
  104533. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  104534. this.onSceneInitObservable.addOnce(function () {
  104535. var filesInput = new babylonjs_1.FilesInput(_this.engine, _this.sceneManager.scene, function () {
  104536. }, function () {
  104537. }, function () {
  104538. }, function () {
  104539. }, function () {
  104540. }, function (file) {
  104541. _this.loadModel(file);
  104542. }, function () {
  104543. });
  104544. filesInput.monitorElementForDragNDrop(_this.templateManager.getCanvas());
  104545. });
  104546. }
  104547. }
  104548. return _super.prototype._onTemplatesLoaded.call(this);
  104549. };
  104550. DefaultViewer.prototype._initNavbar = function () {
  104551. var _this = this;
  104552. var navbar = this.templateManager.getTemplate('navBar');
  104553. if (navbar) {
  104554. this.onFrameRenderedObservable.add(this._updateProgressBar);
  104555. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  104556. // an example how to trigger the help button. publiclly available
  104557. this.templateManager.eventManager.registerCallback("navBar", function () {
  104558. // do your thing
  104559. }, "pointerdown", ".help-button");
  104560. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  104561. var evt = event.event;
  104562. var element = (evt.target);
  104563. if (!_this._currentAnimation)
  104564. return;
  104565. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  104566. if (isNaN(gotoFrame))
  104567. return;
  104568. _this._currentAnimation.goToFrame(gotoFrame);
  104569. }, "input");
  104570. this.templateManager.eventManager.registerCallback("navBar", function () {
  104571. if (_this._resumePlay) {
  104572. _this._togglePlayPause(true);
  104573. }
  104574. _this._resumePlay = false;
  104575. }, "pointerup", ".progress-wrapper");
  104576. if (window.devicePixelRatio === 1 && navbar.configuration.params && !navbar.configuration.params.hideHdButton) {
  104577. navbar.updateParams({
  104578. hideHdButton: true
  104579. });
  104580. }
  104581. this.registerTemplatePlugin(new hdButtonPlugin_1.HDButtonPlugin(this));
  104582. }
  104583. };
  104584. DefaultViewer.prototype.toggleVR = function () {
  104585. _super.prototype.toggleVR.call(this);
  104586. var viewerTemplate = this.templateManager.getTemplate('viewer');
  104587. var viewerElement = viewerTemplate && viewerTemplate.parent;
  104588. if (viewerElement) {
  104589. if (this._vrToggled) {
  104590. viewerElement.classList.add("in-vr");
  104591. }
  104592. else {
  104593. viewerElement.classList.remove("in-vr");
  104594. }
  104595. }
  104596. };
  104597. /**
  104598. * Preparing the container element to present the viewer
  104599. */
  104600. DefaultViewer.prototype._prepareContainerElement = function () {
  104601. this.containerElement.style.position = 'relative';
  104602. this.containerElement.style.height = '100%';
  104603. this.containerElement.style.display = 'flex';
  104604. };
  104605. /**
  104606. * This function will configure the templates and update them after a model was loaded
  104607. * It is mainly responsible to changing the title and subtitle etc'.
  104608. * @param model the model to be used to configure the templates by
  104609. */
  104610. DefaultViewer.prototype._configureTemplate = function (model) {
  104611. var navbar = this.templateManager.getTemplate('navBar');
  104612. if (!navbar)
  104613. return;
  104614. var newParams = navbar.configuration.params || {};
  104615. if (!model) {
  104616. newParams.animations = null;
  104617. }
  104618. else {
  104619. var animationNames = model.getAnimationNames();
  104620. newParams.animations = animationNames.map(function (a) { return { label: a, value: a }; });
  104621. if (animationNames.length) {
  104622. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  104623. this._animationList = animationNames;
  104624. newParams.paused = this._isAnimationPaused;
  104625. var animationIndex = 0;
  104626. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  104627. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  104628. if (animationIndex === -1) {
  104629. animationIndex = 0;
  104630. }
  104631. }
  104632. this._updateAnimationType(newParams.animations[animationIndex], newParams);
  104633. }
  104634. else {
  104635. newParams.animations = null;
  104636. }
  104637. if (model.configuration.thumbnail) {
  104638. newParams.logoImage = model.configuration.thumbnail;
  104639. }
  104640. }
  104641. navbar.updateParams(newParams, false);
  104642. };
  104643. /**
  104644. * This will load a new model to the default viewer
  104645. * overriding the AbstractViewer's loadModel.
  104646. * The scene will automatically be cleared of the old models, if exist.
  104647. * @param model the configuration object (or URL) to load.
  104648. */
  104649. DefaultViewer.prototype.loadModel = function (model) {
  104650. var _this = this;
  104651. if (!model) {
  104652. model = this.configuration.model;
  104653. }
  104654. this.showLoadingScreen();
  104655. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  104656. console.log(error);
  104657. _this.hideLoadingScreen();
  104658. _this.showOverlayScreen('error');
  104659. return Promise.reject(error);
  104660. });
  104661. };
  104662. /**
  104663. * Show the overlay and the defined sub-screen.
  104664. * Mainly used for help and errors
  104665. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  104666. */
  104667. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  104668. var _this = this;
  104669. var template = this.templateManager.getTemplate('overlay');
  104670. if (!template)
  104671. return Promise.resolve('Overlay template not found');
  104672. return template.show((function (template) {
  104673. var canvasRect = _this.containerElement.getBoundingClientRect();
  104674. template.parent.style.display = 'flex';
  104675. template.parent.style.width = canvasRect.width + "px";
  104676. template.parent.style.height = canvasRect.height + "px";
  104677. template.parent.style.opacity = "1";
  104678. var subTemplate = _this.templateManager.getTemplate(subScreen);
  104679. if (!subTemplate) {
  104680. return Promise.reject(subScreen + ' template not found');
  104681. }
  104682. return subTemplate.show((function (template) {
  104683. template.parent.style.display = 'flex';
  104684. return Promise.resolve(template);
  104685. }));
  104686. }));
  104687. };
  104688. /**
  104689. * Hide the overlay screen.
  104690. */
  104691. DefaultViewer.prototype.hideOverlayScreen = function () {
  104692. var template = this.templateManager.getTemplate('overlay');
  104693. if (!template)
  104694. return Promise.resolve('Overlay template not found');
  104695. return template.hide((function (template) {
  104696. template.parent.style.opacity = "0";
  104697. var onTransitionEnd = function () {
  104698. template.parent.removeEventListener("transitionend", onTransitionEnd);
  104699. template.parent.style.display = 'none';
  104700. };
  104701. template.parent.addEventListener("transitionend", onTransitionEnd);
  104702. var overlays = template.parent.querySelectorAll('.overlay');
  104703. if (overlays) {
  104704. for (var i = 0; i < overlays.length; ++i) {
  104705. var htmlElement = overlays.item(i);
  104706. htmlElement.style.display = 'none';
  104707. }
  104708. }
  104709. return Promise.resolve(template);
  104710. }));
  104711. };
  104712. /**
  104713. * show the viewer (in case it was hidden)
  104714. *
  104715. * @param visibilityFunction an optional function to execute in order to show the container
  104716. */
  104717. DefaultViewer.prototype.show = function (visibilityFunction) {
  104718. var template = this.templateManager.getTemplate('main');
  104719. //not possible, but yet:
  104720. if (!template)
  104721. return Promise.reject('Main template not found');
  104722. return template.show(visibilityFunction);
  104723. };
  104724. /**
  104725. * hide the viewer (in case it is visible)
  104726. *
  104727. * @param visibilityFunction an optional function to execute in order to hide the container
  104728. */
  104729. DefaultViewer.prototype.hide = function (visibilityFunction) {
  104730. var template = this.templateManager.getTemplate('main');
  104731. //not possible, but yet:
  104732. if (!template)
  104733. return Promise.reject('Main template not found');
  104734. return template.hide(visibilityFunction);
  104735. };
  104736. /**
  104737. * Show the loading screen.
  104738. * The loading screen can be configured using the configuration object
  104739. */
  104740. DefaultViewer.prototype.showLoadingScreen = function () {
  104741. var _this = this;
  104742. var template = this.templateManager.getTemplate('loadingScreen');
  104743. if (!template)
  104744. return Promise.resolve('Loading Screen template not found');
  104745. return template.show((function (template) {
  104746. var canvasRect = _this.containerElement.getBoundingClientRect();
  104747. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  104748. template.parent.style.display = 'flex';
  104749. template.parent.style.width = canvasRect.width + "px";
  104750. template.parent.style.height = canvasRect.height + "px";
  104751. template.parent.style.opacity = "1";
  104752. // from the configuration!!!
  104753. var color = "black";
  104754. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  104755. color = (_this.configuration.templates.loadingScreen.params &&
  104756. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  104757. }
  104758. template.parent.style.backgroundColor = color;
  104759. return Promise.resolve(template);
  104760. }));
  104761. };
  104762. /**
  104763. * Hide the loading screen
  104764. */
  104765. DefaultViewer.prototype.hideLoadingScreen = function () {
  104766. var template = this.templateManager.getTemplate('loadingScreen');
  104767. if (!template)
  104768. return Promise.resolve('Loading Screen template not found');
  104769. return template.hide((function (template) {
  104770. template.parent.style.opacity = "0";
  104771. var onTransitionEnd = function () {
  104772. template.parent.removeEventListener("transitionend", onTransitionEnd);
  104773. template.parent.style.display = 'none';
  104774. };
  104775. template.parent.addEventListener("transitionend", onTransitionEnd);
  104776. return Promise.resolve(template);
  104777. }));
  104778. };
  104779. DefaultViewer.prototype.dispose = function () {
  104780. this.templateManager.dispose();
  104781. _super.prototype.dispose.call(this);
  104782. };
  104783. DefaultViewer.prototype._onConfigurationLoaded = function (configuration) {
  104784. var _this = this;
  104785. _super.prototype._onConfigurationLoaded.call(this, configuration);
  104786. // initialize the templates
  104787. var templateConfiguration = this.configuration.templates || {};
  104788. this.templateManager.initTemplate(templateConfiguration);
  104789. // when done, execute onTemplatesLoaded()
  104790. this.templateManager.onAllLoaded.add(function () {
  104791. var canvas = _this.templateManager.getCanvas();
  104792. if (canvas) {
  104793. _this._canvas = canvas;
  104794. }
  104795. _this._onTemplateLoaded();
  104796. });
  104797. };
  104798. /**
  104799. * An extension of the light configuration of the abstract viewer.
  104800. * @param lightsConfiguration the light configuration to use
  104801. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  104802. */
  104803. DefaultViewer.prototype._configureLights = function () {
  104804. var _this = this;
  104805. // labs feature - flashlight
  104806. if (this.configuration.lab && this.configuration.lab.flashlight) {
  104807. var lightTarget_1;
  104808. var angle = 0.5;
  104809. var exponent = Math.PI / 2;
  104810. if (typeof this.configuration.lab.flashlight === "object") {
  104811. exponent = this.configuration.lab.flashlight.exponent || exponent;
  104812. angle = this.configuration.lab.flashlight.angle || angle;
  104813. }
  104814. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  104815. if (typeof this.configuration.lab.flashlight === "object") {
  104816. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  104817. if (this.configuration.lab.flashlight.diffuse) {
  104818. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  104819. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  104820. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  104821. }
  104822. if (this.configuration.lab.flashlight.specular) {
  104823. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  104824. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  104825. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  104826. }
  104827. }
  104828. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  104829. this.sceneManager.scene.onPointerObservable.add(function (eventData) {
  104830. if (eventData.type === 4 && eventData.pickInfo) {
  104831. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  104832. }
  104833. else {
  104834. lightTarget_1 = undefined;
  104835. }
  104836. });
  104837. var updateFlashlightFunction = function () {
  104838. if (_this.sceneManager.camera && flashlight) {
  104839. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  104840. if (lightTarget_1) {
  104841. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  104842. }
  104843. }
  104844. };
  104845. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  104846. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  104847. }
  104848. };
  104849. return DefaultViewer;
  104850. }(viewer_1.AbstractViewer));
  104851. exports.DefaultViewer = DefaultViewer;
  104852. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdFZpZXdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvZGVmYXVsdFZpZXdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7QUFJQSxtQ0FBMEM7QUFDMUMsdUNBQTJEO0FBSTNELHVFQUFzRTtBQUV0RTs7O0dBR0c7QUFDSDtJQUFtQyxpQ0FBYztJQUk3Qzs7OztPQUlHO0lBQ0gsdUJBQW1CLGdCQUE2QixFQUFFLG9CQUFrRTtRQUFsRSxxQ0FBQSxFQUFBLHlCQUE4QyxPQUFPLEVBQUUsU0FBUyxFQUFFO1FBQXBILFlBQ0ksa0JBQU0sZ0JBQWdCLEVBQUUsb0JBQW9CLENBQUMsU0FrQmhEO1FBbkJrQixzQkFBZ0IsR0FBaEIsZ0JBQWdCLENBQWE7UUFxQnhDLHdCQUFrQixHQUFpQyxFQUFFLENBQUM7UUFpSHRELHdCQUFrQixHQUFHLFVBQUMsS0FBb0I7WUFFOUMsSUFBSSxXQUFXLEdBQWlCL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0wsQ0FBQyxDQUFDLENBQUM7WUFDSCxJQUFJLHdCQUF3QixHQUFHO2dCQUMzQixJQUFJLEtBQUksQ0FBQyxZQUFZLENBQUMsTUFBTSxJQUFJLFVBQVUsRUFBRTtvQkFDeEMsVUFBVSxDQUFDLFFBQVEsQ0FBQyxRQUFRLENBQUMsS0FBSSxDQUFDLFlBQVksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLENBQUM7b0JBQ2hFLElBQUksYUFBVyxFQUFFO3dCQUNiLGFBQVcsQ0FBQyxhQUFhLENBQUMsVUFBVSxDQUFDLFFBQVEsRUFBRSxVQUFVLENBQUMsU0FBUyxDQUFDLENBQUM7cUJBQ3hFO2lCQUNKO1lBQ0wsQ0FBQyxDQUFBO1lBQ0QsSUFBSSxDQUFDLFlBQVksQ0FBQyxLQUFLLENBQUMsb0JBQW9CLENBQUMsd0JBQXdCLENBQUMsQ0FBQztZQUN2RSxJQUFJLENBQUMsa0NBQWtDLENBQUMsSUFBSSxDQUFDLHdCQUF3QixDQUFDLENBQUM7U0FDMUU7SUFDTCxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBN25CRCxDQUFtQyx1QkFBYyxHQTZuQmhEO0FBN25CWSxzQ0FBYSJ9
  104853. /***/ }),
  104854. /* 9 */
  104855. /***/ (function(module, exports, __webpack_require__) {
  104856. "use strict";
  104857. Object.defineProperty(exports, "__esModule", { value: true });
  104858. var viewerManager_1 = __webpack_require__(7);
  104859. var sceneManager_1 = __webpack_require__(24);
  104860. var loader_1 = __webpack_require__(30);
  104861. var babylonjs_1 = __webpack_require__(0);
  104862. var modelLoader_1 = __webpack_require__(13);
  104863. var globals_1 = __webpack_require__(4);
  104864. var telemetryManager_1 = __webpack_require__(6);
  104865. var _1 = __webpack_require__(1);
  104866. var observablesManager_1 = __webpack_require__(61);
  104867. var configurationContainer_1 = __webpack_require__(62);
  104868. var templateManager_1 = __webpack_require__(63);
  104869. /**
  104870. * The AbstractViewr is the center of Babylon's viewer.
  104871. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  104872. */
  104873. var AbstractViewer = /** @class */ (function () {
  104874. function AbstractViewer(containerElement, initialConfiguration) {
  104875. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  104876. var _this = this;
  104877. this.containerElement = containerElement;
  104878. /**
  104879. * A flag that controls whether or not the render loop should be executed
  104880. */
  104881. this.runRenderLoop = true;
  104882. /**
  104883. * is this viewer disposed?
  104884. */
  104885. this._isDisposed = false;
  104886. this._hdToggled = false;
  104887. this._vrToggled = false;
  104888. this._vrModelRepositioning = 0;
  104889. this._vrScale = 1;
  104890. /**
  104891. * The resize function that will be registered with the window object
  104892. */
  104893. this._resize = function () {
  104894. // Only resize if Canvas is in the DOM
  104895. if (!_this.isCanvasInDOM()) {
  104896. return;
  104897. }
  104898. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  104899. return;
  104900. }
  104901. if (_this.configuration.engine && _this.configuration.engine.disableResize) {
  104902. return;
  104903. }
  104904. _this.engine.resize();
  104905. };
  104906. /**
  104907. * render loop that will be executed by the engine
  104908. */
  104909. this._render = function (force) {
  104910. if (force === void 0) { force = false; }
  104911. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  104912. if (_this.runRenderLoop || force) {
  104913. _this.engine.performanceMonitor.enable();
  104914. _this.sceneManager.scene.render();
  104915. _this.onFrameRenderedObservable.notifyObservers(_this);
  104916. }
  104917. else {
  104918. _this.engine.performanceMonitor.disable();
  104919. // update camera instead of rendering
  104920. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  104921. }
  104922. }
  104923. };
  104924. // if exists, use the container id. otherwise, generate a random string.
  104925. if (containerElement.id) {
  104926. this.baseId = containerElement.id;
  104927. }
  104928. else {
  104929. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  104930. }
  104931. this._registeredOnBeforeRenderFunctions = [];
  104932. this._configurationContainer = new configurationContainer_1.ConfigurationContainer();
  104933. // add this viewer to the viewer manager
  104934. viewerManager_1.viewerManager.addViewer(this);
  104935. this.observablesManager = new observablesManager_1.ObservablesManager();
  104936. this.modelLoader = new modelLoader_1.ModelLoader(this.observablesManager, this._configurationContainer);
  104937. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  104938. // extend the configuration
  104939. this._configurationLoader = new loader_1.ConfigurationLoader();
  104940. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  104941. _this._onConfigurationLoaded(configuration);
  104942. });
  104943. this.onSceneInitObservable.add(function () {
  104944. _this.updateConfiguration();
  104945. });
  104946. this.onInitDoneObservable.add(function () {
  104947. _this._isInit = true;
  104948. _this.engine.runRenderLoop(_this._render);
  104949. });
  104950. this._prepareContainerElement();
  104951. }
  104952. Object.defineProperty(AbstractViewer.prototype, "onSceneInitObservable", {
  104953. // observables
  104954. /**
  104955. * Will notify when the scene was initialized
  104956. */
  104957. get: function () {
  104958. return this.observablesManager.onSceneInitObservable;
  104959. },
  104960. enumerable: true,
  104961. configurable: true
  104962. });
  104963. Object.defineProperty(AbstractViewer.prototype, "onEngineInitObservable", {
  104964. /**
  104965. * will notify when the engine was initialized
  104966. */
  104967. get: function () {
  104968. return this.observablesManager.onEngineInitObservable;
  104969. },
  104970. enumerable: true,
  104971. configurable: true
  104972. });
  104973. Object.defineProperty(AbstractViewer.prototype, "onModelAddedObservable", {
  104974. /**
  104975. * Will notify when a new model was added to the scene.
  104976. * Note that added does not neccessarily mean loaded!
  104977. */
  104978. get: function () {
  104979. return this.observablesManager.onModelAddedObservable;
  104980. },
  104981. enumerable: true,
  104982. configurable: true
  104983. });
  104984. Object.defineProperty(AbstractViewer.prototype, "onModelLoadedObservable", {
  104985. /**
  104986. * will notify after every model load
  104987. */
  104988. get: function () {
  104989. return this.observablesManager.onModelLoadedObservable;
  104990. },
  104991. enumerable: true,
  104992. configurable: true
  104993. });
  104994. Object.defineProperty(AbstractViewer.prototype, "onModelLoadProgressObservable", {
  104995. /**
  104996. * will notify when any model notify of progress
  104997. */
  104998. get: function () {
  104999. return this.observablesManager.onModelLoadProgressObservable;
  105000. },
  105001. enumerable: true,
  105002. configurable: true
  105003. });
  105004. Object.defineProperty(AbstractViewer.prototype, "onModelLoadErrorObservable", {
  105005. /**
  105006. * will notify when any model load failed.
  105007. */
  105008. get: function () {
  105009. return this.observablesManager.onModelLoadErrorObservable;
  105010. },
  105011. enumerable: true,
  105012. configurable: true
  105013. });
  105014. Object.defineProperty(AbstractViewer.prototype, "onModelRemovedObservable", {
  105015. /**
  105016. * Will notify when a model was removed from the scene;
  105017. */
  105018. get: function () {
  105019. return this.observablesManager.onModelRemovedObservable;
  105020. },
  105021. enumerable: true,
  105022. configurable: true
  105023. });
  105024. Object.defineProperty(AbstractViewer.prototype, "onLoaderInitObservable", {
  105025. /**
  105026. * will notify when a new loader was initialized.
  105027. * Used mainly to know when a model starts loading.
  105028. */
  105029. get: function () {
  105030. return this.observablesManager.onLoaderInitObservable;
  105031. },
  105032. enumerable: true,
  105033. configurable: true
  105034. });
  105035. Object.defineProperty(AbstractViewer.prototype, "onInitDoneObservable", {
  105036. /**
  105037. * Observers registered here will be executed when the entire load process has finished.
  105038. */
  105039. get: function () {
  105040. return this.observablesManager.onViewerInitDoneObservable;
  105041. },
  105042. enumerable: true,
  105043. configurable: true
  105044. });
  105045. Object.defineProperty(AbstractViewer.prototype, "onFrameRenderedObservable", {
  105046. /**
  105047. * Functions added to this observable will be executed on each frame rendered.
  105048. */
  105049. get: function () {
  105050. return this.observablesManager.onFrameRenderedObservable;
  105051. },
  105052. enumerable: true,
  105053. configurable: true
  105054. });
  105055. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  105056. /**
  105057. * The (single) canvas of this viewer
  105058. */
  105059. get: function () {
  105060. return this._canvas;
  105061. },
  105062. enumerable: true,
  105063. configurable: true
  105064. });
  105065. Object.defineProperty(AbstractViewer.prototype, "configurationContainer", {
  105066. get: function () {
  105067. return this._configurationContainer;
  105068. },
  105069. enumerable: true,
  105070. configurable: true
  105071. });
  105072. /**
  105073. * get the baseId of this viewer
  105074. */
  105075. AbstractViewer.prototype.getBaseId = function () {
  105076. return this.baseId;
  105077. };
  105078. /**
  105079. * Do we have a canvas to render on, and is it a part of the scene
  105080. */
  105081. AbstractViewer.prototype.isCanvasInDOM = function () {
  105082. return !!this._canvas && !!this._canvas.parentElement;
  105083. };
  105084. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  105085. /**
  105086. * Is the engine currently set to rende even when the page is in background
  105087. */
  105088. get: function () {
  105089. return this.engine && this.engine.renderEvenInBackground;
  105090. },
  105091. /**
  105092. * Set the viewer's background rendering flag.
  105093. */
  105094. set: function (value) {
  105095. if (this.engine) {
  105096. this.engine.renderEvenInBackground = value;
  105097. }
  105098. },
  105099. enumerable: true,
  105100. configurable: true
  105101. });
  105102. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  105103. /**
  105104. * Get the configuration object. This is a reference only.
  105105. * The configuration can ONLY be updated using the updateConfiguration function.
  105106. * changing this object will have no direct effect on the scene.
  105107. */
  105108. get: function () {
  105109. return this._configurationContainer.configuration;
  105110. },
  105111. enumerable: true,
  105112. configurable: true
  105113. });
  105114. /**
  105115. * force resizing the engine.
  105116. */
  105117. AbstractViewer.prototype.forceResize = function () {
  105118. this._resize();
  105119. };
  105120. AbstractViewer.prototype.toggleHD = function () {
  105121. this._hdToggled = !this._hdToggled;
  105122. var scale = this._hdToggled ? Math.max(0.5, 1 / (window.devicePixelRatio || 2)) : 1;
  105123. this.engine.setHardwareScalingLevel(scale);
  105124. };
  105125. AbstractViewer.prototype.toggleVR = function () {
  105126. this._vrToggled = !this._vrToggled;
  105127. if (this._vrToggled && this.sceneManager.vrHelper) {
  105128. // make sure the floor is set
  105129. if (this.sceneManager.environmentHelper && this.sceneManager.environmentHelper.ground) {
  105130. this.sceneManager.vrHelper.addFloorMesh(this.sceneManager.environmentHelper.ground);
  105131. }
  105132. this.sceneManager.vrHelper.enterVR();
  105133. // calculate position and vr scale
  105134. if (this.sceneManager.environmentHelper) {
  105135. this.sceneManager.environmentHelper.ground && this.sceneManager.environmentHelper.ground.scaling.scaleInPlace(this._vrScale);
  105136. this.sceneManager.environmentHelper.skybox && this.sceneManager.environmentHelper.skybox.scaling.scaleInPlace(this._vrScale);
  105137. }
  105138. // position the vr camera to be in front of the object
  105139. if (this.sceneManager.vrHelper.currentVRCamera) {
  105140. this.sceneManager.vrHelper.currentVRCamera.position.copyFromFloats(0, this.sceneManager.vrHelper.currentVRCamera.position.y, -1);
  105141. this.sceneManager.vrHelper.currentVRCamera.rotationQuaternion && this.sceneManager.vrHelper.currentVRCamera.rotationQuaternion.copyFromFloats(0, 0, 0, 1);
  105142. this._vrModelRepositioning = this.sceneManager.vrHelper.currentVRCamera.position.y / 2;
  105143. // enable rotation using the axels
  105144. // check if the camera is a webvr camera
  105145. if (this.sceneManager.vrHelper.currentVRCamera.getClassName() === "WebVRFreeCamera") {
  105146. }
  105147. }
  105148. else {
  105149. this._vrModelRepositioning = 0;
  105150. }
  105151. if (this.sceneManager.models.length) {
  105152. var boundingVectors = this.sceneManager.models[0].rootMesh.getHierarchyBoundingVectors();
  105153. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  105154. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  105155. this._vrScale = (1 / maxDimension);
  105156. if (this.configuration.vr && this.configuration.vr.objectScaleFactor) {
  105157. this._vrScale *= this.configuration.vr.objectScaleFactor;
  105158. }
  105159. this.sceneManager.models[0].rootMesh.scaling.scaleInPlace(this._vrScale);
  105160. // reposition the object to "float" in front of the user
  105161. this.sceneManager.models[0].rootMesh.position.y += this._vrModelRepositioning;
  105162. this.sceneManager.models[0].rootMesh.rotationQuaternion = null;
  105163. }
  105164. // post processing
  105165. if (this.sceneManager.defaultRenderingPipelineEnabled && this.sceneManager.defaultRenderingPipeline) {
  105166. this.sceneManager.defaultRenderingPipeline.imageProcessingEnabled = false;
  105167. this.sceneManager.defaultRenderingPipeline.prepare();
  105168. }
  105169. }
  105170. else {
  105171. if (this.sceneManager.vrHelper) {
  105172. this.sceneManager.vrHelper.exitVR();
  105173. //this.sceneManager.scene.activeCamera = this.sceneManager.camera;
  105174. if (this.sceneManager.models.length) {
  105175. this.sceneManager.models[0].rootMesh.scaling.scaleInPlace(1 / this._vrScale);
  105176. this.sceneManager.models[0].rootMesh.position.y -= this._vrModelRepositioning;
  105177. }
  105178. if (this.sceneManager.environmentHelper) {
  105179. this.sceneManager.environmentHelper.ground && this.sceneManager.environmentHelper.ground.scaling.scaleInPlace(1 / this._vrScale);
  105180. this.sceneManager.environmentHelper.skybox && this.sceneManager.environmentHelper.skybox.scaling.scaleInPlace(1 / this._vrScale);
  105181. }
  105182. // post processing
  105183. if (this.sceneManager.defaultRenderingPipelineEnabled && this.sceneManager.defaultRenderingPipeline) {
  105184. this.sceneManager.defaultRenderingPipeline.imageProcessingEnabled = true;
  105185. this.sceneManager.defaultRenderingPipeline.prepare();
  105186. }
  105187. }
  105188. }
  105189. };
  105190. AbstractViewer.prototype._onConfigurationLoaded = function (configuration) {
  105191. var _this = this;
  105192. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, configuration);
  105193. if (this.configuration.observers) {
  105194. this._configureObservers(this.configuration.observers);
  105195. }
  105196. // TODO remove this after testing, as this is done in the updateCOnfiguration as well.
  105197. if (this.configuration.loaderPlugins) {
  105198. Object.keys(this.configuration.loaderPlugins).forEach((function (name) {
  105199. if (_this.configuration.loaderPlugins && _this.configuration.loaderPlugins[name]) {
  105200. _this.modelLoader.addPlugin(name);
  105201. }
  105202. }));
  105203. }
  105204. this.templateManager = new templateManager_1.TemplateManager(this.containerElement);
  105205. this.observablesManager.onViewerInitStartedObservable.notifyObservers(this);
  105206. };
  105207. /**
  105208. * Force a single render loop execution.
  105209. */
  105210. AbstractViewer.prototype.forceRender = function () {
  105211. this._render(true);
  105212. };
  105213. /**
  105214. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  105215. * @param callback optional callback that will be triggered when screenshot is done.
  105216. * @param width Optional screenshot width (default to 512).
  105217. * @param height Optional screenshot height (default to 512).
  105218. * @returns a promise with the screenshot data
  105219. */
  105220. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  105221. var _this = this;
  105222. if (width === void 0) { width = 0; }
  105223. if (height === void 0) { height = 0; }
  105224. width = width || this.canvas.clientWidth;
  105225. height = height || this.canvas.clientHeight;
  105226. // Create the screenshot
  105227. return new Promise(function (resolve, reject) {
  105228. try {
  105229. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  105230. if (callback) {
  105231. callback(data);
  105232. }
  105233. resolve(data);
  105234. });
  105235. }
  105236. catch (e) {
  105237. reject(e);
  105238. }
  105239. });
  105240. };
  105241. /**
  105242. * Update the current viewer configuration with new values.
  105243. * Only provided information will be updated, old configuration values will be kept.
  105244. * If this.configuration was manually changed, you can trigger this function with no parameters,
  105245. * and the entire configuration will be updated.
  105246. * @param newConfiguration the partial configuration to update
  105247. *
  105248. */
  105249. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  105250. var _this = this;
  105251. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  105252. // update this.configuration with the new data
  105253. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, newConfiguration);
  105254. this.sceneManager.updateConfiguration(newConfiguration);
  105255. // observers in configuration
  105256. if (newConfiguration.observers) {
  105257. this._configureObservers(newConfiguration.observers);
  105258. }
  105259. if (newConfiguration.loaderPlugins) {
  105260. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  105261. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  105262. _this.modelLoader.addPlugin(name);
  105263. }
  105264. }));
  105265. }
  105266. };
  105267. /**
  105268. * this is used to register native functions using the configuration object.
  105269. * This will configure the observers.
  105270. * @param observersConfiguration observers configuration
  105271. */
  105272. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  105273. if (observersConfiguration.onEngineInit) {
  105274. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  105275. }
  105276. else {
  105277. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  105278. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  105279. }
  105280. }
  105281. if (observersConfiguration.onSceneInit) {
  105282. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  105283. }
  105284. else {
  105285. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  105286. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  105287. }
  105288. }
  105289. if (observersConfiguration.onModelLoaded) {
  105290. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  105291. }
  105292. else {
  105293. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  105294. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  105295. }
  105296. }
  105297. };
  105298. /**
  105299. * Dispoe the entire viewer including the scene and the engine
  105300. */
  105301. AbstractViewer.prototype.dispose = function () {
  105302. if (this._isDisposed) {
  105303. return;
  105304. }
  105305. window.removeEventListener('resize', this._resize);
  105306. if (this.sceneManager) {
  105307. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  105308. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  105309. }
  105310. this.sceneManager.dispose();
  105311. }
  105312. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  105313. this.observablesManager.dispose();
  105314. this.modelLoader.dispose();
  105315. if (this.engine) {
  105316. this.engine.dispose();
  105317. }
  105318. viewerManager_1.viewerManager.removeViewer(this);
  105319. this._isDisposed = true;
  105320. };
  105321. /**
  105322. * This function will execute when the HTML templates finished initializing.
  105323. * It should initialize the engine and continue execution.
  105324. *
  105325. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  105326. */
  105327. AbstractViewer.prototype._onTemplatesLoaded = function () {
  105328. return Promise.resolve(this);
  105329. };
  105330. /**
  105331. * This will force the creation of an engine and a scene.
  105332. * It will also load a model if preconfigured.
  105333. * But first - it will load the extendible onTemplateLoaded()!
  105334. */
  105335. AbstractViewer.prototype._onTemplateLoaded = function () {
  105336. var _this = this;
  105337. // check if viewer was disposed right after created
  105338. if (this._isDisposed) {
  105339. return Promise.reject("viewer was disposed");
  105340. }
  105341. return this._onTemplatesLoaded().then(function () {
  105342. var autoLoad = typeof _this.configuration.model === 'string' || (_this.configuration.model && _this.configuration.model.url);
  105343. return _this._initEngine().then(function (engine) {
  105344. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  105345. }).then(function () {
  105346. _this._initTelemetryEvents();
  105347. if (autoLoad) {
  105348. return _this.loadModel(_this.configuration.model).catch(function () { }).then(function () { return _this.sceneManager.scene; });
  105349. }
  105350. else {
  105351. return _this.sceneManager.scene || _this.sceneManager.initScene(_this.configuration.scene);
  105352. }
  105353. }).then(function () {
  105354. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  105355. }).catch(function (e) {
  105356. babylonjs_1.Tools.Warn(e.toString());
  105357. return _this;
  105358. });
  105359. });
  105360. };
  105361. /**
  105362. * Initialize the engine. Retruns a promise in case async calls are needed.
  105363. *
  105364. * @protected
  105365. * @returns {Promise<Engine>}
  105366. * @memberof Viewer
  105367. */
  105368. AbstractViewer.prototype._initEngine = function () {
  105369. // init custom shaders
  105370. this._injectCustomShaders();
  105371. //let canvasElement = this.templateManager.getCanvas();
  105372. if (!this.canvas) {
  105373. return Promise.reject('Canvas element not found!');
  105374. }
  105375. var config = this.configuration.engine || {};
  105376. // TDO enable further configuration
  105377. // check for webgl2 support, force-disable if needed.
  105378. if (globals_1.viewerGlobals.disableWebGL2Support) {
  105379. config.engineOptions = config.engineOptions || {};
  105380. config.engineOptions.disableWebGL2Support = true;
  105381. }
  105382. this.engine = new babylonjs_1.Engine(this.canvas, !!config.antialiasing, config.engineOptions);
  105383. // Disable manifest checking
  105384. babylonjs_1.Database.IDBStorageEnabled = false;
  105385. if (!config.disableResize) {
  105386. window.addEventListener('resize', this._resize);
  105387. }
  105388. if (this.configuration.engine) {
  105389. if (this.configuration.engine.adaptiveQuality) {
  105390. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  105391. this.engine.setHardwareScalingLevel(scale);
  105392. }
  105393. if (this.configuration.engine.hdEnabled) {
  105394. this.toggleHD();
  105395. }
  105396. }
  105397. // create a new template manager for this viewer
  105398. this.sceneManager = new sceneManager_1.SceneManager(this.engine, this._configurationContainer, this.observablesManager);
  105399. return Promise.resolve(this.engine);
  105400. };
  105401. /**
  105402. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  105403. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  105404. *
  105405. * @param modelConfig model configuration to use when loading the model.
  105406. * @param clearScene should the scene be cleared before loading this model
  105407. * @returns a ViewerModel object that is not yet fully loaded.
  105408. */
  105409. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  105410. var _this = this;
  105411. if (clearScene === void 0) { clearScene = true; }
  105412. var configuration;
  105413. if (typeof modelConfig === 'string') {
  105414. configuration = {
  105415. url: modelConfig
  105416. };
  105417. }
  105418. else if (modelConfig instanceof File) {
  105419. configuration = {
  105420. file: modelConfig,
  105421. root: "file:"
  105422. };
  105423. }
  105424. else {
  105425. configuration = modelConfig;
  105426. }
  105427. if (!configuration.url && !configuration.file) {
  105428. throw new Error("no model provided");
  105429. }
  105430. if (clearScene) {
  105431. this.sceneManager.clearScene(true, false);
  105432. }
  105433. //merge the configuration for future models:
  105434. if (this.configuration.model && typeof this.configuration.model === 'object') {
  105435. var globalConfig = _1.deepmerge({}, this.configuration.model);
  105436. configuration = _1.deepmerge(globalConfig, configuration);
  105437. if (modelConfig instanceof File) {
  105438. configuration.file = modelConfig;
  105439. }
  105440. }
  105441. else {
  105442. this.configuration.model = configuration;
  105443. }
  105444. this._isLoading = true;
  105445. var model = this.modelLoader.load(configuration);
  105446. this.lastUsedLoader = model.loader;
  105447. model.onLoadErrorObservable.add(function (errorObject) {
  105448. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  105449. });
  105450. model.onLoadProgressObservable.add(function (progressEvent) {
  105451. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  105452. });
  105453. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  105454. model.onLoadedObservable.add(function () {
  105455. _this._isLoading = false;
  105456. });
  105457. return model;
  105458. };
  105459. /**
  105460. * load a model using the provided configuration.
  105461. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  105462. * If you want to attach to the observables of the model, use initModle instead.
  105463. *
  105464. * @param modelConfig the model configuration or URL to load.
  105465. * @param clearScene Should the scene be cleared before loading the model
  105466. * @returns a Promise the fulfills when the model finished loading successfully.
  105467. */
  105468. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  105469. var _this = this;
  105470. if (clearScene === void 0) { clearScene = true; }
  105471. if (this._isLoading) {
  105472. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  105473. return Promise.reject("another model is curently being loaded.");
  105474. }
  105475. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  105476. if (!scene)
  105477. return _this.sceneManager.initScene(_this.configuration.scene, _this.configuration.optimizer);
  105478. return scene;
  105479. }).then(function () {
  105480. var model = _this.initModel(modelConfig, clearScene);
  105481. return new Promise(function (resolve, reject) {
  105482. // at this point, configuration.model is an object, not a string
  105483. model.onLoadedObservable.add(function () {
  105484. resolve(model);
  105485. });
  105486. model.onLoadErrorObservable.add(function (error) {
  105487. reject(error);
  105488. });
  105489. });
  105490. });
  105491. };
  105492. AbstractViewer.prototype._initTelemetryEvents = function () {
  105493. var _this = this;
  105494. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps());
  105495. telemetryManager_1.telemetryManager.broadcast("Platform Details", this.baseId, {
  105496. userAgent: navigator.userAgent,
  105497. platform: navigator.platform
  105498. });
  105499. telemetryManager_1.telemetryManager.flushWebGLErrors(this.engine, this.baseId);
  105500. var trackFPS = function () {
  105501. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this.baseId, { fps: _this.engine.getFps() });
  105502. };
  105503. trackFPS();
  105504. // Track the FPS again after 60 seconds
  105505. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  105506. };
  105507. /**
  105508. * Injects all the spectre shader in the babylon shader store
  105509. */
  105510. AbstractViewer.prototype._injectCustomShaders = function () {
  105511. var customShaders = this.configuration.customShaders;
  105512. // Inject all the spectre shader in the babylon shader store.
  105513. if (!customShaders) {
  105514. return;
  105515. }
  105516. if (customShaders.shaders) {
  105517. Object.keys(customShaders.shaders).forEach(function (key) {
  105518. // typescript considers a callback "unsafe", so... '!'
  105519. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  105520. });
  105521. }
  105522. if (customShaders.includes) {
  105523. Object.keys(customShaders.includes).forEach(function (key) {
  105524. // typescript considers a callback "unsafe", so... '!'
  105525. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  105526. });
  105527. }
  105528. };
  105529. return AbstractViewer;
  105530. }());
  105531. exports.AbstractViewer = AbstractViewer;
  105532. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3ZpZXdlci92aWV3ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpREFBZ0Q7QUFDaEQseURBQXdEO0FBQ3hELGtEQUE4RDtBQUM5RCx1Q0FBdU07QUFJdk0scURBQW9EO0FBQ3BELG9EQUF5RDtBQUN6RCxpRUFBZ0U7QUFDaEUsK0JBQXVDO0FBQ3ZDLHFFQUFvRTtBQUN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HQUFHLENBQUMsQ0FBQztZQUM1RCxDQUFDLENBQUMsQ0FBQztTQUNOO1FBQ0QsSUFBSSxhQUFhLENBQUMsUUFBUSxFQUFFO1lBQ3hCLE1BQU0sQ0FBQyxJQUFJLENBQUMsYUFBYSxDQUFDLFFBQVEsQ0FBQyxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7Z0JBQzNDLHNEQUFzRDtnQkFDdEQsa0JBQU0sQ0FBQyxvQkFBb0IsQ0FBQyxHQUFHLENBQUMsR0FBRyxhQUFjLENBQUMsUUFBUyxDQUFDLEdBQUcsQ0FBQyxDQUFDO1lBQ3JFLENBQUMsQ0FBQyxDQUFDO1NBQ047SUFDTCxDQUFDO0lBQ0wscUJBQUM7QUFBRCxDQUFDLEFBL3RCRCxJQSt0QkM7QUEvdEJxQix3Q0FBYyJ9
  105533. /***/ }),
  105534. /* 10 */
  105535. /***/ (function(module, exports, __webpack_require__) {
  105536. "use strict";
  105537. function __export(m) {
  105538. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  105539. }
  105540. Object.defineProperty(exports, "__esModule", { value: true });
  105541. __export(__webpack_require__(11));
  105542. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLHFDQUFnQyJ9
  105543. /***/ }),
  105544. /* 11 */
  105545. /***/ (function(module, exports, __webpack_require__) {
  105546. "use strict";
  105547. Object.defineProperty(exports, "__esModule", { value: true });
  105548. function getConfigurationKey(key, configObject) {
  105549. var splits = key.split('.');
  105550. if (splits.length === 0 || !configObject)
  105551. return;
  105552. else if (splits.length === 1) {
  105553. if (configObject[key] !== undefined) {
  105554. return configObject[key];
  105555. }
  105556. }
  105557. else {
  105558. var firstKey = splits.shift();
  105559. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  105560. }
  105561. }
  105562. exports.getConfigurationKey = getConfigurationKey;
  105563. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFHQSw2QkFBb0MsR0FBVyxFQUFFLFlBQWlCO0lBQzlELElBQUksTUFBTSxHQUFHLEdBQUcsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7SUFFNUIsSUFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsSUFBSSxDQUFDLFlBQVk7UUFBRSxPQUFPO1NBQzVDLElBQUksTUFBTSxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDMUIsSUFBSSxZQUFZLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO1lBQ2pDLE9BQU8sWUFBWSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1NBQzVCO0tBQ0o7U0FBTTtRQUNILElBQUksUUFBUSxHQUFHLE1BQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUM5QixPQUFPLG1CQUFtQixDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsWUFBWSxDQUFDLFFBQVMsQ0FBQyxDQUFDLENBQUE7S0FDeEU7QUFDTCxDQUFDO0FBWkQsa0RBWUMifQ==
  105564. /***/ }),
  105565. /* 12 */
  105566. /***/ (function(module, exports, __webpack_require__) {
  105567. "use strict";
  105568. Object.defineProperty(exports, "__esModule", { value: true });
  105569. var babylonjs_1 = __webpack_require__(0);
  105570. /**
  105571. * A minimal WebGL cubemap descriptor
  105572. */
  105573. var TextureCube = /** @class */ (function () {
  105574. /**
  105575. * constructor
  105576. * @param internalFormat WebGL pixel format for the texture on the GPU
  105577. * @param type WebGL pixel type of the supplied data and texture on the GPU
  105578. * @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
  105579. */
  105580. function TextureCube(internalFormat, type, source) {
  105581. if (source === void 0) { source = []; }
  105582. this.internalFormat = internalFormat;
  105583. this.type = type;
  105584. this.source = source;
  105585. }
  105586. Object.defineProperty(TextureCube.prototype, "Width", {
  105587. /**
  105588. * Returns the width of a face of the texture or 0 if not available
  105589. */
  105590. get: function () {
  105591. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  105592. },
  105593. enumerable: true,
  105594. configurable: true
  105595. });
  105596. Object.defineProperty(TextureCube.prototype, "Height", {
  105597. /**
  105598. * Returns the height of a face of the texture or 0 if not available
  105599. */
  105600. get: function () {
  105601. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  105602. },
  105603. enumerable: true,
  105604. configurable: true
  105605. });
  105606. return TextureCube;
  105607. }());
  105608. exports.TextureCube = TextureCube;
  105609. /**
  105610. * A static class providing methods to aid working with Bablyon textures.
  105611. */
  105612. var TextureUtils = /** @class */ (function () {
  105613. function TextureUtils() {
  105614. }
  105615. /**
  105616. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  105617. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  105618. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  105619. * @param scene A Babylon Scene instance
  105620. * @param textureCube A Spectre TextureCube object
  105621. * @param parameters WebGL texture sampling parameters
  105622. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  105623. * @param environment Specifies that the texture will be used as an environment
  105624. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  105625. * @return Babylon cube texture
  105626. */
  105627. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  105628. if (environment === void 0) { environment = false; }
  105629. if (singleLod === void 0) { singleLod = false; }
  105630. if (!textureCube)
  105631. throw new Error("no texture cube provided");
  105632. var parameters;
  105633. if (environment) {
  105634. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  105635. }
  105636. else {
  105637. parameters = {
  105638. magFilter: 9728 /* NEAREST */,
  105639. minFilter: 9728 /* NEAREST */,
  105640. wrapS: 33071 /* CLAMP_TO_EDGE */,
  105641. wrapT: 33071 /* CLAMP_TO_EDGE */
  105642. };
  105643. }
  105644. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  105645. var babylonTexture = textureCube[key];
  105646. if (!babylonTexture) {
  105647. //initialize babylon texture
  105648. babylonTexture = new babylonjs_1.CubeTexture('', scene);
  105649. if (environment) {
  105650. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  105651. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  105652. }
  105653. babylonTexture.gammaSpace = false;
  105654. var internalTexture_1 = new babylonjs_1.InternalTexture(scene.getEngine(), babylonjs_1.InternalTexture.DATASOURCE_CUBERAW);
  105655. var glTexture_1 = internalTexture_1._webGLTexture;
  105656. //babylon properties
  105657. internalTexture_1.isCube = true;
  105658. internalTexture_1.generateMipMaps = false;
  105659. babylonTexture._texture = internalTexture_1;
  105660. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  105661. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  105662. var texturesUploaded_1 = 0;
  105663. var textureComplete = function () {
  105664. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  105665. };
  105666. var uploadFace = function (i, level, face) {
  105667. if (!glTexture_1)
  105668. return;
  105669. if (i === 0 && level === 0) {
  105670. internalTexture_1.width = face.width;
  105671. internalTexture_1.height = face.height;
  105672. }
  105673. var gl = (scene.getEngine())._gl;
  105674. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  105675. scene.getEngine()._unpackFlipY(false);
  105676. if (face instanceof HTMLElement || face instanceof ImageData) {
  105677. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  105678. }
  105679. else {
  105680. var textureData = face;
  105681. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  105682. }
  105683. texturesUploaded_1++;
  105684. if (textureComplete()) {
  105685. //generate mipmaps
  105686. if (automaticMipmaps) {
  105687. var w = face.width;
  105688. var h = face.height;
  105689. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  105690. if (isPot) {
  105691. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  105692. }
  105693. }
  105694. // Upload Separate lods in case there is no support for texture lod.
  105695. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  105696. var mipSlices = 3;
  105697. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  105698. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  105699. var lod = textureCube[lodKey];
  105700. //initialize lod texture if it doesn't already exist
  105701. if (lod == null && textureCube.Width) {
  105702. //compute LOD from even spacing in smoothness (matching shader calculation)
  105703. var smoothness = i_1 / (mipSlices - 1);
  105704. var roughness = 1 - smoothness;
  105705. var kMinimumVariance = 0.0005;
  105706. var alphaG = roughness * roughness + kMinimumVariance;
  105707. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  105708. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (babylonjs_1.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  105709. var maxLODIndex = textureCube.source.length - 1;
  105710. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  105711. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  105712. if (i_1 === 0) {
  105713. internalTexture_1._lodTextureLow = lod;
  105714. }
  105715. else if (i_1 === 1) {
  105716. internalTexture_1._lodTextureMid = lod;
  105717. }
  105718. else {
  105719. internalTexture_1._lodTextureHigh = lod;
  105720. }
  105721. textureCube[lodKey] = lod;
  105722. }
  105723. }
  105724. }
  105725. internalTexture_1.isReady = true;
  105726. }
  105727. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  105728. scene.getEngine().resetTextureCache();
  105729. };
  105730. var _loop_1 = function (i) {
  105731. var faces = textureCube.source[i];
  105732. var _loop_2 = function (j) {
  105733. var face = faces[j];
  105734. if (face instanceof HTMLImageElement && !face.complete) {
  105735. face.addEventListener('load', function () {
  105736. uploadFace(j, i, face);
  105737. }, false);
  105738. }
  105739. else {
  105740. uploadFace(j, i, face);
  105741. }
  105742. };
  105743. for (var j = 0; j < faces.length; j++) {
  105744. _loop_2(j);
  105745. }
  105746. };
  105747. for (var i = 0; i <= maxMipLevel_1; i++) {
  105748. _loop_1(i);
  105749. }
  105750. scene.getEngine().resetTextureCache();
  105751. babylonTexture.isReady = function () {
  105752. return textureComplete();
  105753. };
  105754. textureCube[key] = babylonTexture;
  105755. }
  105756. return babylonTexture;
  105757. };
  105758. /**
  105759. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  105760. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  105761. * @param parameters Spectre SamplingParameters to apply
  105762. */
  105763. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  105764. var scene = babylonTexture.getScene();
  105765. if (!scene)
  105766. return;
  105767. var gl = (scene.getEngine())._gl;
  105768. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  105769. var internalTexture = babylonTexture._texture;
  105770. if (!internalTexture)
  105771. return;
  105772. var glTexture = internalTexture._webGLTexture;
  105773. gl.bindTexture(target, glTexture);
  105774. if (parameters.magFilter != null)
  105775. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  105776. if (parameters.minFilter != null)
  105777. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  105778. if (parameters.wrapS != null)
  105779. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  105780. if (parameters.wrapT != null)
  105781. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  105782. //set babylon wrap modes from sampling parameter
  105783. switch (parameters.wrapS) {
  105784. case 10497 /* REPEAT */:
  105785. babylonTexture.wrapU = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  105786. break;
  105787. case 33071 /* CLAMP_TO_EDGE */:
  105788. babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  105789. break;
  105790. case 33648 /* MIRRORED_REPEAT */:
  105791. babylonTexture.wrapU = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  105792. break;
  105793. default: babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  105794. }
  105795. switch (parameters.wrapT) {
  105796. case 10497 /* REPEAT */:
  105797. babylonTexture.wrapV = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  105798. break;
  105799. case 33071 /* CLAMP_TO_EDGE */:
  105800. babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  105801. break;
  105802. case 33648 /* MIRRORED_REPEAT */:
  105803. babylonTexture.wrapV = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  105804. break;
  105805. default: babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  105806. }
  105807. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  105808. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  105809. if (anisotropicExt) {
  105810. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  105811. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  105812. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  105813. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  105814. }
  105815. }
  105816. gl.bindTexture(target, null);
  105817. scene.getEngine().resetTextureCache();
  105818. };
  105819. /**
  105820. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  105821. */
  105822. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  105823. /**
  105824. * Controls anisotropic filtering for deserialized textures.
  105825. */
  105826. TextureUtils.MaxAnisotropy = 4;
  105827. TextureUtils._EnvironmentSampling = {
  105828. magFilter: 9729 /* LINEAR */,
  105829. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  105830. wrapS: 33071 /* CLAMP_TO_EDGE */,
  105831. wrapT: 33071 /* CLAMP_TO_EDGE */,
  105832. maxAnisotropy: 1
  105833. };
  105834. TextureUtils._EnvironmentSingleMipSampling = {
  105835. magFilter: 9729 /* LINEAR */,
  105836. minFilter: 9729 /* LINEAR */,
  105837. wrapS: 33071 /* CLAMP_TO_EDGE */,
  105838. wrapT: 33071 /* CLAMP_TO_EDGE */,
  105839. maxAnisotropy: 1
  105840. };
  105841. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  105842. /**
  105843. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  105844. */
  105845. TextureUtils.EnvironmentLODScale = 0.8;
  105846. /**
  105847. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  105848. */
  105849. TextureUtils.EnvironmentLODOffset = 1.0;
  105850. return TextureUtils;
  105851. }());
  105852. exports.TextureUtils = TextureUtils;
  105853. //# sourceMappingURL=data:application/json;base64,ey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LEdBQUcsQ0FBQztJQUM3QyxtQkFBQztDQUFBLEFBMVBELElBMFBDO0FBMVBZLG9DQUFZIn0=
  105854. /***/ }),
  105855. /* 13 */
  105856. /***/ (function(module, exports, __webpack_require__) {
  105857. "use strict";
  105858. Object.defineProperty(exports, "__esModule", { value: true });
  105859. var babylonjs_1 = __webpack_require__(0);
  105860. var babylonjs_loaders_1 = __webpack_require__(14);
  105861. var viewerModel_1 = __webpack_require__(5);
  105862. var _1 = __webpack_require__(56);
  105863. /**
  105864. * An instance of the class is in charge of loading the model correctly.
  105865. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  105866. *
  105867. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  105868. */
  105869. var ModelLoader = /** @class */ (function () {
  105870. /**
  105871. * Create a new Model loader
  105872. * @param _viewer the viewer using this model loader
  105873. */
  105874. function ModelLoader(_observablesManager, _configurationContainer) {
  105875. this._observablesManager = _observablesManager;
  105876. this._configurationContainer = _configurationContainer;
  105877. this._disposed = false;
  105878. this._loaders = [];
  105879. this._loadId = 0;
  105880. this._plugins = [];
  105881. }
  105882. /**
  105883. * Adds a new plugin to the loader process.
  105884. *
  105885. * @param plugin the plugin name or the plugin itself
  105886. */
  105887. ModelLoader.prototype.addPlugin = function (plugin) {
  105888. var actualPlugin = {};
  105889. if (typeof plugin === 'string') {
  105890. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  105891. if (loadedPlugin) {
  105892. actualPlugin = loadedPlugin;
  105893. }
  105894. }
  105895. else {
  105896. actualPlugin = plugin;
  105897. }
  105898. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  105899. this._plugins.push(actualPlugin);
  105900. }
  105901. };
  105902. /**
  105903. * Load a model using predefined configuration
  105904. * @param modelConfiguration the modelConfiguration to use to load the model
  105905. */
  105906. ModelLoader.prototype.load = function (modelConfiguration) {
  105907. var _this = this;
  105908. var model = new viewerModel_1.ViewerModel(this._observablesManager, modelConfiguration, this._configurationContainer);
  105909. model.loadId = this._loadId++;
  105910. var base = "";
  105911. var filename;
  105912. if (modelConfiguration.file) {
  105913. base = "file:";
  105914. filename = modelConfiguration.file;
  105915. }
  105916. else if (modelConfiguration.url) {
  105917. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  105918. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  105919. }
  105920. if (!filename || !base) {
  105921. model.state = viewerModel_1.ModelState.ERROR;
  105922. babylonjs_1.Tools.Error("No URL provided");
  105923. return model;
  105924. }
  105925. var plugin = modelConfiguration.loader;
  105926. var scene = model.rootMesh.getScene();
  105927. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  105928. meshes.forEach(function (mesh) {
  105929. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  105930. model.addMesh(mesh);
  105931. });
  105932. model.particleSystems = particleSystems;
  105933. model.skeletons = skeletons;
  105934. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  105935. var animationGroup = animationGroups_1[_i];
  105936. model.addAnimationGroup(animationGroup);
  105937. }
  105938. _this._checkAndRun("onLoaded", model);
  105939. scene.executeWhenReady(function () {
  105940. model.onLoadedObservable.notifyObservers(model);
  105941. });
  105942. }, function (progressEvent) {
  105943. _this._checkAndRun("onProgress", progressEvent);
  105944. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  105945. }, function (scene, m, exception) {
  105946. model.state = viewerModel_1.ModelState.ERROR;
  105947. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  105948. _this._checkAndRun("onError", m, exception);
  105949. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  105950. }, plugin);
  105951. if (model.loader.name === "gltf") {
  105952. var gltfLoader_1 = model.loader;
  105953. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  105954. gltfLoader_1.compileMaterials = true;
  105955. if (!modelConfiguration.file) {
  105956. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  105957. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  105958. };
  105959. }
  105960. // if ground is set to "mirror":
  105961. if (this._configurationContainer
  105962. && this._configurationContainer.configuration
  105963. && this._configurationContainer.configuration.ground
  105964. && typeof this._configurationContainer.configuration.ground === 'object'
  105965. && this._configurationContainer.configuration.ground.mirror) {
  105966. gltfLoader_1.useClipPlane = true;
  105967. }
  105968. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  105969. gltfLoader_1[functionName].add(function (payload) {
  105970. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  105971. });
  105972. });
  105973. gltfLoader_1.onParsedObservable.add(function (data) {
  105974. if (data && data.json && data.json['asset']) {
  105975. model.loadInfo = data.json['asset'];
  105976. }
  105977. });
  105978. gltfLoader_1.onCompleteObservable.add(function () {
  105979. model.loaderDone = true;
  105980. });
  105981. }
  105982. else {
  105983. model.loaderDone = true;
  105984. }
  105985. this._checkAndRun("onInit", model.loader, model);
  105986. this._loaders.push(model.loader);
  105987. return model;
  105988. };
  105989. ModelLoader.prototype.cancelLoad = function (model) {
  105990. var loader = model.loader || this._loaders[model.loadId];
  105991. // ATM only available in the GLTF Loader
  105992. if (loader && loader.name === "gltf") {
  105993. var gltfLoader = loader;
  105994. gltfLoader.dispose();
  105995. model.state = viewerModel_1.ModelState.CANCELED;
  105996. }
  105997. else {
  105998. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  105999. }
  106000. };
  106001. /**
  106002. * dispose the model loader.
  106003. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  106004. */
  106005. ModelLoader.prototype.dispose = function () {
  106006. this._loaders.forEach(function (loader) {
  106007. if (loader.name === "gltf") {
  106008. loader.dispose();
  106009. }
  106010. });
  106011. this._loaders.length = 0;
  106012. this._disposed = true;
  106013. };
  106014. ModelLoader.prototype._checkAndRun = function (functionName) {
  106015. var _this = this;
  106016. var payload = [];
  106017. for (var _i = 1; _i < arguments.length; _i++) {
  106018. payload[_i - 1] = arguments[_i];
  106019. }
  106020. if (this._disposed)
  106021. return;
  106022. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  106023. try {
  106024. plugin[functionName].apply(_this, payload);
  106025. }
  106026. catch (e) { }
  106027. });
  106028. };
  106029. return ModelLoader;
  106030. }());
  106031. exports.ModelLoader = ModelLoader;
  106032. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxMb2FkZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbG9hZGVyL21vZGVsTG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQWtHO0FBQ2xHLHVEQUFpRjtBQUtqRixvREFBK0Q7QUFDL0QsK0JBQWtFO0FBRWxFOzs7OztHQUtHO0FBQ0g7SUFTSTs7O09BR0c7SUFDSCxxQkFBb0IsbUJBQXVDLEVBQVUsdUJBQWdEO1FBQWpHLHdCQUFtQixHQUFuQixtQkFBbUIsQ0FBb0I7UUFBVSw0QkFBdUIsR0FBdkIsdUJBQXVCLENBQXlCO1FBVjdHLGNBQVMsR0FBRyxLQUFLLENBQUM7UUFXdEIsSUFBSSxDQUFDLFFBQVEsR0FBRyxFQUFFLENBQUM7UUFDbkIsSUFBSSxDQUFDLE9BQU8sR0FBRyxDQUFDLENBQUM7UUFDakIsSUFBSSxDQUFDLFFBQVEsR0FBRyxFQUFFLENBQUM7SUFDdkIsQ0FBQztJQUVEOzs7O09BSUc7SUFDSSwrQkFBUyxHQUFoQixVQUFpQixNQUE4QjtRQUMzQyxJQUFJLFlBQVksR0FBa0IsRUFBRSxDQUFDO1FBQ3JDLElBQUksT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sQ0FBQyxZQUFZLENBQUMsQ0FBQyxLQUFLLENBQUMsS0FBSSxFQUFFLE9BQU8sQ0FBQyxDQUFDO2FBQzdDO1lBQUMsT0FBTyxDQUFDLEVBQUUsR0FBRztRQUNuQixDQUFDLENBQUMsQ0FBQTtJQUNOLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUFoTEQsSUFnTEM7QUFoTFksa0NBQVcifQ==
  106033. /***/ }),
  106034. /* 14 */
  106035. /***/ (function(module, exports, __webpack_require__) {
  106036. (function universalModuleDefinition(root, factory) {
  106037. var amdDependencies = [];
  106038. var BABYLON = root.BABYLON || this.BABYLON;
  106039. if(true) {
  106040. BABYLON = BABYLON || __webpack_require__(0);
  106041. module.exports = factory(BABYLON);
  106042. } else if(typeof define === 'function' && define.amd) {
  106043. amdDependencies.push("babylonjs");
  106044. define("babylonjs-loaders", amdDependencies, factory);
  106045. } else if(typeof exports === 'object') {
  106046. BABYLON = BABYLON || require("babylonjs");
  106047. exports["babylonjs-loaders"] = factory(BABYLON);
  106048. } else {
  106049. root["BABYLON"] = factory(BABYLON);
  106050. }
  106051. })(this, function(BABYLON) {
  106052. BABYLON = BABYLON || this.BABYLON;
  106053. 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};
  106054. 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)}}();
  106055. var BABYLON;
  106056. (function (BABYLON) {
  106057. var STLFileLoader = /** @class */ (function () {
  106058. function STLFileLoader() {
  106059. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  106060. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  106061. 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;
  106062. 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;
  106063. this.name = "stl";
  106064. // force data to come in as an ArrayBuffer
  106065. // we'll convert to string if it looks like it's an ASCII .stl
  106066. this.extensions = {
  106067. ".stl": { isBinary: true },
  106068. };
  106069. }
  106070. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  106071. var matches;
  106072. if (typeof data !== "string") {
  106073. if (this.isBinary(data)) {
  106074. // binary .stl
  106075. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  106076. this.parseBinary(babylonMesh, data);
  106077. if (meshes) {
  106078. meshes.push(babylonMesh);
  106079. }
  106080. return true;
  106081. }
  106082. // ASCII .stl
  106083. // convert to string
  106084. var array_buffer = new Uint8Array(data);
  106085. var str = '';
  106086. for (var i = 0; i < data.byteLength; i++) {
  106087. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  106088. }
  106089. data = str;
  106090. }
  106091. //if arrived here, data is a string, containing the STLA data.
  106092. while (matches = this.solidPattern.exec(data)) {
  106093. var meshName = matches[1];
  106094. var meshNameFromEnd = matches[3];
  106095. if (meshName != meshNameFromEnd) {
  106096. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  106097. return false;
  106098. }
  106099. // check meshesNames
  106100. if (meshesNames && meshName) {
  106101. if (meshesNames instanceof Array) {
  106102. if (!meshesNames.indexOf(meshName)) {
  106103. continue;
  106104. }
  106105. }
  106106. else {
  106107. if (meshName !== meshesNames) {
  106108. continue;
  106109. }
  106110. }
  106111. }
  106112. // stl mesh name can be empty as well
  106113. meshName = meshName || "stlmesh";
  106114. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  106115. this.parseASCII(babylonMesh, matches[2]);
  106116. if (meshes) {
  106117. meshes.push(babylonMesh);
  106118. }
  106119. }
  106120. return true;
  106121. };
  106122. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  106123. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  106124. if (result) {
  106125. scene.createDefaultCameraOrLight();
  106126. }
  106127. return result;
  106128. };
  106129. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  106130. var container = new BABYLON.AssetContainer(scene);
  106131. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  106132. container.removeAllFromScene();
  106133. return container;
  106134. };
  106135. STLFileLoader.prototype.isBinary = function (data) {
  106136. // check if file size is correct for binary stl
  106137. var faceSize, nFaces, reader;
  106138. reader = new DataView(data);
  106139. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  106140. nFaces = reader.getUint32(80, true);
  106141. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  106142. return true;
  106143. }
  106144. // check characters higher than ASCII to confirm binary
  106145. var fileLength = reader.byteLength;
  106146. for (var index = 0; index < fileLength; index++) {
  106147. if (reader.getUint8(index) > 127) {
  106148. return true;
  106149. }
  106150. }
  106151. return false;
  106152. };
  106153. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  106154. var reader = new DataView(data);
  106155. var faces = reader.getUint32(80, true);
  106156. var dataOffset = 84;
  106157. var faceLength = 12 * 4 + 2;
  106158. var offset = 0;
  106159. var positions = new Float32Array(faces * 3 * 3);
  106160. var normals = new Float32Array(faces * 3 * 3);
  106161. var indices = new Uint32Array(faces * 3);
  106162. var indicesCount = 0;
  106163. for (var face = 0; face < faces; face++) {
  106164. var start = dataOffset + face * faceLength;
  106165. var normalX = reader.getFloat32(start, true);
  106166. var normalY = reader.getFloat32(start + 4, true);
  106167. var normalZ = reader.getFloat32(start + 8, true);
  106168. for (var i = 1; i <= 3; i++) {
  106169. var vertexstart = start + i * 12;
  106170. // ordering is intentional to match ascii import
  106171. positions[offset] = reader.getFloat32(vertexstart, true);
  106172. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  106173. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  106174. normals[offset] = normalX;
  106175. normals[offset + 2] = normalY;
  106176. normals[offset + 1] = normalZ;
  106177. offset += 3;
  106178. }
  106179. indices[indicesCount] = indicesCount++;
  106180. indices[indicesCount] = indicesCount++;
  106181. indices[indicesCount] = indicesCount++;
  106182. }
  106183. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  106184. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  106185. mesh.setIndices(indices);
  106186. mesh.computeWorldMatrix(true);
  106187. };
  106188. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  106189. var positions = [];
  106190. var normals = [];
  106191. var indices = [];
  106192. var indicesCount = 0;
  106193. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  106194. var matches;
  106195. while (matches = this.facetsPattern.exec(solidData)) {
  106196. var facet = matches[1];
  106197. //one normal per face
  106198. var normalMatches = this.normalPattern.exec(facet);
  106199. this.normalPattern.lastIndex = 0;
  106200. if (!normalMatches) {
  106201. continue;
  106202. }
  106203. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  106204. var vertexMatch;
  106205. while (vertexMatch = this.vertexPattern.exec(facet)) {
  106206. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  106207. normals.push(normal[0], normal[1], normal[2]);
  106208. }
  106209. indices.push(indicesCount++, indicesCount++, indicesCount++);
  106210. this.vertexPattern.lastIndex = 0;
  106211. }
  106212. this.facetsPattern.lastIndex = 0;
  106213. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  106214. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  106215. mesh.setIndices(indices);
  106216. mesh.computeWorldMatrix(true);
  106217. };
  106218. return STLFileLoader;
  106219. }());
  106220. BABYLON.STLFileLoader = STLFileLoader;
  106221. if (BABYLON.SceneLoader) {
  106222. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  106223. }
  106224. })(BABYLON || (BABYLON = {}));
  106225. //# sourceMappingURL=babylon.stlFileLoader.js.map
  106226. var BABYLON;
  106227. (function (BABYLON) {
  106228. /**
  106229. * Class reading and parsing the MTL file bundled with the obj file.
  106230. */
  106231. var MTLFileLoader = /** @class */ (function () {
  106232. function MTLFileLoader() {
  106233. // All material loaded from the mtl will be set here
  106234. this.materials = [];
  106235. }
  106236. /**
  106237. * This function will read the mtl file and create each material described inside
  106238. * This function could be improve by adding :
  106239. * -some component missing (Ni, Tf...)
  106240. * -including the specific options available
  106241. *
  106242. * @param scene
  106243. * @param data
  106244. * @param rootUrl
  106245. */
  106246. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  106247. if (data instanceof ArrayBuffer) {
  106248. return;
  106249. }
  106250. //Split the lines from the file
  106251. var lines = data.split('\n');
  106252. //Space char
  106253. var delimiter_pattern = /\s+/;
  106254. //Array with RGB colors
  106255. var color;
  106256. //New material
  106257. var material = null;
  106258. //Look at each line
  106259. for (var i = 0; i < lines.length; i++) {
  106260. var line = lines[i].trim();
  106261. // Blank line or comment
  106262. if (line.length === 0 || line.charAt(0) === '#') {
  106263. continue;
  106264. }
  106265. //Get the first parameter (keyword)
  106266. var pos = line.indexOf(' ');
  106267. var key = (pos >= 0) ? line.substring(0, pos) : line;
  106268. key = key.toLowerCase();
  106269. //Get the data following the key
  106270. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  106271. //This mtl keyword will create the new material
  106272. if (key === "newmtl") {
  106273. //Check if it is the first material.
  106274. // Materials specifications are described after this keyword.
  106275. if (material) {
  106276. //Add the previous material in the material array.
  106277. this.materials.push(material);
  106278. }
  106279. //Create a new material.
  106280. // value is the name of the material read in the mtl file
  106281. material = new BABYLON.StandardMaterial(value, scene);
  106282. }
  106283. else if (key === "kd" && material) {
  106284. // Diffuse color (color under white light) using RGB values
  106285. //value = "r g b"
  106286. color = value.split(delimiter_pattern, 3).map(parseFloat);
  106287. //color = [r,g,b]
  106288. //Set tghe color into the material
  106289. material.diffuseColor = BABYLON.Color3.FromArray(color);
  106290. }
  106291. else if (key === "ka" && material) {
  106292. // Ambient color (color under shadow) using RGB values
  106293. //value = "r g b"
  106294. color = value.split(delimiter_pattern, 3).map(parseFloat);
  106295. //color = [r,g,b]
  106296. //Set tghe color into the material
  106297. material.ambientColor = BABYLON.Color3.FromArray(color);
  106298. }
  106299. else if (key === "ks" && material) {
  106300. // Specular color (color when light is reflected from shiny surface) using RGB values
  106301. //value = "r g b"
  106302. color = value.split(delimiter_pattern, 3).map(parseFloat);
  106303. //color = [r,g,b]
  106304. //Set the color into the material
  106305. material.specularColor = BABYLON.Color3.FromArray(color);
  106306. }
  106307. else if (key === "ke" && material) {
  106308. // Emissive color using RGB values
  106309. color = value.split(delimiter_pattern, 3).map(parseFloat);
  106310. material.emissiveColor = BABYLON.Color3.FromArray(color);
  106311. }
  106312. else if (key === "ns" && material) {
  106313. //value = "Integer"
  106314. material.specularPower = parseFloat(value);
  106315. }
  106316. else if (key === "d" && material) {
  106317. //d is dissolve for current material. It mean alpha for BABYLON
  106318. material.alpha = parseFloat(value);
  106319. //Texture
  106320. //This part can be improved by adding the possible options of texture
  106321. }
  106322. else if (key === "map_ka" && material) {
  106323. // ambient texture map with a loaded image
  106324. //We must first get the folder of the image
  106325. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  106326. }
  106327. else if (key === "map_kd" && material) {
  106328. // Diffuse texture map with a loaded image
  106329. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  106330. }
  106331. else if (key === "map_ks" && material) {
  106332. // Specular texture map with a loaded image
  106333. //We must first get the folder of the image
  106334. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  106335. }
  106336. else if (key === "map_ns") {
  106337. //Specular
  106338. //Specular highlight component
  106339. //We must first get the folder of the image
  106340. //
  106341. //Not supported by BABYLON
  106342. //
  106343. // continue;
  106344. }
  106345. else if (key === "map_bump" && material) {
  106346. //The bump texture
  106347. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  106348. }
  106349. else if (key === "map_d" && material) {
  106350. // The dissolve of the material
  106351. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  106352. //Options for illumination
  106353. }
  106354. else if (key === "illum") {
  106355. //Illumination
  106356. if (value === "0") {
  106357. //That mean Kd == Kd
  106358. }
  106359. else if (value === "1") {
  106360. //Color on and Ambient on
  106361. }
  106362. else if (value === "2") {
  106363. //Highlight on
  106364. }
  106365. else if (value === "3") {
  106366. //Reflection on and Ray trace on
  106367. }
  106368. else if (value === "4") {
  106369. //Transparency: Glass on, Reflection: Ray trace on
  106370. }
  106371. else if (value === "5") {
  106372. //Reflection: Fresnel on and Ray trace on
  106373. }
  106374. else if (value === "6") {
  106375. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  106376. }
  106377. else if (value === "7") {
  106378. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  106379. }
  106380. else if (value === "8") {
  106381. //Reflection on and Ray trace off
  106382. }
  106383. else if (value === "9") {
  106384. //Transparency: Glass on, Reflection: Ray trace off
  106385. }
  106386. else if (value === "10") {
  106387. //Casts shadows onto invisible surfaces
  106388. }
  106389. }
  106390. else {
  106391. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  106392. }
  106393. }
  106394. //At the end of the file, add the last material
  106395. if (material) {
  106396. this.materials.push(material);
  106397. }
  106398. };
  106399. /**
  106400. * Gets the texture for the material.
  106401. *
  106402. * If the material is imported from input file,
  106403. * We sanitize the url to ensure it takes the textre from aside the material.
  106404. *
  106405. * @param rootUrl The root url to load from
  106406. * @param value The value stored in the mtl
  106407. * @return The Texture
  106408. */
  106409. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  106410. if (!value) {
  106411. return null;
  106412. }
  106413. var url = rootUrl;
  106414. // Load from input file.
  106415. if (rootUrl === "file:") {
  106416. var lastDelimiter = value.lastIndexOf("\\");
  106417. if (lastDelimiter === -1) {
  106418. lastDelimiter = value.lastIndexOf("/");
  106419. }
  106420. if (lastDelimiter > -1) {
  106421. url += value.substr(lastDelimiter + 1);
  106422. }
  106423. else {
  106424. url += value;
  106425. }
  106426. }
  106427. // Not from input file.
  106428. else {
  106429. url += value;
  106430. }
  106431. return new BABYLON.Texture(url, scene);
  106432. };
  106433. return MTLFileLoader;
  106434. }());
  106435. BABYLON.MTLFileLoader = MTLFileLoader;
  106436. var OBJFileLoader = /** @class */ (function () {
  106437. function OBJFileLoader() {
  106438. this.name = "obj";
  106439. this.extensions = ".obj";
  106440. this.obj = /^o/;
  106441. this.group = /^g/;
  106442. this.mtllib = /^mtllib /;
  106443. this.usemtl = /^usemtl /;
  106444. this.smooth = /^s /;
  106445. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  106446. // vn float float float
  106447. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  106448. // vt float float
  106449. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  106450. // f vertex vertex vertex ...
  106451. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  106452. // f vertex/uvs vertex/uvs vertex/uvs ...
  106453. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  106454. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  106455. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  106456. // f vertex//normal vertex//normal vertex//normal ...
  106457. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  106458. }
  106459. /**
  106460. * Calls synchronously the MTL file attached to this obj.
  106461. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  106462. * Without this function materials are not displayed in the first frame (but displayed after).
  106463. * In consequence it is impossible to get material information in your HTML file
  106464. *
  106465. * @param url The URL of the MTL file
  106466. * @param rootUrl
  106467. * @param onSuccess Callback function to be called when the MTL file is loaded
  106468. * @private
  106469. */
  106470. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  106471. //The complete path to the mtl file
  106472. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  106473. // Loads through the babylon tools to allow fileInput search.
  106474. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  106475. };
  106476. OBJFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106477. //get the meshes from OBJ file
  106478. return this._parseSolid(meshesNames, scene, data, rootUrl).then(function (meshes) {
  106479. return {
  106480. meshes: meshes,
  106481. particleSystems: [],
  106482. skeletons: [],
  106483. animationGroups: []
  106484. };
  106485. });
  106486. };
  106487. OBJFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106488. //Get the 3D model
  106489. return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(function () {
  106490. // return void
  106491. });
  106492. };
  106493. OBJFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  106494. return this.importMeshAsync(null, scene, data, rootUrl).then(function (result) {
  106495. var container = new BABYLON.AssetContainer(scene);
  106496. result.meshes.forEach(function (mesh) { return container.meshes.push(mesh); });
  106497. container.removeAllFromScene();
  106498. return container;
  106499. });
  106500. };
  106501. /**
  106502. * Read the OBJ file and create an Array of meshes.
  106503. * Each mesh contains all information given by the OBJ and the MTL file.
  106504. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  106505. *
  106506. * @param meshesNames
  106507. * @param scene BABYLON.Scene The scene where are displayed the data
  106508. * @param data String The content of the obj file
  106509. * @param rootUrl String The path to the folder
  106510. * @returns Array<AbstractMesh>
  106511. * @private
  106512. */
  106513. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  106514. var _this = this;
  106515. var positions = []; //values for the positions of vertices
  106516. var normals = []; //Values for the normals
  106517. var uvs = []; //Values for the textures
  106518. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  106519. var handledMesh; //The current mesh of meshes array
  106520. var indicesForBabylon = []; //The list of indices for VertexData
  106521. var wrappedPositionForBabylon = []; //The list of position in vectors
  106522. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  106523. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  106524. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  106525. var curPositionInIndices = 0;
  106526. var hasMeshes = false; //Meshes are defined in the file
  106527. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  106528. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  106529. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  106530. var triangles = []; //Indices from new triangles coming from polygons
  106531. var materialNameFromObj = ""; //The name of the current material
  106532. var fileToLoad = ""; //The name of the mtlFile to load
  106533. var materialsFromMTLFile = new MTLFileLoader();
  106534. var objMeshName = ""; //The name of the current obj mesh
  106535. var increment = 1; //Id for meshes created by the multimaterial
  106536. var isFirstMaterial = true;
  106537. /**
  106538. * Search for obj in the given array.
  106539. * This function is called to check if a couple of data already exists in an array.
  106540. *
  106541. * If found, returns the index of the founded tuple index. Returns -1 if not found
  106542. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  106543. * @param obj Array<number>
  106544. * @returns {boolean}
  106545. */
  106546. var isInArray = function (arr, obj) {
  106547. if (!arr[obj[0]])
  106548. arr[obj[0]] = { normals: [], idx: [] };
  106549. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  106550. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  106551. };
  106552. var isInArrayUV = function (arr, obj) {
  106553. if (!arr[obj[0]])
  106554. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  106555. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  106556. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  106557. return arr[obj[0]].idx[idx];
  106558. }
  106559. return -1;
  106560. };
  106561. /**
  106562. * This function set the data for each triangle.
  106563. * Data are position, normals and uvs
  106564. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  106565. * If the tuple already exist, add only their indice
  106566. *
  106567. * @param indicePositionFromObj Integer The index in positions array
  106568. * @param indiceUvsFromObj Integer The index in uvs array
  106569. * @param indiceNormalFromObj Integer The index in normals array
  106570. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  106571. * @param textureVectorFromOBJ Vector3 The value of uvs
  106572. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  106573. */
  106574. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  106575. //Check if this tuple already exists in the list of tuples
  106576. var _index;
  106577. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  106578. _index = isInArrayUV(tuplePosNorm, [
  106579. indicePositionFromObj,
  106580. indiceNormalFromObj,
  106581. indiceUvsFromObj
  106582. ]);
  106583. }
  106584. else {
  106585. _index = isInArray(tuplePosNorm, [
  106586. indicePositionFromObj,
  106587. indiceNormalFromObj
  106588. ]);
  106589. }
  106590. //If it not exists
  106591. if (_index == -1) {
  106592. //Add an new indice.
  106593. //The array of indices is only an array with his length equal to the number of triangles - 1.
  106594. //We add vertices data in this order
  106595. indicesForBabylon.push(wrappedPositionForBabylon.length);
  106596. //Push the position of vertice for Babylon
  106597. //Each element is a BABYLON.Vector3(x,y,z)
  106598. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  106599. //Push the uvs for Babylon
  106600. //Each element is a BABYLON.Vector3(u,v)
  106601. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  106602. //Push the normals for Babylon
  106603. //Each element is a BABYLON.Vector3(x,y,z)
  106604. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  106605. //Add the tuple in the comparison list
  106606. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  106607. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  106608. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  106609. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  106610. }
  106611. else {
  106612. //The tuple already exists
  106613. //Add the index of the already existing tuple
  106614. //At this index we can get the value of position, normal and uvs of vertex
  106615. indicesForBabylon.push(_index);
  106616. }
  106617. };
  106618. /**
  106619. * Transform BABYLON.Vector() object onto 3 digits in an array
  106620. */
  106621. var unwrapData = function () {
  106622. //Every array has the same length
  106623. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  106624. //Push the x, y, z values of each element in the unwrapped array
  106625. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  106626. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  106627. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  106628. }
  106629. // Reset arrays for the next new meshes
  106630. wrappedPositionForBabylon = [];
  106631. wrappedNormalsForBabylon = [];
  106632. wrappedUvsForBabylon = [];
  106633. tuplePosNorm = [];
  106634. curPositionInIndices = 0;
  106635. };
  106636. /**
  106637. * Create triangles from polygons by recursion
  106638. * The best to understand how it works is to draw it in the same time you get the recursion.
  106639. * It is important to notice that a triangle is a polygon
  106640. * We get 4 patterns of face defined in OBJ File :
  106641. * facePattern1 = ["1","2","3","4","5","6"]
  106642. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  106643. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  106644. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  106645. * Each pattern is divided by the same method
  106646. * @param face Array[String] The indices of elements
  106647. * @param v Integer The variable to increment
  106648. */
  106649. var getTriangles = function (face, v) {
  106650. //Work for each element of the array
  106651. if (v + 1 < face.length) {
  106652. //Add on the triangle variable the indexes to obtain triangles
  106653. triangles.push(face[0], face[v], face[v + 1]);
  106654. //Incrementation for recursion
  106655. v += 1;
  106656. //Recursion
  106657. getTriangles(face, v);
  106658. }
  106659. //Result obtained after 2 iterations:
  106660. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  106661. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  106662. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  106663. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  106664. };
  106665. /**
  106666. * Create triangles and push the data for each polygon for the pattern 1
  106667. * In this pattern we get vertice positions
  106668. * @param face
  106669. * @param v
  106670. */
  106671. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  106672. //Get the indices of triangles for each polygon
  106673. getTriangles(face, v);
  106674. //For each element in the triangles array.
  106675. //This var could contains 1 to an infinity of triangles
  106676. for (var k = 0; k < triangles.length; k++) {
  106677. // Set position indice
  106678. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  106679. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  106680. positions[indicePositionFromObj], //Get the vectors data
  106681. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  106682. );
  106683. }
  106684. //Reset variable for the next line
  106685. triangles = [];
  106686. };
  106687. /**
  106688. * Create triangles and push the data for each polygon for the pattern 2
  106689. * In this pattern we get vertice positions and uvsu
  106690. * @param face
  106691. * @param v
  106692. */
  106693. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  106694. //Get the indices of triangles for each polygon
  106695. getTriangles(face, v);
  106696. for (var k = 0; k < triangles.length; k++) {
  106697. //triangle[k] = "1/1"
  106698. //Split the data for getting position and uv
  106699. var point = triangles[k].split("/"); // ["1", "1"]
  106700. //Set position indice
  106701. var indicePositionFromObj = parseInt(point[0]) - 1;
  106702. //Set uv indice
  106703. var indiceUvsFromObj = parseInt(point[1]) - 1;
  106704. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  106705. positions[indicePositionFromObj], //Get the values for each element
  106706. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  106707. );
  106708. }
  106709. //Reset variable for the next line
  106710. triangles = [];
  106711. };
  106712. /**
  106713. * Create triangles and push the data for each polygon for the pattern 3
  106714. * In this pattern we get vertice positions, uvs and normals
  106715. * @param face
  106716. * @param v
  106717. */
  106718. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  106719. //Get the indices of triangles for each polygon
  106720. getTriangles(face, v);
  106721. for (var k = 0; k < triangles.length; k++) {
  106722. //triangle[k] = "1/1/1"
  106723. //Split the data for getting position, uv, and normals
  106724. var point = triangles[k].split("/"); // ["1", "1", "1"]
  106725. // Set position indice
  106726. var indicePositionFromObj = parseInt(point[0]) - 1;
  106727. // Set uv indice
  106728. var indiceUvsFromObj = parseInt(point[1]) - 1;
  106729. // Set normal indice
  106730. var indiceNormalFromObj = parseInt(point[2]) - 1;
  106731. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  106732. );
  106733. }
  106734. //Reset variable for the next line
  106735. triangles = [];
  106736. };
  106737. /**
  106738. * Create triangles and push the data for each polygon for the pattern 4
  106739. * In this pattern we get vertice positions and normals
  106740. * @param face
  106741. * @param v
  106742. */
  106743. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  106744. getTriangles(face, v);
  106745. for (var k = 0; k < triangles.length; k++) {
  106746. //triangle[k] = "1//1"
  106747. //Split the data for getting position and normals
  106748. var point = triangles[k].split("//"); // ["1", "1"]
  106749. // We check indices, and normals
  106750. var indicePositionFromObj = parseInt(point[0]) - 1;
  106751. var indiceNormalFromObj = parseInt(point[1]) - 1;
  106752. setData(indicePositionFromObj, 1, //Default value for uv
  106753. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  106754. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  106755. }
  106756. //Reset variable for the next line
  106757. triangles = [];
  106758. };
  106759. var addPreviousObjMesh = function () {
  106760. //Check if it is not the first mesh. Otherwise we don't have data.
  106761. if (meshesFromObj.length > 0) {
  106762. //Get the previous mesh for applying the data about the faces
  106763. //=> in obj file, faces definition append after the name of the mesh
  106764. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  106765. //Set the data into Array for the mesh
  106766. unwrapData();
  106767. // Reverse tab. Otherwise face are displayed in the wrong sens
  106768. indicesForBabylon.reverse();
  106769. //Set the information for the mesh
  106770. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  106771. handledMesh.indices = indicesForBabylon.slice();
  106772. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  106773. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  106774. handledMesh.uvs = unwrappedUVForBabylon.slice();
  106775. //Reset the array for the next mesh
  106776. indicesForBabylon = [];
  106777. unwrappedPositionsForBabylon = [];
  106778. unwrappedNormalsForBabylon = [];
  106779. unwrappedUVForBabylon = [];
  106780. }
  106781. };
  106782. //Main function
  106783. //Split the file into lines
  106784. var lines = data.split('\n');
  106785. //Look at each line
  106786. for (var i = 0; i < lines.length; i++) {
  106787. var line = lines[i].trim();
  106788. var result;
  106789. //Comment or newLine
  106790. if (line.length === 0 || line.charAt(0) === '#') {
  106791. continue;
  106792. //Get information about one position possible for the vertices
  106793. }
  106794. else if ((result = this.vertexPattern.exec(line)) !== null) {
  106795. //Create a Vector3 with the position x, y, z
  106796. //Value of result:
  106797. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  106798. //Add the Vector in the list of positions
  106799. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  106800. }
  106801. else if ((result = this.normalPattern.exec(line)) !== null) {
  106802. //Create a Vector3 with the normals x, y, z
  106803. //Value of result
  106804. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  106805. //Add the Vector in the list of normals
  106806. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  106807. }
  106808. else if ((result = this.uvPattern.exec(line)) !== null) {
  106809. //Create a Vector2 with the normals u, v
  106810. //Value of result
  106811. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  106812. //Add the Vector in the list of uvs
  106813. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  106814. //Identify patterns of faces
  106815. //Face could be defined in different type of pattern
  106816. }
  106817. else if ((result = this.facePattern3.exec(line)) !== null) {
  106818. //Value of result:
  106819. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  106820. //Set the data for this face
  106821. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  106822. 1);
  106823. }
  106824. else if ((result = this.facePattern4.exec(line)) !== null) {
  106825. //Value of result:
  106826. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  106827. //Set the data for this face
  106828. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  106829. 1);
  106830. }
  106831. else if ((result = this.facePattern2.exec(line)) !== null) {
  106832. //Value of result:
  106833. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  106834. //Set the data for this face
  106835. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  106836. 1);
  106837. }
  106838. else if ((result = this.facePattern1.exec(line)) !== null) {
  106839. //Value of result
  106840. //["f 1 2 3", "1 2 3"...]
  106841. //Set the data for this face
  106842. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  106843. 1);
  106844. //Define a mesh or an object
  106845. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  106846. }
  106847. else if (this.group.test(line) || this.obj.test(line)) {
  106848. //Create a new mesh corresponding to the name of the group.
  106849. //Definition of the mesh
  106850. var objMesh =
  106851. //Set the name of the current obj mesh
  106852. {
  106853. name: line.substring(2).trim(),
  106854. indices: undefined,
  106855. positions: undefined,
  106856. normals: undefined,
  106857. uvs: undefined,
  106858. materialName: ""
  106859. };
  106860. addPreviousObjMesh();
  106861. //Push the last mesh created with only the name
  106862. meshesFromObj.push(objMesh);
  106863. //Set this variable to indicate that now meshesFromObj has objects defined inside
  106864. hasMeshes = true;
  106865. isFirstMaterial = true;
  106866. increment = 1;
  106867. //Keyword for applying a material
  106868. }
  106869. else if (this.usemtl.test(line)) {
  106870. //Get the name of the material
  106871. materialNameFromObj = line.substring(7).trim();
  106872. //If this new material is in the same mesh
  106873. if (!isFirstMaterial) {
  106874. //Set the data for the previous mesh
  106875. addPreviousObjMesh();
  106876. //Create a new mesh
  106877. var objMesh =
  106878. //Set the name of the current obj mesh
  106879. {
  106880. name: objMeshName + "_mm" + increment.toString(),
  106881. indices: undefined,
  106882. positions: undefined,
  106883. normals: undefined,
  106884. uvs: undefined,
  106885. materialName: materialNameFromObj
  106886. };
  106887. increment++;
  106888. //If meshes are already defined
  106889. meshesFromObj.push(objMesh);
  106890. }
  106891. //Set the material name if the previous line define a mesh
  106892. if (hasMeshes && isFirstMaterial) {
  106893. //Set the material name to the previous mesh (1 material per mesh)
  106894. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  106895. isFirstMaterial = false;
  106896. }
  106897. //Keyword for loading the mtl file
  106898. }
  106899. else if (this.mtllib.test(line)) {
  106900. //Get the name of mtl file
  106901. fileToLoad = line.substring(7).trim();
  106902. //Apply smoothing
  106903. }
  106904. else if (this.smooth.test(line)) {
  106905. // smooth shading => apply smoothing
  106906. //Toda y I don't know it work with babylon and with obj.
  106907. //With the obj file an integer is set
  106908. }
  106909. else {
  106910. //If there is another possibility
  106911. console.log("Unhandled expression at line : " + line);
  106912. }
  106913. }
  106914. //At the end of the file, add the last mesh into the meshesFromObj array
  106915. if (hasMeshes) {
  106916. //Set the data for the last mesh
  106917. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  106918. //Reverse indices for displaying faces in the good sens
  106919. indicesForBabylon.reverse();
  106920. //Get the good array
  106921. unwrapData();
  106922. //Set array
  106923. handledMesh.indices = indicesForBabylon;
  106924. handledMesh.positions = unwrappedPositionsForBabylon;
  106925. handledMesh.normals = unwrappedNormalsForBabylon;
  106926. handledMesh.uvs = unwrappedUVForBabylon;
  106927. }
  106928. //If any o or g keyword found, create a mesj with a random id
  106929. if (!hasMeshes) {
  106930. // reverse tab of indices
  106931. indicesForBabylon.reverse();
  106932. //Get positions normals uvs
  106933. unwrapData();
  106934. //Set data for one mesh
  106935. meshesFromObj.push({
  106936. name: BABYLON.Geometry.RandomId(),
  106937. indices: indicesForBabylon,
  106938. positions: unwrappedPositionsForBabylon,
  106939. normals: unwrappedNormalsForBabylon,
  106940. uvs: unwrappedUVForBabylon,
  106941. materialName: materialNameFromObj
  106942. });
  106943. }
  106944. //Create a BABYLON.Mesh list
  106945. var babylonMeshesArray = []; //The mesh for babylon
  106946. var materialToUse = new Array();
  106947. //Set data for each mesh
  106948. for (var j = 0; j < meshesFromObj.length; j++) {
  106949. //check meshesNames (stlFileLoader)
  106950. if (meshesNames && meshesFromObj[j].name) {
  106951. if (meshesNames instanceof Array) {
  106952. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  106953. continue;
  106954. }
  106955. }
  106956. else {
  106957. if (meshesFromObj[j].name !== meshesNames) {
  106958. continue;
  106959. }
  106960. }
  106961. }
  106962. //Get the current mesh
  106963. //Set the data with VertexBuffer for each mesh
  106964. handledMesh = meshesFromObj[j];
  106965. //Create a BABYLON.Mesh with the name of the obj mesh
  106966. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  106967. //Push the name of the material to an array
  106968. //This is indispensable for the importMesh function
  106969. materialToUse.push(meshesFromObj[j].materialName);
  106970. var vertexData = new BABYLON.VertexData(); //The container for the values
  106971. //Set the data for the babylonMesh
  106972. vertexData.positions = handledMesh.positions;
  106973. vertexData.normals = handledMesh.normals;
  106974. vertexData.uvs = handledMesh.uvs;
  106975. vertexData.indices = handledMesh.indices;
  106976. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  106977. vertexData.applyToMesh(babylonMesh);
  106978. if (OBJFileLoader.INVERT_Y) {
  106979. babylonMesh.scaling.y *= -1;
  106980. }
  106981. //Push the mesh into an array
  106982. babylonMeshesArray.push(babylonMesh);
  106983. }
  106984. var mtlPromises = [];
  106985. //load the materials
  106986. //Check if we have a file to load
  106987. if (fileToLoad !== "") {
  106988. //Load the file synchronously
  106989. mtlPromises.push(new Promise(function (resolve, reject) {
  106990. _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  106991. try {
  106992. //Create materials thanks MTLLoader function
  106993. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  106994. //Look at each material loaded in the mtl file
  106995. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  106996. //Three variables to get all meshes with the same material
  106997. var startIndex = 0;
  106998. var _indices = [];
  106999. var _index;
  107000. //The material from MTL file is used in the meshes loaded
  107001. //Push the indice in an array
  107002. //Check if the material is not used for another mesh
  107003. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  107004. _indices.push(_index);
  107005. startIndex = _index + 1;
  107006. }
  107007. //If the material is not used dispose it
  107008. if (_index == -1 && _indices.length == 0) {
  107009. //If the material is not needed, remove it
  107010. materialsFromMTLFile.materials[n].dispose();
  107011. }
  107012. else {
  107013. for (var o = 0; o < _indices.length; o++) {
  107014. //Apply the material to the BABYLON.Mesh for each mesh with the material
  107015. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  107016. }
  107017. }
  107018. }
  107019. resolve();
  107020. }
  107021. catch (e) {
  107022. reject(e);
  107023. }
  107024. });
  107025. }));
  107026. }
  107027. //Return an array with all BABYLON.Mesh
  107028. return Promise.all(mtlPromises).then(function () {
  107029. return babylonMeshesArray;
  107030. });
  107031. };
  107032. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  107033. OBJFileLoader.INVERT_Y = false;
  107034. return OBJFileLoader;
  107035. }());
  107036. BABYLON.OBJFileLoader = OBJFileLoader;
  107037. if (BABYLON.SceneLoader) {
  107038. //Add this loader into the register plugin
  107039. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  107040. }
  107041. })(BABYLON || (BABYLON = {}));
  107042. //# sourceMappingURL=babylon.objFileLoader.js.map
  107043. var BABYLON;
  107044. (function (BABYLON) {
  107045. /**
  107046. * Mode that determines the coordinate system to use.
  107047. */
  107048. var GLTFLoaderCoordinateSystemMode;
  107049. (function (GLTFLoaderCoordinateSystemMode) {
  107050. /**
  107051. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  107052. */
  107053. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  107054. /**
  107055. * Sets the useRightHandedSystem flag on the scene.
  107056. */
  107057. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  107058. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  107059. /**
  107060. * Mode that determines what animations will start.
  107061. */
  107062. var GLTFLoaderAnimationStartMode;
  107063. (function (GLTFLoaderAnimationStartMode) {
  107064. /**
  107065. * No animation will start.
  107066. */
  107067. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  107068. /**
  107069. * The first animation will start.
  107070. */
  107071. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  107072. /**
  107073. * All animations will start.
  107074. */
  107075. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  107076. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  107077. /**
  107078. * Loader state.
  107079. */
  107080. var GLTFLoaderState;
  107081. (function (GLTFLoaderState) {
  107082. /**
  107083. * The asset is loading.
  107084. */
  107085. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  107086. /**
  107087. * The asset is ready for rendering.
  107088. */
  107089. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  107090. /**
  107091. * The asset is completely loaded.
  107092. */
  107093. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  107094. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  107095. /**
  107096. * File loader for loading glTF files into a scene.
  107097. */
  107098. var GLTFFileLoader = /** @class */ (function () {
  107099. function GLTFFileLoader() {
  107100. // #region Common options
  107101. /**
  107102. * Raised when the asset has been parsed
  107103. */
  107104. this.onParsedObservable = new BABYLON.Observable();
  107105. // #endregion
  107106. // #region V2 options
  107107. /**
  107108. * The coordinate system mode. Defaults to AUTO.
  107109. */
  107110. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  107111. /**
  107112. * The animation start mode. Defaults to FIRST.
  107113. */
  107114. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  107115. /**
  107116. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  107117. */
  107118. this.compileMaterials = false;
  107119. /**
  107120. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  107121. */
  107122. this.useClipPlane = false;
  107123. /**
  107124. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  107125. */
  107126. this.compileShadowGenerators = false;
  107127. /**
  107128. * Defines if the Alpha blended materials are only applied as coverage.
  107129. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  107130. * If true, no extra effects are applied to transparent pixels.
  107131. */
  107132. this.transparencyAsCoverage = false;
  107133. /** @hidden */
  107134. this._normalizeAnimationGroupsToBeginAtZero = true;
  107135. /**
  107136. * Function called before loading a url referenced by the asset.
  107137. */
  107138. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  107139. /**
  107140. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  107141. */
  107142. this.onMeshLoadedObservable = new BABYLON.Observable();
  107143. /**
  107144. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  107145. */
  107146. this.onTextureLoadedObservable = new BABYLON.Observable();
  107147. /**
  107148. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  107149. */
  107150. this.onMaterialLoadedObservable = new BABYLON.Observable();
  107151. /**
  107152. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  107153. */
  107154. this.onCameraLoadedObservable = new BABYLON.Observable();
  107155. /**
  107156. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  107157. * For assets with LODs, raised when all of the LODs are complete.
  107158. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  107159. */
  107160. this.onCompleteObservable = new BABYLON.Observable();
  107161. /**
  107162. * Observable raised after the loader is disposed.
  107163. */
  107164. this.onDisposeObservable = new BABYLON.Observable();
  107165. /**
  107166. * Observable raised after a loader extension is created.
  107167. * Set additional options for a loader extension in this event.
  107168. */
  107169. this.onExtensionLoadedObservable = new BABYLON.Observable();
  107170. // #endregion
  107171. this._loader = null;
  107172. /**
  107173. * Name of the loader ("gltf")
  107174. */
  107175. this.name = "gltf";
  107176. /**
  107177. * Supported file extensions of the loader (.gltf, .glb)
  107178. */
  107179. this.extensions = {
  107180. ".gltf": { isBinary: false },
  107181. ".glb": { isBinary: true }
  107182. };
  107183. this._logIndentLevel = 0;
  107184. this._loggingEnabled = false;
  107185. /** @hidden */
  107186. this._log = this._logDisabled;
  107187. this._capturePerformanceCounters = false;
  107188. /** @hidden */
  107189. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  107190. /** @hidden */
  107191. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  107192. }
  107193. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  107194. /**
  107195. * Raised when the asset has been parsed
  107196. */
  107197. set: function (callback) {
  107198. if (this._onParsedObserver) {
  107199. this.onParsedObservable.remove(this._onParsedObserver);
  107200. }
  107201. this._onParsedObserver = this.onParsedObservable.add(callback);
  107202. },
  107203. enumerable: true,
  107204. configurable: true
  107205. });
  107206. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  107207. /**
  107208. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  107209. */
  107210. set: function (callback) {
  107211. if (this._onMeshLoadedObserver) {
  107212. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  107213. }
  107214. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  107215. },
  107216. enumerable: true,
  107217. configurable: true
  107218. });
  107219. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  107220. /**
  107221. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  107222. */
  107223. set: function (callback) {
  107224. if (this._onTextureLoadedObserver) {
  107225. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  107226. }
  107227. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  107228. },
  107229. enumerable: true,
  107230. configurable: true
  107231. });
  107232. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  107233. /**
  107234. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  107235. */
  107236. set: function (callback) {
  107237. if (this._onMaterialLoadedObserver) {
  107238. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  107239. }
  107240. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  107241. },
  107242. enumerable: true,
  107243. configurable: true
  107244. });
  107245. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  107246. /**
  107247. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  107248. */
  107249. set: function (callback) {
  107250. if (this._onCameraLoadedObserver) {
  107251. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  107252. }
  107253. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  107254. },
  107255. enumerable: true,
  107256. configurable: true
  107257. });
  107258. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  107259. /**
  107260. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  107261. */
  107262. set: function (callback) {
  107263. if (this._onCompleteObserver) {
  107264. this.onCompleteObservable.remove(this._onCompleteObserver);
  107265. }
  107266. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  107267. },
  107268. enumerable: true,
  107269. configurable: true
  107270. });
  107271. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  107272. /**
  107273. * Callback raised after the loader is disposed.
  107274. */
  107275. set: function (callback) {
  107276. if (this._onDisposeObserver) {
  107277. this.onDisposeObservable.remove(this._onDisposeObserver);
  107278. }
  107279. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  107280. },
  107281. enumerable: true,
  107282. configurable: true
  107283. });
  107284. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  107285. /**
  107286. * Callback raised after a loader extension is created.
  107287. */
  107288. set: function (callback) {
  107289. if (this._onExtensionLoadedObserver) {
  107290. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  107291. }
  107292. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  107293. },
  107294. enumerable: true,
  107295. configurable: true
  107296. });
  107297. /**
  107298. * Returns a promise that resolves when the asset is completely loaded.
  107299. * @returns a promise that resolves when the asset is completely loaded.
  107300. */
  107301. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  107302. var _this = this;
  107303. return new Promise(function (resolve) {
  107304. _this.onCompleteObservable.addOnce(function () {
  107305. resolve();
  107306. });
  107307. });
  107308. };
  107309. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  107310. /**
  107311. * The loader state or null if the loader is not active.
  107312. */
  107313. get: function () {
  107314. return this._loader ? this._loader.state : null;
  107315. },
  107316. enumerable: true,
  107317. configurable: true
  107318. });
  107319. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  107320. /**
  107321. * Defines if the loader logging is enabled.
  107322. */
  107323. get: function () {
  107324. return this._loggingEnabled;
  107325. },
  107326. set: function (value) {
  107327. if (this._loggingEnabled === value) {
  107328. return;
  107329. }
  107330. this._loggingEnabled = value;
  107331. if (this._loggingEnabled) {
  107332. this._log = this._logEnabled;
  107333. }
  107334. else {
  107335. this._log = this._logDisabled;
  107336. }
  107337. },
  107338. enumerable: true,
  107339. configurable: true
  107340. });
  107341. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  107342. /**
  107343. * Defines if the loader should capture performance counters.
  107344. */
  107345. get: function () {
  107346. return this._capturePerformanceCounters;
  107347. },
  107348. set: function (value) {
  107349. if (this._capturePerformanceCounters === value) {
  107350. return;
  107351. }
  107352. this._capturePerformanceCounters = value;
  107353. if (this._capturePerformanceCounters) {
  107354. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  107355. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  107356. }
  107357. else {
  107358. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  107359. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  107360. }
  107361. },
  107362. enumerable: true,
  107363. configurable: true
  107364. });
  107365. /**
  107366. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  107367. */
  107368. GLTFFileLoader.prototype.dispose = function () {
  107369. if (this._loader) {
  107370. this._loader.dispose();
  107371. this._loader = null;
  107372. }
  107373. this._clear();
  107374. this.onDisposeObservable.notifyObservers(undefined);
  107375. this.onDisposeObservable.clear();
  107376. };
  107377. /** @hidden */
  107378. GLTFFileLoader.prototype._clear = function () {
  107379. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  107380. this.onMeshLoadedObservable.clear();
  107381. this.onTextureLoadedObservable.clear();
  107382. this.onMaterialLoadedObservable.clear();
  107383. this.onCameraLoadedObservable.clear();
  107384. this.onCompleteObservable.clear();
  107385. this.onExtensionLoadedObservable.clear();
  107386. };
  107387. /**
  107388. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  107389. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  107390. * @param scene the scene the meshes should be added to
  107391. * @param data the glTF data to load
  107392. * @param rootUrl root url to load from
  107393. * @param onProgress event that fires when loading progress has occured
  107394. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  107395. */
  107396. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107397. var _this = this;
  107398. return Promise.resolve().then(function () {
  107399. var loaderData = _this._parse(data);
  107400. _this._loader = _this._getLoader(loaderData);
  107401. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  107402. });
  107403. };
  107404. /**
  107405. * Imports all objects from the loaded glTF data and adds them to the scene
  107406. * @param scene the scene the objects should be added to
  107407. * @param data the glTF data to load
  107408. * @param rootUrl root url to load from
  107409. * @param onProgress event that fires when loading progress has occured
  107410. * @returns a promise which completes when objects have been loaded to the scene
  107411. */
  107412. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107413. var _this = this;
  107414. return Promise.resolve().then(function () {
  107415. var loaderData = _this._parse(data);
  107416. _this._loader = _this._getLoader(loaderData);
  107417. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  107418. });
  107419. };
  107420. /**
  107421. * Load into an asset container.
  107422. * @param scene The scene to load into
  107423. * @param data The data to import
  107424. * @param rootUrl The root url for scene and resources
  107425. * @param onProgress The callback when the load progresses
  107426. * @returns The loaded asset container
  107427. */
  107428. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  107429. var _this = this;
  107430. return Promise.resolve().then(function () {
  107431. var loaderData = _this._parse(data);
  107432. _this._loader = _this._getLoader(loaderData);
  107433. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  107434. var container = new BABYLON.AssetContainer(scene);
  107435. Array.prototype.push.apply(container.meshes, result.meshes);
  107436. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  107437. Array.prototype.push.apply(container.skeletons, result.skeletons);
  107438. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  107439. container.removeAllFromScene();
  107440. return container;
  107441. });
  107442. });
  107443. };
  107444. /**
  107445. * If the data string can be loaded directly.
  107446. * @param data string contianing the file data
  107447. * @returns if the data can be loaded directly
  107448. */
  107449. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  107450. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  107451. };
  107452. /**
  107453. * Instantiates a glTF file loader plugin.
  107454. * @returns the created plugin
  107455. */
  107456. GLTFFileLoader.prototype.createPlugin = function () {
  107457. return new GLTFFileLoader();
  107458. };
  107459. GLTFFileLoader.prototype._parse = function (data) {
  107460. this._startPerformanceCounter("Parse");
  107461. var parsedData;
  107462. if (data instanceof ArrayBuffer) {
  107463. this._log("Parsing binary");
  107464. parsedData = this._parseBinary(data);
  107465. }
  107466. else {
  107467. this._log("Parsing JSON");
  107468. this._log("JSON length: " + data.length);
  107469. parsedData = {
  107470. json: JSON.parse(data),
  107471. bin: null
  107472. };
  107473. }
  107474. this.onParsedObservable.notifyObservers(parsedData);
  107475. this.onParsedObservable.clear();
  107476. this._endPerformanceCounter("Parse");
  107477. return parsedData;
  107478. };
  107479. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  107480. var asset = loaderData.json.asset || {};
  107481. this._log("Asset version: " + asset.version);
  107482. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  107483. asset.generator && this._log("Asset generator: " + asset.generator);
  107484. var version = GLTFFileLoader._parseVersion(asset.version);
  107485. if (!version) {
  107486. throw new Error("Invalid version: " + asset.version);
  107487. }
  107488. if (asset.minVersion !== undefined) {
  107489. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  107490. if (!minVersion) {
  107491. throw new Error("Invalid minimum version: " + asset.minVersion);
  107492. }
  107493. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  107494. throw new Error("Incompatible minimum version: " + asset.minVersion);
  107495. }
  107496. }
  107497. var createLoaders = {
  107498. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  107499. 2: GLTFFileLoader._CreateGLTFLoaderV2
  107500. };
  107501. var createLoader = createLoaders[version.major];
  107502. if (!createLoader) {
  107503. throw new Error("Unsupported version: " + asset.version);
  107504. }
  107505. return createLoader(this);
  107506. };
  107507. GLTFFileLoader.prototype._parseBinary = function (data) {
  107508. var Binary = {
  107509. Magic: 0x46546C67
  107510. };
  107511. this._log("Binary length: " + data.byteLength);
  107512. var binaryReader = new BinaryReader(data);
  107513. var magic = binaryReader.readUint32();
  107514. if (magic !== Binary.Magic) {
  107515. throw new Error("Unexpected magic: " + magic);
  107516. }
  107517. var version = binaryReader.readUint32();
  107518. if (this.loggingEnabled) {
  107519. this._log("Binary version: " + version);
  107520. }
  107521. switch (version) {
  107522. case 1: return this._parseV1(binaryReader);
  107523. case 2: return this._parseV2(binaryReader);
  107524. }
  107525. throw new Error("Unsupported version: " + version);
  107526. };
  107527. GLTFFileLoader.prototype._parseV1 = function (binaryReader) {
  107528. var ContentFormat = {
  107529. JSON: 0
  107530. };
  107531. var length = binaryReader.readUint32();
  107532. if (length != binaryReader.getLength()) {
  107533. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  107534. }
  107535. var contentLength = binaryReader.readUint32();
  107536. var contentFormat = binaryReader.readUint32();
  107537. var content;
  107538. switch (contentFormat) {
  107539. case ContentFormat.JSON: {
  107540. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  107541. break;
  107542. }
  107543. default: {
  107544. throw new Error("Unexpected content format: " + contentFormat);
  107545. }
  107546. }
  107547. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  107548. var body = binaryReader.readUint8Array(bytesRemaining);
  107549. return {
  107550. json: content,
  107551. bin: body
  107552. };
  107553. };
  107554. GLTFFileLoader.prototype._parseV2 = function (binaryReader) {
  107555. var ChunkFormat = {
  107556. JSON: 0x4E4F534A,
  107557. BIN: 0x004E4942
  107558. };
  107559. var length = binaryReader.readUint32();
  107560. if (length !== binaryReader.getLength()) {
  107561. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  107562. }
  107563. // JSON chunk
  107564. var chunkLength = binaryReader.readUint32();
  107565. var chunkFormat = binaryReader.readUint32();
  107566. if (chunkFormat !== ChunkFormat.JSON) {
  107567. throw new Error("First chunk format is not JSON");
  107568. }
  107569. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  107570. // Look for BIN chunk
  107571. var bin = null;
  107572. while (binaryReader.getPosition() < binaryReader.getLength()) {
  107573. var chunkLength_1 = binaryReader.readUint32();
  107574. var chunkFormat_1 = binaryReader.readUint32();
  107575. switch (chunkFormat_1) {
  107576. case ChunkFormat.JSON: {
  107577. throw new Error("Unexpected JSON chunk");
  107578. }
  107579. case ChunkFormat.BIN: {
  107580. bin = binaryReader.readUint8Array(chunkLength_1);
  107581. break;
  107582. }
  107583. default: {
  107584. // ignore unrecognized chunkFormat
  107585. binaryReader.skipBytes(chunkLength_1);
  107586. break;
  107587. }
  107588. }
  107589. }
  107590. return {
  107591. json: json,
  107592. bin: bin
  107593. };
  107594. };
  107595. GLTFFileLoader._parseVersion = function (version) {
  107596. if (version === "1.0" || version === "1.0.1") {
  107597. return {
  107598. major: 1,
  107599. minor: 0
  107600. };
  107601. }
  107602. var match = (version + "").match(/^(\d+)\.(\d+)/);
  107603. if (!match) {
  107604. return null;
  107605. }
  107606. return {
  107607. major: parseInt(match[1]),
  107608. minor: parseInt(match[2])
  107609. };
  107610. };
  107611. GLTFFileLoader._compareVersion = function (a, b) {
  107612. if (a.major > b.major)
  107613. return 1;
  107614. if (a.major < b.major)
  107615. return -1;
  107616. if (a.minor > b.minor)
  107617. return 1;
  107618. if (a.minor < b.minor)
  107619. return -1;
  107620. return 0;
  107621. };
  107622. GLTFFileLoader._decodeBufferToText = function (buffer) {
  107623. var result = "";
  107624. var length = buffer.byteLength;
  107625. for (var i = 0; i < length; i++) {
  107626. result += String.fromCharCode(buffer[i]);
  107627. }
  107628. return result;
  107629. };
  107630. /** @hidden */
  107631. GLTFFileLoader.prototype._logOpen = function (message) {
  107632. this._log(message);
  107633. this._logIndentLevel++;
  107634. };
  107635. /** @hidden */
  107636. GLTFFileLoader.prototype._logClose = function () {
  107637. --this._logIndentLevel;
  107638. };
  107639. GLTFFileLoader.prototype._logEnabled = function (message) {
  107640. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  107641. BABYLON.Tools.Log("" + spaces + message);
  107642. };
  107643. GLTFFileLoader.prototype._logDisabled = function (message) {
  107644. };
  107645. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  107646. BABYLON.Tools.StartPerformanceCounter(counterName);
  107647. };
  107648. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  107649. };
  107650. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  107651. BABYLON.Tools.EndPerformanceCounter(counterName);
  107652. };
  107653. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  107654. };
  107655. // #endregion
  107656. // #region V1 options
  107657. /**
  107658. * 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.
  107659. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  107660. * Defaults to true.
  107661. * @hidden
  107662. */
  107663. GLTFFileLoader.IncrementalLoading = true;
  107664. /**
  107665. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  107666. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  107667. * @hidden
  107668. */
  107669. GLTFFileLoader.HomogeneousCoordinates = false;
  107670. GLTFFileLoader._logSpaces = " ";
  107671. return GLTFFileLoader;
  107672. }());
  107673. BABYLON.GLTFFileLoader = GLTFFileLoader;
  107674. var BinaryReader = /** @class */ (function () {
  107675. function BinaryReader(arrayBuffer) {
  107676. this._arrayBuffer = arrayBuffer;
  107677. this._dataView = new DataView(arrayBuffer);
  107678. this._byteOffset = 0;
  107679. }
  107680. BinaryReader.prototype.getPosition = function () {
  107681. return this._byteOffset;
  107682. };
  107683. BinaryReader.prototype.getLength = function () {
  107684. return this._arrayBuffer.byteLength;
  107685. };
  107686. BinaryReader.prototype.readUint32 = function () {
  107687. var value = this._dataView.getUint32(this._byteOffset, true);
  107688. this._byteOffset += 4;
  107689. return value;
  107690. };
  107691. BinaryReader.prototype.readUint8Array = function (length) {
  107692. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  107693. this._byteOffset += length;
  107694. return value;
  107695. };
  107696. BinaryReader.prototype.skipBytes = function (length) {
  107697. this._byteOffset += length;
  107698. };
  107699. return BinaryReader;
  107700. }());
  107701. if (BABYLON.SceneLoader) {
  107702. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  107703. }
  107704. })(BABYLON || (BABYLON = {}));
  107705. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  107706. var BABYLON;
  107707. (function (BABYLON) {
  107708. var GLTF1;
  107709. (function (GLTF1) {
  107710. /**
  107711. * Enums
  107712. */
  107713. var EComponentType;
  107714. (function (EComponentType) {
  107715. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  107716. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  107717. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  107718. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  107719. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  107720. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  107721. var EShaderType;
  107722. (function (EShaderType) {
  107723. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  107724. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  107725. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  107726. var EParameterType;
  107727. (function (EParameterType) {
  107728. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  107729. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  107730. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  107731. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  107732. EParameterType[EParameterType["INT"] = 5124] = "INT";
  107733. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  107734. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  107735. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  107736. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  107737. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  107738. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  107739. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  107740. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  107741. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  107742. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  107743. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  107744. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  107745. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  107746. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  107747. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  107748. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  107749. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  107750. var ETextureWrapMode;
  107751. (function (ETextureWrapMode) {
  107752. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  107753. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  107754. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  107755. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  107756. var ETextureFilterType;
  107757. (function (ETextureFilterType) {
  107758. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  107759. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  107760. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  107761. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  107762. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  107763. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  107764. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  107765. var ETextureFormat;
  107766. (function (ETextureFormat) {
  107767. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  107768. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  107769. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  107770. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  107771. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  107772. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  107773. var ECullingType;
  107774. (function (ECullingType) {
  107775. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  107776. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  107777. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  107778. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  107779. var EBlendingFunction;
  107780. (function (EBlendingFunction) {
  107781. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  107782. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  107783. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  107784. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  107785. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  107786. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  107787. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  107788. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  107789. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  107790. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  107791. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  107792. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  107793. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  107794. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  107795. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  107796. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  107797. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107798. })(BABYLON || (BABYLON = {}));
  107799. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  107800. var BABYLON;
  107801. (function (BABYLON) {
  107802. var GLTF1;
  107803. (function (GLTF1) {
  107804. /**
  107805. * Tokenizer. Used for shaders compatibility
  107806. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  107807. */
  107808. var ETokenType;
  107809. (function (ETokenType) {
  107810. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  107811. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  107812. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  107813. })(ETokenType || (ETokenType = {}));
  107814. var Tokenizer = /** @class */ (function () {
  107815. function Tokenizer(toParse) {
  107816. this._pos = 0;
  107817. this.currentToken = ETokenType.UNKNOWN;
  107818. this.currentIdentifier = "";
  107819. this.currentString = "";
  107820. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  107821. this._toParse = toParse;
  107822. this._maxPos = toParse.length;
  107823. }
  107824. Tokenizer.prototype.getNextToken = function () {
  107825. if (this.isEnd())
  107826. return ETokenType.END_OF_INPUT;
  107827. this.currentString = this.read();
  107828. this.currentToken = ETokenType.UNKNOWN;
  107829. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  107830. this.currentToken = ETokenType.IDENTIFIER;
  107831. this.currentIdentifier = this.currentString;
  107832. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  107833. this.currentIdentifier += this.currentString;
  107834. this.forward();
  107835. }
  107836. }
  107837. return this.currentToken;
  107838. };
  107839. Tokenizer.prototype.peek = function () {
  107840. return this._toParse[this._pos];
  107841. };
  107842. Tokenizer.prototype.read = function () {
  107843. return this._toParse[this._pos++];
  107844. };
  107845. Tokenizer.prototype.forward = function () {
  107846. this._pos++;
  107847. };
  107848. Tokenizer.prototype.isEnd = function () {
  107849. return this._pos >= this._maxPos;
  107850. };
  107851. return Tokenizer;
  107852. }());
  107853. /**
  107854. * Values
  107855. */
  107856. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  107857. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  107858. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  107859. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  107860. /**
  107861. * Parse
  107862. */
  107863. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  107864. for (var buf in parsedBuffers) {
  107865. var parsedBuffer = parsedBuffers[buf];
  107866. gltfRuntime.buffers[buf] = parsedBuffer;
  107867. gltfRuntime.buffersCount++;
  107868. }
  107869. };
  107870. var parseShaders = function (parsedShaders, gltfRuntime) {
  107871. for (var sha in parsedShaders) {
  107872. var parsedShader = parsedShaders[sha];
  107873. gltfRuntime.shaders[sha] = parsedShader;
  107874. gltfRuntime.shaderscount++;
  107875. }
  107876. };
  107877. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  107878. for (var object in parsedObjects) {
  107879. var parsedObject = parsedObjects[object];
  107880. gltfRuntime[runtimeProperty][object] = parsedObject;
  107881. }
  107882. };
  107883. /**
  107884. * Utils
  107885. */
  107886. var normalizeUVs = function (buffer) {
  107887. if (!buffer) {
  107888. return;
  107889. }
  107890. for (var i = 0; i < buffer.length / 2; i++) {
  107891. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  107892. }
  107893. };
  107894. var getAttribute = function (attributeParameter) {
  107895. if (attributeParameter.semantic === "NORMAL") {
  107896. return "normal";
  107897. }
  107898. else if (attributeParameter.semantic === "POSITION") {
  107899. return "position";
  107900. }
  107901. else if (attributeParameter.semantic === "JOINT") {
  107902. return "matricesIndices";
  107903. }
  107904. else if (attributeParameter.semantic === "WEIGHT") {
  107905. return "matricesWeights";
  107906. }
  107907. else if (attributeParameter.semantic === "COLOR") {
  107908. return "color";
  107909. }
  107910. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  107911. var channel = Number(attributeParameter.semantic.split("_")[1]);
  107912. return "uv" + (channel === 0 ? "" : channel + 1);
  107913. }
  107914. return null;
  107915. };
  107916. /**
  107917. * Loads and creates animations
  107918. */
  107919. var loadAnimations = function (gltfRuntime) {
  107920. for (var anim in gltfRuntime.animations) {
  107921. var animation = gltfRuntime.animations[anim];
  107922. if (!animation.channels || !animation.samplers) {
  107923. continue;
  107924. }
  107925. var lastAnimation = null;
  107926. for (var i = 0; i < animation.channels.length; i++) {
  107927. // Get parameters and load buffers
  107928. var channel = animation.channels[i];
  107929. var sampler = animation.samplers[channel.sampler];
  107930. if (!sampler) {
  107931. continue;
  107932. }
  107933. var inputData = null;
  107934. var outputData = null;
  107935. if (animation.parameters) {
  107936. inputData = animation.parameters[sampler.input];
  107937. outputData = animation.parameters[sampler.output];
  107938. }
  107939. else {
  107940. inputData = sampler.input;
  107941. outputData = sampler.output;
  107942. }
  107943. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  107944. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  107945. var targetID = channel.target.id;
  107946. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  107947. if (targetNode === null) {
  107948. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  107949. }
  107950. if (targetNode === null) {
  107951. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  107952. continue;
  107953. }
  107954. var isBone = targetNode instanceof BABYLON.Bone;
  107955. // Get target path (position, rotation or scaling)
  107956. var targetPath = channel.target.path;
  107957. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  107958. if (targetPathIndex !== -1) {
  107959. targetPath = babylonAnimationPaths[targetPathIndex];
  107960. }
  107961. // Determine animation type
  107962. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  107963. if (!isBone) {
  107964. if (targetPath === "rotationQuaternion") {
  107965. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  107966. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  107967. }
  107968. else {
  107969. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  107970. }
  107971. }
  107972. // Create animation and key frames
  107973. var babylonAnimation = null;
  107974. var keys = [];
  107975. var arrayOffset = 0;
  107976. var modifyKey = false;
  107977. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  107978. babylonAnimation = lastAnimation;
  107979. modifyKey = true;
  107980. }
  107981. if (!modifyKey) {
  107982. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  107983. }
  107984. // For each frame
  107985. for (var j = 0; j < bufferInput.length; j++) {
  107986. var value = null;
  107987. if (targetPath === "rotationQuaternion") { // VEC4
  107988. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  107989. arrayOffset += 4;
  107990. }
  107991. else { // Position and scaling are VEC3
  107992. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  107993. arrayOffset += 3;
  107994. }
  107995. if (isBone) {
  107996. var bone = targetNode;
  107997. var translation = BABYLON.Vector3.Zero();
  107998. var rotationQuaternion = new BABYLON.Quaternion();
  107999. var scaling = BABYLON.Vector3.Zero();
  108000. // Warning on decompose
  108001. var mat = bone.getBaseMatrix();
  108002. if (modifyKey && lastAnimation) {
  108003. mat = lastAnimation.getKeys()[j].value;
  108004. }
  108005. mat.decompose(scaling, rotationQuaternion, translation);
  108006. if (targetPath === "position") {
  108007. translation = value;
  108008. }
  108009. else if (targetPath === "rotationQuaternion") {
  108010. rotationQuaternion = value;
  108011. }
  108012. else {
  108013. scaling = value;
  108014. }
  108015. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  108016. }
  108017. if (!modifyKey) {
  108018. keys.push({
  108019. frame: bufferInput[j],
  108020. value: value
  108021. });
  108022. }
  108023. else if (lastAnimation) {
  108024. lastAnimation.getKeys()[j].value = value;
  108025. }
  108026. }
  108027. // Finish
  108028. if (!modifyKey && babylonAnimation) {
  108029. babylonAnimation.setKeys(keys);
  108030. targetNode.animations.push(babylonAnimation);
  108031. }
  108032. lastAnimation = babylonAnimation;
  108033. gltfRuntime.scene.stopAnimation(targetNode);
  108034. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  108035. }
  108036. }
  108037. };
  108038. /**
  108039. * Returns the bones transformation matrix
  108040. */
  108041. var configureBoneTransformation = function (node) {
  108042. var mat = null;
  108043. if (node.translation || node.rotation || node.scale) {
  108044. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  108045. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  108046. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  108047. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  108048. }
  108049. else {
  108050. mat = BABYLON.Matrix.FromArray(node.matrix);
  108051. }
  108052. return mat;
  108053. };
  108054. /**
  108055. * Returns the parent bone
  108056. */
  108057. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  108058. // Try to find
  108059. for (var i = 0; i < newSkeleton.bones.length; i++) {
  108060. if (newSkeleton.bones[i].name === jointName) {
  108061. return newSkeleton.bones[i];
  108062. }
  108063. }
  108064. // Not found, search in gltf nodes
  108065. var nodes = gltfRuntime.nodes;
  108066. for (var nde in nodes) {
  108067. var node = nodes[nde];
  108068. if (!node.jointName) {
  108069. continue;
  108070. }
  108071. var children = node.children;
  108072. for (var i = 0; i < children.length; i++) {
  108073. var child = gltfRuntime.nodes[children[i]];
  108074. if (!child.jointName) {
  108075. continue;
  108076. }
  108077. if (child.jointName === jointName) {
  108078. var mat = configureBoneTransformation(node);
  108079. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  108080. bone.id = nde;
  108081. return bone;
  108082. }
  108083. }
  108084. }
  108085. return null;
  108086. };
  108087. /**
  108088. * Returns the appropriate root node
  108089. */
  108090. var getNodeToRoot = function (nodesToRoot, id) {
  108091. for (var i = 0; i < nodesToRoot.length; i++) {
  108092. var nodeToRoot = nodesToRoot[i];
  108093. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  108094. var child = nodeToRoot.node.children[j];
  108095. if (child === id) {
  108096. return nodeToRoot.bone;
  108097. }
  108098. }
  108099. }
  108100. return null;
  108101. };
  108102. /**
  108103. * Returns the node with the joint name
  108104. */
  108105. var getJointNode = function (gltfRuntime, jointName) {
  108106. var nodes = gltfRuntime.nodes;
  108107. var node = nodes[jointName];
  108108. if (node) {
  108109. return {
  108110. node: node,
  108111. id: jointName
  108112. };
  108113. }
  108114. for (var nde in nodes) {
  108115. node = nodes[nde];
  108116. if (node.jointName === jointName) {
  108117. return {
  108118. node: node,
  108119. id: nde
  108120. };
  108121. }
  108122. }
  108123. return null;
  108124. };
  108125. /**
  108126. * Checks if a nodes is in joints
  108127. */
  108128. var nodeIsInJoints = function (skins, id) {
  108129. for (var i = 0; i < skins.jointNames.length; i++) {
  108130. if (skins.jointNames[i] === id) {
  108131. return true;
  108132. }
  108133. }
  108134. return false;
  108135. };
  108136. /**
  108137. * Fills the nodes to root for bones and builds hierarchy
  108138. */
  108139. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  108140. // Creates nodes for root
  108141. for (var nde in gltfRuntime.nodes) {
  108142. var node = gltfRuntime.nodes[nde];
  108143. var id = nde;
  108144. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  108145. continue;
  108146. }
  108147. // Create node to root bone
  108148. var mat = configureBoneTransformation(node);
  108149. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  108150. bone.id = id;
  108151. nodesToRoot.push({ bone: bone, node: node, id: id });
  108152. }
  108153. // Parenting
  108154. for (var i = 0; i < nodesToRoot.length; i++) {
  108155. var nodeToRoot = nodesToRoot[i];
  108156. var children = nodeToRoot.node.children;
  108157. for (var j = 0; j < children.length; j++) {
  108158. var child = null;
  108159. for (var k = 0; k < nodesToRoot.length; k++) {
  108160. if (nodesToRoot[k].id === children[j]) {
  108161. child = nodesToRoot[k];
  108162. break;
  108163. }
  108164. }
  108165. if (child) {
  108166. child.bone._parent = nodeToRoot.bone;
  108167. nodeToRoot.bone.children.push(child.bone);
  108168. }
  108169. }
  108170. }
  108171. };
  108172. /**
  108173. * Imports a skeleton
  108174. */
  108175. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  108176. if (!newSkeleton) {
  108177. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  108178. }
  108179. if (!skins.babylonSkeleton) {
  108180. return newSkeleton;
  108181. }
  108182. // Find the root bones
  108183. var nodesToRoot = [];
  108184. var nodesToRootToAdd = [];
  108185. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  108186. newSkeleton.bones = [];
  108187. // Joints
  108188. for (var i = 0; i < skins.jointNames.length; i++) {
  108189. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  108190. if (!jointNode) {
  108191. continue;
  108192. }
  108193. var node = jointNode.node;
  108194. if (!node) {
  108195. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  108196. continue;
  108197. }
  108198. var id = jointNode.id;
  108199. // Optimize, if the bone already exists...
  108200. var existingBone = gltfRuntime.scene.getBoneByID(id);
  108201. if (existingBone) {
  108202. newSkeleton.bones.push(existingBone);
  108203. continue;
  108204. }
  108205. // Search for parent bone
  108206. var foundBone = false;
  108207. var parentBone = null;
  108208. for (var j = 0; j < i; j++) {
  108209. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  108210. if (!jointNode_1) {
  108211. continue;
  108212. }
  108213. var joint = jointNode_1.node;
  108214. if (!joint) {
  108215. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  108216. continue;
  108217. }
  108218. var children = joint.children;
  108219. if (!children) {
  108220. continue;
  108221. }
  108222. foundBone = false;
  108223. for (var k = 0; k < children.length; k++) {
  108224. if (children[k] === id) {
  108225. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  108226. foundBone = true;
  108227. break;
  108228. }
  108229. }
  108230. if (foundBone) {
  108231. break;
  108232. }
  108233. }
  108234. // Create bone
  108235. var mat = configureBoneTransformation(node);
  108236. if (!parentBone && nodesToRoot.length > 0) {
  108237. parentBone = getNodeToRoot(nodesToRoot, id);
  108238. if (parentBone) {
  108239. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  108240. nodesToRootToAdd.push(parentBone);
  108241. }
  108242. }
  108243. }
  108244. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  108245. bone.id = id;
  108246. }
  108247. // Polish
  108248. var bones = newSkeleton.bones;
  108249. newSkeleton.bones = [];
  108250. for (var i = 0; i < skins.jointNames.length; i++) {
  108251. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  108252. if (!jointNode) {
  108253. continue;
  108254. }
  108255. for (var j = 0; j < bones.length; j++) {
  108256. if (bones[j].id === jointNode.id) {
  108257. newSkeleton.bones.push(bones[j]);
  108258. break;
  108259. }
  108260. }
  108261. }
  108262. newSkeleton.prepare();
  108263. // Finish
  108264. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  108265. newSkeleton.bones.push(nodesToRootToAdd[i]);
  108266. }
  108267. return newSkeleton;
  108268. };
  108269. /**
  108270. * Imports a mesh and its geometries
  108271. */
  108272. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  108273. if (!newMesh) {
  108274. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  108275. newMesh.id = id;
  108276. }
  108277. if (!node.babylonNode) {
  108278. return newMesh;
  108279. }
  108280. var subMaterials = [];
  108281. var vertexData = null;
  108282. var verticesStarts = new Array();
  108283. var verticesCounts = new Array();
  108284. var indexStarts = new Array();
  108285. var indexCounts = new Array();
  108286. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  108287. var meshID = meshes[meshIndex];
  108288. var mesh = gltfRuntime.meshes[meshID];
  108289. if (!mesh) {
  108290. continue;
  108291. }
  108292. // Positions, normals and UVs
  108293. for (var i = 0; i < mesh.primitives.length; i++) {
  108294. // Temporary vertex data
  108295. var tempVertexData = new BABYLON.VertexData();
  108296. var primitive = mesh.primitives[i];
  108297. if (primitive.mode !== 4) {
  108298. // continue;
  108299. }
  108300. var attributes = primitive.attributes;
  108301. var accessor = null;
  108302. var buffer = null;
  108303. // Set positions, normal and uvs
  108304. for (var semantic in attributes) {
  108305. // Link accessor and buffer view
  108306. accessor = gltfRuntime.accessors[attributes[semantic]];
  108307. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  108308. if (semantic === "NORMAL") {
  108309. tempVertexData.normals = new Float32Array(buffer.length);
  108310. tempVertexData.normals.set(buffer);
  108311. }
  108312. else if (semantic === "POSITION") {
  108313. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  108314. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  108315. for (var j = 0; j < buffer.length; j += 4) {
  108316. tempVertexData.positions[j] = buffer[j];
  108317. tempVertexData.positions[j + 1] = buffer[j + 1];
  108318. tempVertexData.positions[j + 2] = buffer[j + 2];
  108319. }
  108320. }
  108321. else {
  108322. tempVertexData.positions = new Float32Array(buffer.length);
  108323. tempVertexData.positions.set(buffer);
  108324. }
  108325. verticesCounts.push(tempVertexData.positions.length);
  108326. }
  108327. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  108328. var channel = Number(semantic.split("_")[1]);
  108329. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  108330. var uvs = new Float32Array(buffer.length);
  108331. uvs.set(buffer);
  108332. normalizeUVs(uvs);
  108333. tempVertexData.set(uvs, uvKind);
  108334. }
  108335. else if (semantic === "JOINT") {
  108336. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  108337. tempVertexData.matricesIndices.set(buffer);
  108338. }
  108339. else if (semantic === "WEIGHT") {
  108340. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  108341. tempVertexData.matricesWeights.set(buffer);
  108342. }
  108343. else if (semantic === "COLOR") {
  108344. tempVertexData.colors = new Float32Array(buffer.length);
  108345. tempVertexData.colors.set(buffer);
  108346. }
  108347. }
  108348. // Indices
  108349. accessor = gltfRuntime.accessors[primitive.indices];
  108350. if (accessor) {
  108351. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  108352. tempVertexData.indices = new Int32Array(buffer.length);
  108353. tempVertexData.indices.set(buffer);
  108354. indexCounts.push(tempVertexData.indices.length);
  108355. }
  108356. else {
  108357. // Set indices on the fly
  108358. var indices = [];
  108359. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  108360. indices.push(j);
  108361. }
  108362. tempVertexData.indices = new Int32Array(indices);
  108363. indexCounts.push(tempVertexData.indices.length);
  108364. }
  108365. if (!vertexData) {
  108366. vertexData = tempVertexData;
  108367. }
  108368. else {
  108369. vertexData.merge(tempVertexData);
  108370. }
  108371. // Sub material
  108372. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  108373. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  108374. // Update vertices start and index start
  108375. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  108376. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  108377. }
  108378. }
  108379. var material;
  108380. if (subMaterials.length > 1) {
  108381. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  108382. material.subMaterials = subMaterials;
  108383. }
  108384. else {
  108385. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  108386. }
  108387. if (subMaterials.length === 1) {
  108388. material = subMaterials[0];
  108389. }
  108390. if (!newMesh.material) {
  108391. newMesh.material = material;
  108392. }
  108393. // Apply geometry
  108394. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  108395. newMesh.computeWorldMatrix(true);
  108396. // Apply submeshes
  108397. newMesh.subMeshes = [];
  108398. var index = 0;
  108399. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  108400. var meshID = meshes[meshIndex];
  108401. var mesh = gltfRuntime.meshes[meshID];
  108402. if (!mesh) {
  108403. continue;
  108404. }
  108405. for (var i = 0; i < mesh.primitives.length; i++) {
  108406. if (mesh.primitives[i].mode !== 4) {
  108407. //continue;
  108408. }
  108409. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  108410. index++;
  108411. }
  108412. }
  108413. // Finish
  108414. return newMesh;
  108415. };
  108416. /**
  108417. * Configure node transformation from position, rotation and scaling
  108418. */
  108419. var configureNode = function (newNode, position, rotation, scaling) {
  108420. if (newNode.position) {
  108421. newNode.position = position;
  108422. }
  108423. if (newNode.rotationQuaternion || newNode.rotation) {
  108424. newNode.rotationQuaternion = rotation;
  108425. }
  108426. if (newNode.scaling) {
  108427. newNode.scaling = scaling;
  108428. }
  108429. };
  108430. /**
  108431. * Configures node from transformation matrix
  108432. */
  108433. var configureNodeFromMatrix = function (newNode, node, parent) {
  108434. if (node.matrix) {
  108435. var position = new BABYLON.Vector3(0, 0, 0);
  108436. var rotation = new BABYLON.Quaternion();
  108437. var scaling = new BABYLON.Vector3(0, 0, 0);
  108438. var mat = BABYLON.Matrix.FromArray(node.matrix);
  108439. mat.decompose(scaling, rotation, position);
  108440. configureNode(newNode, position, rotation, scaling);
  108441. }
  108442. else if (node.translation && node.rotation && node.scale) {
  108443. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  108444. }
  108445. newNode.computeWorldMatrix(true);
  108446. };
  108447. /**
  108448. * Imports a node
  108449. */
  108450. var importNode = function (gltfRuntime, node, id, parent) {
  108451. var lastNode = null;
  108452. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  108453. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  108454. return null;
  108455. }
  108456. }
  108457. // Meshes
  108458. if (node.skin) {
  108459. if (node.meshes) {
  108460. var skin = gltfRuntime.skins[node.skin];
  108461. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  108462. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  108463. if (newMesh.skeleton === null) {
  108464. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  108465. if (!skin.babylonSkeleton) {
  108466. skin.babylonSkeleton = newMesh.skeleton;
  108467. }
  108468. }
  108469. lastNode = newMesh;
  108470. }
  108471. }
  108472. else if (node.meshes) {
  108473. /**
  108474. * Improve meshes property
  108475. */
  108476. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  108477. lastNode = newMesh;
  108478. }
  108479. // Lights
  108480. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  108481. var light = gltfRuntime.lights[node.light];
  108482. if (light) {
  108483. if (light.type === "ambient") {
  108484. var ambienLight = light[light.type];
  108485. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  108486. hemiLight.name = node.name || "";
  108487. if (ambienLight.color) {
  108488. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  108489. }
  108490. lastNode = hemiLight;
  108491. }
  108492. else if (light.type === "directional") {
  108493. var directionalLight = light[light.type];
  108494. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  108495. dirLight.name = node.name || "";
  108496. if (directionalLight.color) {
  108497. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  108498. }
  108499. lastNode = dirLight;
  108500. }
  108501. else if (light.type === "point") {
  108502. var pointLight = light[light.type];
  108503. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  108504. ptLight.name = node.name || "";
  108505. if (pointLight.color) {
  108506. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  108507. }
  108508. lastNode = ptLight;
  108509. }
  108510. else if (light.type === "spot") {
  108511. var spotLight = light[light.type];
  108512. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  108513. spLight.name = node.name || "";
  108514. if (spotLight.color) {
  108515. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  108516. }
  108517. if (spotLight.fallOfAngle) {
  108518. spLight.angle = spotLight.fallOfAngle;
  108519. }
  108520. if (spotLight.fallOffExponent) {
  108521. spLight.exponent = spotLight.fallOffExponent;
  108522. }
  108523. lastNode = spLight;
  108524. }
  108525. }
  108526. }
  108527. // Cameras
  108528. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  108529. var camera = gltfRuntime.cameras[node.camera];
  108530. if (camera) {
  108531. if (camera.type === "orthographic") {
  108532. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  108533. orthoCamera.name = node.name || "";
  108534. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  108535. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  108536. lastNode = orthoCamera;
  108537. }
  108538. else if (camera.type === "perspective") {
  108539. var perspectiveCamera = camera[camera.type];
  108540. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  108541. persCamera.name = node.name || "";
  108542. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  108543. if (!perspectiveCamera.aspectRatio) {
  108544. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  108545. }
  108546. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  108547. persCamera.maxZ = perspectiveCamera.zfar;
  108548. persCamera.minZ = perspectiveCamera.znear;
  108549. }
  108550. lastNode = persCamera;
  108551. }
  108552. }
  108553. }
  108554. // Empty node
  108555. if (!node.jointName) {
  108556. if (node.babylonNode) {
  108557. return node.babylonNode;
  108558. }
  108559. else if (lastNode === null) {
  108560. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  108561. node.babylonNode = dummy;
  108562. lastNode = dummy;
  108563. }
  108564. }
  108565. if (lastNode !== null) {
  108566. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  108567. configureNodeFromMatrix(lastNode, node, parent);
  108568. }
  108569. else {
  108570. var translation = node.translation || [0, 0, 0];
  108571. var rotation = node.rotation || [0, 0, 0, 1];
  108572. var scale = node.scale || [1, 1, 1];
  108573. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  108574. }
  108575. lastNode.updateCache(true);
  108576. node.babylonNode = lastNode;
  108577. }
  108578. return lastNode;
  108579. };
  108580. /**
  108581. * Traverses nodes and creates them
  108582. */
  108583. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  108584. if (meshIncluded === void 0) { meshIncluded = false; }
  108585. var node = gltfRuntime.nodes[id];
  108586. var newNode = null;
  108587. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  108588. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  108589. meshIncluded = true;
  108590. }
  108591. else {
  108592. meshIncluded = false;
  108593. }
  108594. }
  108595. else {
  108596. meshIncluded = true;
  108597. }
  108598. if (!node.jointName && meshIncluded) {
  108599. newNode = importNode(gltfRuntime, node, id, parent);
  108600. if (newNode !== null) {
  108601. newNode.id = id;
  108602. newNode.parent = parent;
  108603. }
  108604. }
  108605. if (node.children) {
  108606. for (var i = 0; i < node.children.length; i++) {
  108607. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  108608. }
  108609. }
  108610. };
  108611. /**
  108612. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  108613. */
  108614. var postLoad = function (gltfRuntime) {
  108615. // Nodes
  108616. var currentScene = gltfRuntime.currentScene;
  108617. if (currentScene) {
  108618. for (var i = 0; i < currentScene.nodes.length; i++) {
  108619. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108620. }
  108621. }
  108622. else {
  108623. for (var thing in gltfRuntime.scenes) {
  108624. currentScene = gltfRuntime.scenes[thing];
  108625. for (var i = 0; i < currentScene.nodes.length; i++) {
  108626. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108627. }
  108628. }
  108629. }
  108630. // Set animations
  108631. loadAnimations(gltfRuntime);
  108632. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  108633. var skeleton = gltfRuntime.scene.skeletons[i];
  108634. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  108635. }
  108636. };
  108637. /**
  108638. * onBind shaderrs callback to set uniforms and matrices
  108639. */
  108640. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  108641. var materialValues = material.values || technique.parameters;
  108642. for (var unif in unTreatedUniforms) {
  108643. var uniform = unTreatedUniforms[unif];
  108644. var type = uniform.type;
  108645. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  108646. if (uniform.semantic && !uniform.source && !uniform.node) {
  108647. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  108648. }
  108649. else if (uniform.semantic && (uniform.source || uniform.node)) {
  108650. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  108651. if (source === null) {
  108652. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  108653. }
  108654. if (source === null) {
  108655. continue;
  108656. }
  108657. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  108658. }
  108659. }
  108660. else {
  108661. var value = materialValues[technique.uniforms[unif]];
  108662. if (!value) {
  108663. continue;
  108664. }
  108665. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  108666. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  108667. if (texture === null || texture === undefined) {
  108668. continue;
  108669. }
  108670. shaderMaterial.getEffect().setTexture(unif, texture);
  108671. }
  108672. else {
  108673. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  108674. }
  108675. }
  108676. }
  108677. onSuccess(shaderMaterial);
  108678. };
  108679. /**
  108680. * Prepare uniforms to send the only one time
  108681. * Loads the appropriate textures
  108682. */
  108683. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  108684. var materialValues = material.values || technique.parameters;
  108685. var techniqueUniforms = technique.uniforms;
  108686. /**
  108687. * Prepare values here (not matrices)
  108688. */
  108689. for (var unif in unTreatedUniforms) {
  108690. var uniform = unTreatedUniforms[unif];
  108691. var type = uniform.type;
  108692. var value = materialValues[techniqueUniforms[unif]];
  108693. if (value === undefined) {
  108694. // In case the value is the same for all materials
  108695. value = uniform.value;
  108696. }
  108697. if (!value) {
  108698. continue;
  108699. }
  108700. var onLoadTexture = function (uniformName) {
  108701. return function (texture) {
  108702. if (uniform.value && uniformName) {
  108703. // Static uniform
  108704. shaderMaterial.setTexture(uniformName, texture);
  108705. delete unTreatedUniforms[uniformName];
  108706. }
  108707. };
  108708. };
  108709. // Texture (sampler2D)
  108710. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  108711. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  108712. }
  108713. // Others
  108714. else {
  108715. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  108716. // Static uniform
  108717. delete unTreatedUniforms[unif];
  108718. }
  108719. }
  108720. }
  108721. };
  108722. /**
  108723. * Shader compilation failed
  108724. */
  108725. var onShaderCompileError = function (program, shaderMaterial, onError) {
  108726. return function (effect, error) {
  108727. shaderMaterial.dispose(true);
  108728. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  108729. };
  108730. };
  108731. /**
  108732. * Shader compilation success
  108733. */
  108734. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  108735. return function (_) {
  108736. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  108737. shaderMaterial.onBind = function (mesh) {
  108738. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  108739. };
  108740. };
  108741. };
  108742. /**
  108743. * Returns the appropriate uniform if already handled by babylon
  108744. */
  108745. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  108746. for (var unif in technique.uniforms) {
  108747. var uniform = technique.uniforms[unif];
  108748. var uniformParameter = technique.parameters[uniform];
  108749. if (tokenizer.currentIdentifier === unif) {
  108750. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  108751. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  108752. if (transformIndex !== -1) {
  108753. delete unTreatedUniforms[unif];
  108754. return babylonTransforms[transformIndex];
  108755. }
  108756. }
  108757. }
  108758. }
  108759. return tokenizer.currentIdentifier;
  108760. };
  108761. /**
  108762. * All shaders loaded. Create materials one by one
  108763. */
  108764. var importMaterials = function (gltfRuntime) {
  108765. // Create materials
  108766. for (var mat in gltfRuntime.materials) {
  108767. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  108768. }
  108769. };
  108770. /**
  108771. * Implementation of the base glTF spec
  108772. */
  108773. var GLTFLoaderBase = /** @class */ (function () {
  108774. function GLTFLoaderBase() {
  108775. }
  108776. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  108777. var gltfRuntime = {
  108778. extensions: {},
  108779. accessors: {},
  108780. buffers: {},
  108781. bufferViews: {},
  108782. meshes: {},
  108783. lights: {},
  108784. cameras: {},
  108785. nodes: {},
  108786. images: {},
  108787. textures: {},
  108788. shaders: {},
  108789. programs: {},
  108790. samplers: {},
  108791. techniques: {},
  108792. materials: {},
  108793. animations: {},
  108794. skins: {},
  108795. extensionsUsed: [],
  108796. scenes: {},
  108797. buffersCount: 0,
  108798. shaderscount: 0,
  108799. scene: scene,
  108800. rootUrl: rootUrl,
  108801. loadedBufferCount: 0,
  108802. loadedBufferViews: {},
  108803. loadedShaderCount: 0,
  108804. importOnlyMeshes: false,
  108805. dummyNodes: []
  108806. };
  108807. // Parse
  108808. if (parsedData.extensions) {
  108809. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  108810. }
  108811. if (parsedData.extensionsUsed) {
  108812. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  108813. }
  108814. if (parsedData.buffers) {
  108815. parseBuffers(parsedData.buffers, gltfRuntime);
  108816. }
  108817. if (parsedData.bufferViews) {
  108818. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  108819. }
  108820. if (parsedData.accessors) {
  108821. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  108822. }
  108823. if (parsedData.meshes) {
  108824. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  108825. }
  108826. if (parsedData.lights) {
  108827. parseObject(parsedData.lights, "lights", gltfRuntime);
  108828. }
  108829. if (parsedData.cameras) {
  108830. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  108831. }
  108832. if (parsedData.nodes) {
  108833. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  108834. }
  108835. if (parsedData.images) {
  108836. parseObject(parsedData.images, "images", gltfRuntime);
  108837. }
  108838. if (parsedData.textures) {
  108839. parseObject(parsedData.textures, "textures", gltfRuntime);
  108840. }
  108841. if (parsedData.shaders) {
  108842. parseShaders(parsedData.shaders, gltfRuntime);
  108843. }
  108844. if (parsedData.programs) {
  108845. parseObject(parsedData.programs, "programs", gltfRuntime);
  108846. }
  108847. if (parsedData.samplers) {
  108848. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  108849. }
  108850. if (parsedData.techniques) {
  108851. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  108852. }
  108853. if (parsedData.materials) {
  108854. parseObject(parsedData.materials, "materials", gltfRuntime);
  108855. }
  108856. if (parsedData.animations) {
  108857. parseObject(parsedData.animations, "animations", gltfRuntime);
  108858. }
  108859. if (parsedData.skins) {
  108860. parseObject(parsedData.skins, "skins", gltfRuntime);
  108861. }
  108862. if (parsedData.scenes) {
  108863. gltfRuntime.scenes = parsedData.scenes;
  108864. }
  108865. if (parsedData.scene && parsedData.scenes) {
  108866. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  108867. }
  108868. return gltfRuntime;
  108869. };
  108870. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108871. var buffer = gltfRuntime.buffers[id];
  108872. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  108873. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  108874. }
  108875. else {
  108876. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  108877. if (request) {
  108878. onError(request.status + " " + request.statusText);
  108879. }
  108880. });
  108881. }
  108882. };
  108883. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108884. var texture = gltfRuntime.textures[id];
  108885. if (!texture || !texture.source) {
  108886. onError("");
  108887. return;
  108888. }
  108889. if (texture.babylonTexture) {
  108890. onSuccess(null);
  108891. return;
  108892. }
  108893. var source = gltfRuntime.images[texture.source];
  108894. if (BABYLON.Tools.IsBase64(source.uri)) {
  108895. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  108896. }
  108897. else {
  108898. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  108899. if (request) {
  108900. onError(request.status + " " + request.statusText);
  108901. }
  108902. });
  108903. }
  108904. };
  108905. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108906. var texture = gltfRuntime.textures[id];
  108907. if (texture.babylonTexture) {
  108908. onSuccess(texture.babylonTexture);
  108909. return;
  108910. }
  108911. var sampler = gltfRuntime.samplers[texture.sampler];
  108912. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  108913. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  108914. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  108915. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  108916. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  108917. var blob = new Blob([buffer]);
  108918. var blobURL = URL.createObjectURL(blob);
  108919. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  108920. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  108921. if (sampler.wrapS !== undefined) {
  108922. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  108923. }
  108924. if (sampler.wrapT !== undefined) {
  108925. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  108926. }
  108927. newTexture.name = id;
  108928. texture.babylonTexture = newTexture;
  108929. onSuccess(newTexture);
  108930. };
  108931. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108932. var shader = gltfRuntime.shaders[id];
  108933. if (BABYLON.Tools.IsBase64(shader.uri)) {
  108934. var shaderString = atob(shader.uri.split(",")[1]);
  108935. if (onSuccess) {
  108936. onSuccess(shaderString);
  108937. }
  108938. }
  108939. else {
  108940. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  108941. if (request && onError) {
  108942. onError(request.status + " " + request.statusText);
  108943. }
  108944. });
  108945. }
  108946. };
  108947. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108948. var material = gltfRuntime.materials[id];
  108949. if (!material.technique) {
  108950. if (onError) {
  108951. onError("No technique found.");
  108952. }
  108953. return;
  108954. }
  108955. var technique = gltfRuntime.techniques[material.technique];
  108956. if (!technique) {
  108957. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108958. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  108959. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108960. onSuccess(defaultMaterial);
  108961. return;
  108962. }
  108963. var program = gltfRuntime.programs[technique.program];
  108964. var states = technique.states;
  108965. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  108966. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  108967. var newVertexShader = "";
  108968. var newPixelShader = "";
  108969. var vertexTokenizer = new Tokenizer(vertexShader);
  108970. var pixelTokenizer = new Tokenizer(pixelShader);
  108971. var unTreatedUniforms = {};
  108972. var uniforms = [];
  108973. var attributes = [];
  108974. var samplers = [];
  108975. // Fill uniform, sampler2D and attributes
  108976. for (var unif in technique.uniforms) {
  108977. var uniform = technique.uniforms[unif];
  108978. var uniformParameter = technique.parameters[uniform];
  108979. unTreatedUniforms[unif] = uniformParameter;
  108980. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  108981. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  108982. if (transformIndex !== -1) {
  108983. uniforms.push(babylonTransforms[transformIndex]);
  108984. delete unTreatedUniforms[unif];
  108985. }
  108986. else {
  108987. uniforms.push(unif);
  108988. }
  108989. }
  108990. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  108991. samplers.push(unif);
  108992. }
  108993. else {
  108994. uniforms.push(unif);
  108995. }
  108996. }
  108997. for (var attr in technique.attributes) {
  108998. var attribute = technique.attributes[attr];
  108999. var attributeParameter = technique.parameters[attribute];
  109000. if (attributeParameter.semantic) {
  109001. attributes.push(getAttribute(attributeParameter));
  109002. }
  109003. }
  109004. // Configure vertex shader
  109005. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  109006. var tokenType = vertexTokenizer.currentToken;
  109007. if (tokenType !== ETokenType.IDENTIFIER) {
  109008. newVertexShader += vertexTokenizer.currentString;
  109009. continue;
  109010. }
  109011. var foundAttribute = false;
  109012. for (var attr in technique.attributes) {
  109013. var attribute = technique.attributes[attr];
  109014. var attributeParameter = technique.parameters[attribute];
  109015. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  109016. newVertexShader += getAttribute(attributeParameter);
  109017. foundAttribute = true;
  109018. break;
  109019. }
  109020. }
  109021. if (foundAttribute) {
  109022. continue;
  109023. }
  109024. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  109025. }
  109026. // Configure pixel shader
  109027. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  109028. var tokenType = pixelTokenizer.currentToken;
  109029. if (tokenType !== ETokenType.IDENTIFIER) {
  109030. newPixelShader += pixelTokenizer.currentString;
  109031. continue;
  109032. }
  109033. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  109034. }
  109035. // Create shader material
  109036. var shaderPath = {
  109037. vertex: program.vertexShader + id,
  109038. fragment: program.fragmentShader + id
  109039. };
  109040. var options = {
  109041. attributes: attributes,
  109042. uniforms: uniforms,
  109043. samplers: samplers,
  109044. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  109045. };
  109046. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  109047. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  109048. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  109049. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  109050. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  109051. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  109052. if (states && states.functions) {
  109053. var functions = states.functions;
  109054. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  109055. shaderMaterial.backFaceCulling = false;
  109056. }
  109057. var blendFunc = functions.blendFuncSeparate;
  109058. if (blendFunc) {
  109059. 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) {
  109060. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  109061. }
  109062. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  109063. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  109064. }
  109065. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  109066. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  109067. }
  109068. 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) {
  109069. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  109070. }
  109071. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  109072. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  109073. }
  109074. 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) {
  109075. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  109076. }
  109077. }
  109078. }
  109079. };
  109080. return GLTFLoaderBase;
  109081. }());
  109082. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  109083. /**
  109084. * glTF V1 Loader
  109085. */
  109086. var GLTFLoader = /** @class */ (function () {
  109087. function GLTFLoader() {
  109088. this.state = null;
  109089. }
  109090. GLTFLoader.RegisterExtension = function (extension) {
  109091. if (GLTFLoader.Extensions[extension.name]) {
  109092. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  109093. return;
  109094. }
  109095. GLTFLoader.Extensions[extension.name] = extension;
  109096. };
  109097. GLTFLoader.prototype.dispose = function () {
  109098. // do nothing
  109099. };
  109100. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  109101. var _this = this;
  109102. scene.useRightHandedSystem = true;
  109103. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  109104. gltfRuntime.importOnlyMeshes = true;
  109105. if (meshesNames === "") {
  109106. gltfRuntime.importMeshesNames = [];
  109107. }
  109108. else if (typeof meshesNames === "string") {
  109109. gltfRuntime.importMeshesNames = [meshesNames];
  109110. }
  109111. else if (meshesNames && !(meshesNames instanceof Array)) {
  109112. gltfRuntime.importMeshesNames = [meshesNames];
  109113. }
  109114. else {
  109115. gltfRuntime.importMeshesNames = [];
  109116. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  109117. }
  109118. // Create nodes
  109119. _this._createNodes(gltfRuntime);
  109120. var meshes = new Array();
  109121. var skeletons = new Array();
  109122. // Fill arrays of meshes and skeletons
  109123. for (var nde in gltfRuntime.nodes) {
  109124. var node = gltfRuntime.nodes[nde];
  109125. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  109126. meshes.push(node.babylonNode);
  109127. }
  109128. }
  109129. for (var skl in gltfRuntime.skins) {
  109130. var skin = gltfRuntime.skins[skl];
  109131. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  109132. skeletons.push(skin.babylonSkeleton);
  109133. }
  109134. }
  109135. // Load buffers, shaders, materials, etc.
  109136. _this._loadBuffersAsync(gltfRuntime, function () {
  109137. _this._loadShadersAsync(gltfRuntime, function () {
  109138. importMaterials(gltfRuntime);
  109139. postLoad(gltfRuntime);
  109140. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  109141. onSuccess(meshes, skeletons);
  109142. }
  109143. });
  109144. }, onProgress);
  109145. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  109146. onSuccess(meshes, skeletons);
  109147. }
  109148. }, onError);
  109149. return true;
  109150. };
  109151. /**
  109152. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  109153. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  109154. * @param scene the scene the meshes should be added to
  109155. * @param data gltf data containing information of the meshes in a loaded file
  109156. * @param rootUrl root url to load from
  109157. * @param onProgress event that fires when loading progress has occured
  109158. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  109159. */
  109160. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  109161. var _this = this;
  109162. return new Promise(function (resolve, reject) {
  109163. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  109164. resolve({
  109165. meshes: meshes,
  109166. particleSystems: [],
  109167. skeletons: skeletons,
  109168. animationGroups: []
  109169. });
  109170. }, onProgress, function (message) {
  109171. reject(new Error(message));
  109172. });
  109173. });
  109174. };
  109175. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  109176. var _this = this;
  109177. scene.useRightHandedSystem = true;
  109178. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  109179. // Load runtime extensios
  109180. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  109181. // Create nodes
  109182. _this._createNodes(gltfRuntime);
  109183. // Load buffers, shaders, materials, etc.
  109184. _this._loadBuffersAsync(gltfRuntime, function () {
  109185. _this._loadShadersAsync(gltfRuntime, function () {
  109186. importMaterials(gltfRuntime);
  109187. postLoad(gltfRuntime);
  109188. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  109189. onSuccess();
  109190. }
  109191. });
  109192. });
  109193. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  109194. onSuccess();
  109195. }
  109196. }, onError);
  109197. }, onError);
  109198. };
  109199. /**
  109200. * Imports all objects from a loaded gltf file and adds them to the scene
  109201. * @param scene the scene the objects should be added to
  109202. * @param data gltf data containing information of the meshes in a loaded file
  109203. * @param rootUrl root url to load from
  109204. * @param onProgress event that fires when loading progress has occured
  109205. * @returns a promise which completes when objects have been loaded to the scene
  109206. */
  109207. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  109208. var _this = this;
  109209. return new Promise(function (resolve, reject) {
  109210. _this._loadAsync(scene, data, rootUrl, function () {
  109211. resolve();
  109212. }, onProgress, function (message) {
  109213. reject(new Error(message));
  109214. });
  109215. });
  109216. };
  109217. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  109218. var hasShaders = false;
  109219. var processShader = function (sha, shader) {
  109220. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  109221. if (shaderString instanceof ArrayBuffer) {
  109222. return;
  109223. }
  109224. gltfRuntime.loadedShaderCount++;
  109225. if (shaderString) {
  109226. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  109227. }
  109228. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  109229. onload();
  109230. }
  109231. }, function () {
  109232. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  109233. });
  109234. };
  109235. for (var sha in gltfRuntime.shaders) {
  109236. hasShaders = true;
  109237. var shader = gltfRuntime.shaders[sha];
  109238. if (shader) {
  109239. processShader.bind(this, sha, shader)();
  109240. }
  109241. else {
  109242. BABYLON.Tools.Error("No shader named: " + sha);
  109243. }
  109244. }
  109245. if (!hasShaders) {
  109246. onload();
  109247. }
  109248. };
  109249. ;
  109250. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  109251. var hasBuffers = false;
  109252. var processBuffer = function (buf, buffer) {
  109253. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  109254. gltfRuntime.loadedBufferCount++;
  109255. if (bufferView) {
  109256. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  109257. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  109258. }
  109259. gltfRuntime.loadedBufferViews[buf] = bufferView;
  109260. }
  109261. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  109262. onLoad();
  109263. }
  109264. }, function () {
  109265. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  109266. });
  109267. };
  109268. for (var buf in gltfRuntime.buffers) {
  109269. hasBuffers = true;
  109270. var buffer = gltfRuntime.buffers[buf];
  109271. if (buffer) {
  109272. processBuffer.bind(this, buf, buffer)();
  109273. }
  109274. else {
  109275. BABYLON.Tools.Error("No buffer named: " + buf);
  109276. }
  109277. }
  109278. if (!hasBuffers) {
  109279. onLoad();
  109280. }
  109281. };
  109282. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  109283. var currentScene = gltfRuntime.currentScene;
  109284. if (currentScene) {
  109285. // Only one scene even if multiple scenes are defined
  109286. for (var i = 0; i < currentScene.nodes.length; i++) {
  109287. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  109288. }
  109289. }
  109290. else {
  109291. // Load all scenes
  109292. for (var thing in gltfRuntime.scenes) {
  109293. currentScene = gltfRuntime.scenes[thing];
  109294. for (var i = 0; i < currentScene.nodes.length; i++) {
  109295. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  109296. }
  109297. }
  109298. }
  109299. };
  109300. GLTFLoader.Extensions = {};
  109301. return GLTFLoader;
  109302. }());
  109303. GLTF1.GLTFLoader = GLTFLoader;
  109304. ;
  109305. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  109306. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109307. })(BABYLON || (BABYLON = {}));
  109308. //# sourceMappingURL=babylon.glTFLoader.js.map
  109309. var BABYLON;
  109310. (function (BABYLON) {
  109311. var GLTF1;
  109312. (function (GLTF1) {
  109313. /**
  109314. * Utils functions for GLTF
  109315. */
  109316. var GLTFUtils = /** @class */ (function () {
  109317. function GLTFUtils() {
  109318. }
  109319. /**
  109320. * Sets the given "parameter" matrix
  109321. * @param scene: the {BABYLON.Scene} object
  109322. * @param source: the source node where to pick the matrix
  109323. * @param parameter: the GLTF technique parameter
  109324. * @param uniformName: the name of the shader's uniform
  109325. * @param shaderMaterial: the shader material
  109326. */
  109327. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  109328. var mat = null;
  109329. if (parameter.semantic === "MODEL") {
  109330. mat = source.getWorldMatrix();
  109331. }
  109332. else if (parameter.semantic === "PROJECTION") {
  109333. mat = scene.getProjectionMatrix();
  109334. }
  109335. else if (parameter.semantic === "VIEW") {
  109336. mat = scene.getViewMatrix();
  109337. }
  109338. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  109339. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  109340. }
  109341. else if (parameter.semantic === "MODELVIEW") {
  109342. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  109343. }
  109344. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  109345. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  109346. }
  109347. else if (parameter.semantic === "MODELINVERSE") {
  109348. mat = source.getWorldMatrix().invert();
  109349. }
  109350. else if (parameter.semantic === "VIEWINVERSE") {
  109351. mat = scene.getViewMatrix().invert();
  109352. }
  109353. else if (parameter.semantic === "PROJECTIONINVERSE") {
  109354. mat = scene.getProjectionMatrix().invert();
  109355. }
  109356. else if (parameter.semantic === "MODELVIEWINVERSE") {
  109357. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  109358. }
  109359. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  109360. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  109361. }
  109362. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  109363. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  109364. }
  109365. else {
  109366. debugger;
  109367. }
  109368. if (mat) {
  109369. switch (parameter.type) {
  109370. case GLTF1.EParameterType.FLOAT_MAT2:
  109371. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  109372. break;
  109373. case GLTF1.EParameterType.FLOAT_MAT3:
  109374. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  109375. break;
  109376. case GLTF1.EParameterType.FLOAT_MAT4:
  109377. shaderMaterial.setMatrix(uniformName, mat);
  109378. break;
  109379. default: break;
  109380. }
  109381. }
  109382. };
  109383. /**
  109384. * Sets the given "parameter" matrix
  109385. * @param shaderMaterial: the shader material
  109386. * @param uniform: the name of the shader's uniform
  109387. * @param value: the value of the uniform
  109388. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  109389. */
  109390. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  109391. switch (type) {
  109392. case GLTF1.EParameterType.FLOAT:
  109393. shaderMaterial.setFloat(uniform, value);
  109394. return true;
  109395. case GLTF1.EParameterType.FLOAT_VEC2:
  109396. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  109397. return true;
  109398. case GLTF1.EParameterType.FLOAT_VEC3:
  109399. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  109400. return true;
  109401. case GLTF1.EParameterType.FLOAT_VEC4:
  109402. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  109403. return true;
  109404. default: return false;
  109405. }
  109406. };
  109407. /**
  109408. * Returns the wrap mode of the texture
  109409. * @param mode: the mode value
  109410. */
  109411. GLTFUtils.GetWrapMode = function (mode) {
  109412. switch (mode) {
  109413. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  109414. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  109415. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  109416. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  109417. }
  109418. };
  109419. /**
  109420. * Returns the byte stride giving an accessor
  109421. * @param accessor: the GLTF accessor objet
  109422. */
  109423. GLTFUtils.GetByteStrideFromType = function (accessor) {
  109424. // Needs this function since "byteStride" isn't requiered in glTF format
  109425. var type = accessor.type;
  109426. switch (type) {
  109427. case "VEC2": return 2;
  109428. case "VEC3": return 3;
  109429. case "VEC4": return 4;
  109430. case "MAT2": return 4;
  109431. case "MAT3": return 9;
  109432. case "MAT4": return 16;
  109433. default: return 1;
  109434. }
  109435. };
  109436. /**
  109437. * Returns the texture filter mode giving a mode value
  109438. * @param mode: the filter mode value
  109439. */
  109440. GLTFUtils.GetTextureFilterMode = function (mode) {
  109441. switch (mode) {
  109442. case GLTF1.ETextureFilterType.LINEAR:
  109443. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  109444. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  109445. case GLTF1.ETextureFilterType.NEAREST:
  109446. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  109447. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  109448. }
  109449. };
  109450. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  109451. var byteOffset = bufferView.byteOffset + byteOffset;
  109452. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  109453. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  109454. throw new Error("Buffer access is out of range");
  109455. }
  109456. var buffer = loadedBufferView.buffer;
  109457. byteOffset += loadedBufferView.byteOffset;
  109458. switch (componentType) {
  109459. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  109460. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  109461. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  109462. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  109463. default: return new Float32Array(buffer, byteOffset, byteLength);
  109464. }
  109465. };
  109466. /**
  109467. * Returns a buffer from its accessor
  109468. * @param gltfRuntime: the GLTF runtime
  109469. * @param accessor: the GLTF accessor
  109470. */
  109471. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  109472. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  109473. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  109474. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  109475. };
  109476. /**
  109477. * Decodes a buffer view into a string
  109478. * @param view: the buffer view
  109479. */
  109480. GLTFUtils.DecodeBufferToText = function (view) {
  109481. var result = "";
  109482. var length = view.byteLength;
  109483. for (var i = 0; i < length; ++i) {
  109484. result += String.fromCharCode(view[i]);
  109485. }
  109486. return result;
  109487. };
  109488. /**
  109489. * Returns the default material of gltf. Related to
  109490. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  109491. * @param scene: the Babylon.js scene
  109492. */
  109493. GLTFUtils.GetDefaultMaterial = function (scene) {
  109494. if (!GLTFUtils._DefaultMaterial) {
  109495. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  109496. "precision highp float;",
  109497. "",
  109498. "uniform mat4 worldView;",
  109499. "uniform mat4 projection;",
  109500. "",
  109501. "attribute vec3 position;",
  109502. "",
  109503. "void main(void)",
  109504. "{",
  109505. " gl_Position = projection * worldView * vec4(position, 1.0);",
  109506. "}"
  109507. ].join("\n");
  109508. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  109509. "precision highp float;",
  109510. "",
  109511. "uniform vec4 u_emission;",
  109512. "",
  109513. "void main(void)",
  109514. "{",
  109515. " gl_FragColor = u_emission;",
  109516. "}"
  109517. ].join("\n");
  109518. var shaderPath = {
  109519. vertex: "GLTFDefaultMaterial",
  109520. fragment: "GLTFDefaultMaterial"
  109521. };
  109522. var options = {
  109523. attributes: ["position"],
  109524. uniforms: ["worldView", "projection", "u_emission"],
  109525. samplers: new Array(),
  109526. needAlphaBlending: false
  109527. };
  109528. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  109529. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  109530. }
  109531. return GLTFUtils._DefaultMaterial;
  109532. };
  109533. // The GLTF default material
  109534. GLTFUtils._DefaultMaterial = null;
  109535. return GLTFUtils;
  109536. }());
  109537. GLTF1.GLTFUtils = GLTFUtils;
  109538. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109539. })(BABYLON || (BABYLON = {}));
  109540. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  109541. var BABYLON;
  109542. (function (BABYLON) {
  109543. var GLTF1;
  109544. (function (GLTF1) {
  109545. var GLTFLoaderExtension = /** @class */ (function () {
  109546. function GLTFLoaderExtension(name) {
  109547. this._name = name;
  109548. }
  109549. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  109550. get: function () {
  109551. return this._name;
  109552. },
  109553. enumerable: true,
  109554. configurable: true
  109555. });
  109556. /**
  109557. * Defines an override for loading the runtime
  109558. * Return true to stop further extensions from loading the runtime
  109559. */
  109560. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109561. return false;
  109562. };
  109563. /**
  109564. * Defines an onverride for creating gltf runtime
  109565. * Return true to stop further extensions from creating the runtime
  109566. */
  109567. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109568. return false;
  109569. };
  109570. /**
  109571. * Defines an override for loading buffers
  109572. * Return true to stop further extensions from loading this buffer
  109573. */
  109574. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  109575. return false;
  109576. };
  109577. /**
  109578. * Defines an override for loading texture buffers
  109579. * Return true to stop further extensions from loading this texture data
  109580. */
  109581. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109582. return false;
  109583. };
  109584. /**
  109585. * Defines an override for creating textures
  109586. * Return true to stop further extensions from loading this texture
  109587. */
  109588. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  109589. return false;
  109590. };
  109591. /**
  109592. * Defines an override for loading shader strings
  109593. * Return true to stop further extensions from loading this shader data
  109594. */
  109595. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109596. return false;
  109597. };
  109598. /**
  109599. * Defines an override for loading materials
  109600. * Return true to stop further extensions from loading this material
  109601. */
  109602. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109603. return false;
  109604. };
  109605. // ---------
  109606. // Utilities
  109607. // ---------
  109608. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109609. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109610. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  109611. }, function () {
  109612. setTimeout(function () {
  109613. if (!onSuccess) {
  109614. return;
  109615. }
  109616. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  109617. });
  109618. });
  109619. };
  109620. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109621. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109622. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  109623. }, function () {
  109624. setTimeout(function () {
  109625. onSuccess();
  109626. });
  109627. });
  109628. };
  109629. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  109630. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109631. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  109632. }, function () {
  109633. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  109634. });
  109635. };
  109636. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  109637. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  109638. if (buffer) {
  109639. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109640. }
  109641. }, onError);
  109642. };
  109643. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109644. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109645. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  109646. }, function () {
  109647. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  109648. });
  109649. };
  109650. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109651. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109652. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  109653. }, function () {
  109654. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  109655. });
  109656. };
  109657. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109658. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109659. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  109660. }, function () {
  109661. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  109662. });
  109663. };
  109664. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  109665. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109666. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109667. }, function () {
  109668. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109669. });
  109670. };
  109671. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  109672. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  109673. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  109674. if (func(loaderExtension)) {
  109675. return;
  109676. }
  109677. }
  109678. defaultFunc();
  109679. };
  109680. return GLTFLoaderExtension;
  109681. }());
  109682. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  109683. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109684. })(BABYLON || (BABYLON = {}));
  109685. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  109686. var BABYLON;
  109687. (function (BABYLON) {
  109688. var GLTF1;
  109689. (function (GLTF1) {
  109690. var BinaryExtensionBufferName = "binary_glTF";
  109691. ;
  109692. ;
  109693. var GLTFBinaryExtension = /** @class */ (function (_super) {
  109694. __extends(GLTFBinaryExtension, _super);
  109695. function GLTFBinaryExtension() {
  109696. return _super.call(this, "KHR_binary_glTF") || this;
  109697. }
  109698. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109699. var extensionsUsed = data.json.extensionsUsed;
  109700. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  109701. return false;
  109702. }
  109703. this._bin = data.bin;
  109704. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  109705. return true;
  109706. };
  109707. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109708. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  109709. return false;
  109710. }
  109711. if (id !== BinaryExtensionBufferName) {
  109712. return false;
  109713. }
  109714. onSuccess(this._bin);
  109715. return true;
  109716. };
  109717. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109718. var texture = gltfRuntime.textures[id];
  109719. var source = gltfRuntime.images[texture.source];
  109720. if (!source.extensions || !(this.name in source.extensions)) {
  109721. return false;
  109722. }
  109723. var sourceExt = source.extensions[this.name];
  109724. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  109725. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  109726. onSuccess(buffer);
  109727. return true;
  109728. };
  109729. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109730. var shader = gltfRuntime.shaders[id];
  109731. if (!shader.extensions || !(this.name in shader.extensions)) {
  109732. return false;
  109733. }
  109734. var binaryExtensionShader = shader.extensions[this.name];
  109735. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  109736. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  109737. setTimeout(function () {
  109738. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  109739. onSuccess(shaderString);
  109740. });
  109741. return true;
  109742. };
  109743. return GLTFBinaryExtension;
  109744. }(GLTF1.GLTFLoaderExtension));
  109745. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  109746. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  109747. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109748. })(BABYLON || (BABYLON = {}));
  109749. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  109750. var BABYLON;
  109751. (function (BABYLON) {
  109752. var GLTF1;
  109753. (function (GLTF1) {
  109754. ;
  109755. ;
  109756. ;
  109757. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  109758. __extends(GLTFMaterialsCommonExtension, _super);
  109759. function GLTFMaterialsCommonExtension() {
  109760. return _super.call(this, "KHR_materials_common") || this;
  109761. }
  109762. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109763. if (!gltfRuntime.extensions)
  109764. return false;
  109765. var extension = gltfRuntime.extensions[this.name];
  109766. if (!extension)
  109767. return false;
  109768. // Create lights
  109769. var lights = extension.lights;
  109770. if (lights) {
  109771. for (var thing in lights) {
  109772. var light = lights[thing];
  109773. switch (light.type) {
  109774. case "ambient":
  109775. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  109776. var ambient = light.ambient;
  109777. if (ambient) {
  109778. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  109779. }
  109780. break;
  109781. case "point":
  109782. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  109783. var point = light.point;
  109784. if (point) {
  109785. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  109786. }
  109787. break;
  109788. case "directional":
  109789. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  109790. var directional = light.directional;
  109791. if (directional) {
  109792. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  109793. }
  109794. break;
  109795. case "spot":
  109796. var spot = light.spot;
  109797. if (spot) {
  109798. 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);
  109799. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  109800. }
  109801. break;
  109802. default:
  109803. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  109804. break;
  109805. }
  109806. }
  109807. }
  109808. return false;
  109809. };
  109810. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109811. var material = gltfRuntime.materials[id];
  109812. if (!material || !material.extensions)
  109813. return false;
  109814. var extension = material.extensions[this.name];
  109815. if (!extension)
  109816. return false;
  109817. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  109818. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  109819. if (extension.technique === "CONSTANT") {
  109820. standardMaterial.disableLighting = true;
  109821. }
  109822. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  109823. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  109824. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  109825. // Ambient
  109826. if (typeof extension.values.ambient === "string") {
  109827. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  109828. }
  109829. else {
  109830. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  109831. }
  109832. // Diffuse
  109833. if (typeof extension.values.diffuse === "string") {
  109834. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  109835. }
  109836. else {
  109837. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  109838. }
  109839. // Emission
  109840. if (typeof extension.values.emission === "string") {
  109841. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  109842. }
  109843. else {
  109844. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  109845. }
  109846. // Specular
  109847. if (typeof extension.values.specular === "string") {
  109848. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  109849. }
  109850. else {
  109851. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  109852. }
  109853. return true;
  109854. };
  109855. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  109856. // Create buffer from texture url
  109857. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  109858. // Create texture from buffer
  109859. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  109860. }, onError);
  109861. };
  109862. return GLTFMaterialsCommonExtension;
  109863. }(GLTF1.GLTFLoaderExtension));
  109864. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  109865. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  109866. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109867. })(BABYLON || (BABYLON = {}));
  109868. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  109869. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  109870. /**
  109871. * Defines the module used to import/export glTF 2.0 assets
  109872. */
  109873. var BABYLON;
  109874. (function (BABYLON) {
  109875. var GLTF2;
  109876. (function (GLTF2) {
  109877. var _ArrayItem = /** @class */ (function () {
  109878. function _ArrayItem() {
  109879. }
  109880. _ArrayItem.Assign = function (values) {
  109881. if (values) {
  109882. for (var index = 0; index < values.length; index++) {
  109883. values[index]._index = index;
  109884. }
  109885. }
  109886. };
  109887. return _ArrayItem;
  109888. }());
  109889. /** @hidden */
  109890. var GLTFLoader = /** @class */ (function () {
  109891. function GLTFLoader(parent) {
  109892. this._completePromises = new Array();
  109893. this._disposed = false;
  109894. this._state = null;
  109895. this._extensions = {};
  109896. this._defaultSampler = {};
  109897. this._defaultBabylonMaterials = {};
  109898. this._requests = new Array();
  109899. this._parent = parent;
  109900. }
  109901. GLTFLoader._Register = function (name, factory) {
  109902. if (GLTFLoader._ExtensionFactories[name]) {
  109903. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  109904. return;
  109905. }
  109906. GLTFLoader._ExtensionFactories[name] = factory;
  109907. // Keep the order of registration so that extensions registered first are called first.
  109908. GLTFLoader._ExtensionNames.push(name);
  109909. };
  109910. Object.defineProperty(GLTFLoader.prototype, "state", {
  109911. /**
  109912. * Loader state or null if the loader is not active.
  109913. */
  109914. get: function () {
  109915. return this._state;
  109916. },
  109917. enumerable: true,
  109918. configurable: true
  109919. });
  109920. GLTFLoader.prototype.dispose = function () {
  109921. if (this._disposed) {
  109922. return;
  109923. }
  109924. this._disposed = true;
  109925. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109926. var request = _a[_i];
  109927. request.abort();
  109928. }
  109929. this._requests.length = 0;
  109930. delete this._gltf;
  109931. delete this._babylonScene;
  109932. delete this._readyPromise;
  109933. this._completePromises.length = 0;
  109934. for (var name_1 in this._extensions) {
  109935. this._extensions[name_1].dispose();
  109936. }
  109937. this._extensions = {};
  109938. delete this._rootBabylonMesh;
  109939. delete this._progressCallback;
  109940. this._parent._clear();
  109941. };
  109942. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  109943. var _this = this;
  109944. return Promise.resolve().then(function () {
  109945. _this._babylonScene = scene;
  109946. _this._rootUrl = rootUrl;
  109947. _this._progressCallback = onProgress;
  109948. _this._loadData(data);
  109949. var nodes = null;
  109950. if (meshesNames) {
  109951. var nodeMap_1 = {};
  109952. if (_this._gltf.nodes) {
  109953. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  109954. var node = _a[_i];
  109955. if (node.name) {
  109956. nodeMap_1[node.name] = node._index;
  109957. }
  109958. }
  109959. }
  109960. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  109961. nodes = names.map(function (name) {
  109962. var node = nodeMap_1[name];
  109963. if (node === undefined) {
  109964. throw new Error("Failed to find node '" + name + "'");
  109965. }
  109966. return node;
  109967. });
  109968. }
  109969. return _this._loadAsync(nodes).then(function () {
  109970. return {
  109971. meshes: _this._getMeshes(),
  109972. particleSystems: [],
  109973. skeletons: _this._getSkeletons(),
  109974. animationGroups: _this._getAnimationGroups()
  109975. };
  109976. });
  109977. });
  109978. };
  109979. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  109980. var _this = this;
  109981. return Promise.resolve().then(function () {
  109982. _this._babylonScene = scene;
  109983. _this._rootUrl = rootUrl;
  109984. _this._progressCallback = onProgress;
  109985. _this._loadData(data);
  109986. return _this._loadAsync(null);
  109987. });
  109988. };
  109989. GLTFLoader.prototype._loadAsync = function (nodes) {
  109990. var _this = this;
  109991. return Promise.resolve().then(function () {
  109992. _this._parent._startPerformanceCounter("Loading => Ready");
  109993. _this._parent._startPerformanceCounter("Loading => Complete");
  109994. _this._state = BABYLON.GLTFLoaderState.LOADING;
  109995. _this._parent._log("Loading");
  109996. var readyDeferred = new BABYLON.Deferred();
  109997. _this._readyPromise = readyDeferred.promise;
  109998. _this._loadExtensions();
  109999. _this._checkExtensions();
  110000. var promises = new Array();
  110001. if (nodes) {
  110002. promises.push(_this._loadSceneAsync("#/nodes", { nodes: nodes, _index: -1 }));
  110003. }
  110004. else {
  110005. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  110006. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  110007. }
  110008. if (_this._parent.compileMaterials) {
  110009. promises.push(_this._compileMaterialsAsync());
  110010. }
  110011. if (_this._parent.compileShadowGenerators) {
  110012. promises.push(_this._compileShadowGeneratorsAsync());
  110013. }
  110014. var resultPromise = Promise.all(promises).then(function () {
  110015. _this._state = BABYLON.GLTFLoaderState.READY;
  110016. _this._parent._log("Ready");
  110017. readyDeferred.resolve();
  110018. _this._startAnimations();
  110019. });
  110020. resultPromise.then(function () {
  110021. _this._parent._endPerformanceCounter("Loading => Ready");
  110022. BABYLON.Tools.SetImmediate(function () {
  110023. if (!_this._disposed) {
  110024. Promise.all(_this._completePromises).then(function () {
  110025. _this._parent._endPerformanceCounter("Loading => Complete");
  110026. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  110027. _this._parent._log("Complete");
  110028. _this._parent.onCompleteObservable.notifyObservers(undefined);
  110029. _this._parent.onCompleteObservable.clear();
  110030. _this.dispose();
  110031. }).catch(function (error) {
  110032. BABYLON.Tools.Error("glTF Loader: " + error.message);
  110033. _this.dispose();
  110034. });
  110035. }
  110036. });
  110037. });
  110038. return resultPromise;
  110039. }).catch(function (error) {
  110040. if (!_this._disposed) {
  110041. BABYLON.Tools.Error("glTF Loader: " + error.message);
  110042. _this.dispose();
  110043. throw error;
  110044. }
  110045. });
  110046. };
  110047. GLTFLoader.prototype._loadData = function (data) {
  110048. this._gltf = data.json;
  110049. this._setupData();
  110050. if (data.bin) {
  110051. var buffers = this._gltf.buffers;
  110052. if (buffers && buffers[0] && !buffers[0].uri) {
  110053. var binaryBuffer = buffers[0];
  110054. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  110055. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  110056. }
  110057. binaryBuffer._data = Promise.resolve(data.bin);
  110058. }
  110059. else {
  110060. BABYLON.Tools.Warn("Unexpected BIN chunk");
  110061. }
  110062. }
  110063. };
  110064. GLTFLoader.prototype._setupData = function () {
  110065. _ArrayItem.Assign(this._gltf.accessors);
  110066. _ArrayItem.Assign(this._gltf.animations);
  110067. _ArrayItem.Assign(this._gltf.buffers);
  110068. _ArrayItem.Assign(this._gltf.bufferViews);
  110069. _ArrayItem.Assign(this._gltf.cameras);
  110070. _ArrayItem.Assign(this._gltf.images);
  110071. _ArrayItem.Assign(this._gltf.materials);
  110072. _ArrayItem.Assign(this._gltf.meshes);
  110073. _ArrayItem.Assign(this._gltf.nodes);
  110074. _ArrayItem.Assign(this._gltf.samplers);
  110075. _ArrayItem.Assign(this._gltf.scenes);
  110076. _ArrayItem.Assign(this._gltf.skins);
  110077. _ArrayItem.Assign(this._gltf.textures);
  110078. if (this._gltf.nodes) {
  110079. var nodeParents = {};
  110080. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  110081. var node = _a[_i];
  110082. if (node.children) {
  110083. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  110084. var index = _c[_b];
  110085. nodeParents[index] = node._index;
  110086. }
  110087. }
  110088. }
  110089. var rootNode = this._createRootNode();
  110090. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  110091. var node = _e[_d];
  110092. var parentIndex = nodeParents[node._index];
  110093. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  110094. }
  110095. }
  110096. };
  110097. GLTFLoader.prototype._loadExtensions = function () {
  110098. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  110099. var name_2 = _a[_i];
  110100. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  110101. this._extensions[name_2] = extension;
  110102. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  110103. }
  110104. this._parent.onExtensionLoadedObservable.clear();
  110105. };
  110106. GLTFLoader.prototype._checkExtensions = function () {
  110107. if (this._gltf.extensionsRequired) {
  110108. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  110109. var name_3 = _a[_i];
  110110. var extension = this._extensions[name_3];
  110111. if (!extension || !extension.enabled) {
  110112. throw new Error("Require extension " + name_3 + " is not available");
  110113. }
  110114. }
  110115. }
  110116. };
  110117. GLTFLoader.prototype._createRootNode = function () {
  110118. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  110119. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  110120. switch (this._parent.coordinateSystemMode) {
  110121. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  110122. if (!this._babylonScene.useRightHandedSystem) {
  110123. rootNode.rotation = [0, 1, 0, 0];
  110124. rootNode.scale = [1, 1, -1];
  110125. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  110126. }
  110127. break;
  110128. }
  110129. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  110130. this._babylonScene.useRightHandedSystem = true;
  110131. break;
  110132. }
  110133. default: {
  110134. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  110135. }
  110136. }
  110137. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  110138. return rootNode;
  110139. };
  110140. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  110141. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  110142. if (promise) {
  110143. return promise;
  110144. }
  110145. var promises = new Array();
  110146. this._parent._logOpen(context + " " + (scene.name || ""));
  110147. if (scene.nodes) {
  110148. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  110149. var index = _a[_i];
  110150. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  110151. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  110152. }
  110153. }
  110154. promises.push(this._loadAnimationsAsync());
  110155. this._parent._logClose();
  110156. return Promise.all(promises).then(function () { });
  110157. };
  110158. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  110159. if (node._primitiveBabylonMeshes) {
  110160. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  110161. var babylonMesh = _a[_i];
  110162. callback(babylonMesh);
  110163. }
  110164. }
  110165. else {
  110166. callback(node._babylonMesh);
  110167. }
  110168. };
  110169. GLTFLoader.prototype._getMeshes = function () {
  110170. var meshes = new Array();
  110171. // Root mesh is always first.
  110172. meshes.push(this._rootBabylonMesh);
  110173. var nodes = this._gltf.nodes;
  110174. if (nodes) {
  110175. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  110176. var node = nodes_1[_i];
  110177. if (node._babylonMesh) {
  110178. meshes.push(node._babylonMesh);
  110179. }
  110180. if (node._primitiveBabylonMeshes) {
  110181. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  110182. var babylonMesh = _b[_a];
  110183. meshes.push(babylonMesh);
  110184. }
  110185. }
  110186. }
  110187. }
  110188. return meshes;
  110189. };
  110190. GLTFLoader.prototype._getSkeletons = function () {
  110191. var skeletons = new Array();
  110192. var skins = this._gltf.skins;
  110193. if (skins) {
  110194. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  110195. var skin = skins_1[_i];
  110196. if (skin._babylonSkeleton) {
  110197. skeletons.push(skin._babylonSkeleton);
  110198. }
  110199. }
  110200. }
  110201. return skeletons;
  110202. };
  110203. GLTFLoader.prototype._getAnimationGroups = function () {
  110204. var animationGroups = new Array();
  110205. var animations = this._gltf.animations;
  110206. if (animations) {
  110207. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  110208. var animation = animations_1[_i];
  110209. if (animation._babylonAnimationGroup) {
  110210. animationGroups.push(animation._babylonAnimationGroup);
  110211. }
  110212. }
  110213. }
  110214. return animationGroups;
  110215. };
  110216. GLTFLoader.prototype._startAnimations = function () {
  110217. switch (this._parent.animationStartMode) {
  110218. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  110219. // do nothing
  110220. break;
  110221. }
  110222. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  110223. var babylonAnimationGroups = this._getAnimationGroups();
  110224. if (babylonAnimationGroups.length !== 0) {
  110225. babylonAnimationGroups[0].start(true);
  110226. }
  110227. break;
  110228. }
  110229. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  110230. var babylonAnimationGroups = this._getAnimationGroups();
  110231. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  110232. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  110233. babylonAnimationGroup.start(true);
  110234. }
  110235. break;
  110236. }
  110237. default: {
  110238. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  110239. return;
  110240. }
  110241. }
  110242. };
  110243. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  110244. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  110245. if (promise) {
  110246. return promise;
  110247. }
  110248. if (node._babylonMesh) {
  110249. throw new Error(context + ": Invalid recursive node hierarchy");
  110250. }
  110251. var promises = new Array();
  110252. this._parent._logOpen(context + " " + (node.name || ""));
  110253. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  110254. node._babylonMesh = babylonMesh;
  110255. babylonMesh.setEnabled(false);
  110256. GLTFLoader._LoadTransform(node, babylonMesh);
  110257. if (node.mesh != undefined) {
  110258. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  110259. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  110260. }
  110261. if (node.camera != undefined) {
  110262. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  110263. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  110264. }
  110265. if (node.children) {
  110266. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  110267. var index = _a[_i];
  110268. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  110269. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  110270. }
  110271. }
  110272. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  110273. this._parent._logClose();
  110274. return Promise.all(promises).then(function () {
  110275. babylonMesh.setEnabled(true);
  110276. });
  110277. };
  110278. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  110279. var _this = this;
  110280. var promises = new Array();
  110281. this._parent._logOpen(context + " " + (mesh.name || ""));
  110282. var primitives = mesh.primitives;
  110283. if (!primitives || primitives.length === 0) {
  110284. throw new Error(context + ": Primitives are missing");
  110285. }
  110286. _ArrayItem.Assign(primitives);
  110287. if (primitives.length === 1) {
  110288. var primitive = primitives[0];
  110289. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  110290. }
  110291. else {
  110292. node._primitiveBabylonMeshes = [];
  110293. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  110294. var primitive = primitives_1[_i];
  110295. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  110296. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  110297. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  110298. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  110299. }
  110300. }
  110301. if (node.skin != undefined) {
  110302. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  110303. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  110304. }
  110305. this._parent._logClose();
  110306. return Promise.all(promises).then(function () {
  110307. _this._forEachPrimitive(node, function (babylonMesh) {
  110308. babylonMesh._refreshBoundingInfo(true);
  110309. });
  110310. });
  110311. };
  110312. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  110313. var _this = this;
  110314. var promises = new Array();
  110315. this._parent._logOpen("" + context);
  110316. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  110317. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  110318. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  110319. babylonGeometry.applyToMesh(babylonMesh);
  110320. });
  110321. }));
  110322. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  110323. if (primitive.material == undefined) {
  110324. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  110325. }
  110326. else {
  110327. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  110328. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  110329. babylonMesh.material = babylonMaterial;
  110330. }));
  110331. }
  110332. this._parent._logClose();
  110333. return Promise.all(promises).then(function () { });
  110334. };
  110335. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  110336. var _this = this;
  110337. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  110338. if (promise) {
  110339. return promise;
  110340. }
  110341. var attributes = primitive.attributes;
  110342. if (!attributes) {
  110343. throw new Error(context + ": Attributes are missing");
  110344. }
  110345. var promises = new Array();
  110346. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  110347. if (primitive.indices == undefined) {
  110348. babylonMesh.isUnIndexed = true;
  110349. }
  110350. else {
  110351. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  110352. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  110353. babylonGeometry.setIndices(data);
  110354. }));
  110355. }
  110356. var loadAttribute = function (attribute, kind, callback) {
  110357. if (attributes[attribute] == undefined) {
  110358. return;
  110359. }
  110360. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  110361. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  110362. babylonMesh._delayInfo.push(kind);
  110363. }
  110364. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  110365. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  110366. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  110367. }));
  110368. if (callback) {
  110369. callback(accessor);
  110370. }
  110371. };
  110372. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  110373. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  110374. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  110375. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  110376. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  110377. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  110378. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  110379. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  110380. if (accessor.type === "VEC4" /* VEC4 */) {
  110381. babylonMesh.hasVertexAlpha = true;
  110382. }
  110383. });
  110384. return Promise.all(promises).then(function () {
  110385. return babylonGeometry;
  110386. });
  110387. };
  110388. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  110389. if (!primitive.targets) {
  110390. return;
  110391. }
  110392. if (node._numMorphTargets == undefined) {
  110393. node._numMorphTargets = primitive.targets.length;
  110394. }
  110395. else if (primitive.targets.length !== node._numMorphTargets) {
  110396. throw new Error(context + ": Primitives do not have the same number of targets");
  110397. }
  110398. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  110399. for (var index = 0; index < primitive.targets.length; index++) {
  110400. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  110401. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  110402. // TODO: tell the target whether it has positions, normals, tangents
  110403. }
  110404. };
  110405. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  110406. if (!primitive.targets) {
  110407. return Promise.resolve();
  110408. }
  110409. var promises = new Array();
  110410. var morphTargetManager = babylonMesh.morphTargetManager;
  110411. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  110412. var babylonMorphTarget = morphTargetManager.getTarget(index);
  110413. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  110414. }
  110415. return Promise.all(promises).then(function () { });
  110416. };
  110417. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  110418. var _this = this;
  110419. var promises = new Array();
  110420. var loadAttribute = function (attribute, kind, setData) {
  110421. if (attributes[attribute] == undefined) {
  110422. return;
  110423. }
  110424. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  110425. if (!babylonVertexBuffer) {
  110426. return;
  110427. }
  110428. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  110429. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  110430. setData(babylonVertexBuffer, data);
  110431. }));
  110432. };
  110433. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  110434. babylonVertexBuffer.forEach(data.length, function (value, index) {
  110435. data[index] += value;
  110436. });
  110437. babylonMorphTarget.setPositions(data);
  110438. });
  110439. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  110440. babylonVertexBuffer.forEach(data.length, function (value, index) {
  110441. data[index] += value;
  110442. });
  110443. babylonMorphTarget.setNormals(data);
  110444. });
  110445. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  110446. var dataIndex = 0;
  110447. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  110448. // Tangent data for morph targets is stored as xyz delta.
  110449. // The vertexData.tangent is stored as xyzw.
  110450. // So we need to skip every fourth vertexData.tangent.
  110451. if (((index + 1) % 4) !== 0) {
  110452. data[dataIndex++] += value;
  110453. }
  110454. });
  110455. babylonMorphTarget.setTangents(data);
  110456. });
  110457. return Promise.all(promises).then(function () { });
  110458. };
  110459. GLTFLoader._LoadTransform = function (node, babylonNode) {
  110460. var position = BABYLON.Vector3.Zero();
  110461. var rotation = BABYLON.Quaternion.Identity();
  110462. var scaling = BABYLON.Vector3.One();
  110463. if (node.matrix) {
  110464. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  110465. matrix.decompose(scaling, rotation, position);
  110466. }
  110467. else {
  110468. if (node.translation)
  110469. position = BABYLON.Vector3.FromArray(node.translation);
  110470. if (node.rotation)
  110471. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  110472. if (node.scale)
  110473. scaling = BABYLON.Vector3.FromArray(node.scale);
  110474. }
  110475. babylonNode.position = position;
  110476. babylonNode.rotationQuaternion = rotation;
  110477. babylonNode.scaling = scaling;
  110478. };
  110479. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  110480. var _this = this;
  110481. var assignSkeleton = function (skeleton) {
  110482. _this._forEachPrimitive(node, function (babylonMesh) {
  110483. babylonMesh.skeleton = skeleton;
  110484. });
  110485. // Ignore the TRS of skinned nodes.
  110486. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  110487. node._babylonMesh.parent = _this._rootBabylonMesh;
  110488. node._babylonMesh.position = BABYLON.Vector3.Zero();
  110489. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  110490. node._babylonMesh.scaling = BABYLON.Vector3.One();
  110491. };
  110492. if (skin._loaded) {
  110493. return skin._loaded.then(function () {
  110494. assignSkeleton(skin._babylonSkeleton);
  110495. });
  110496. }
  110497. var skeletonId = "skeleton" + skin._index;
  110498. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  110499. skin._babylonSkeleton = babylonSkeleton;
  110500. this._loadBones(context, skin);
  110501. assignSkeleton(babylonSkeleton);
  110502. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  110503. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  110504. }));
  110505. };
  110506. GLTFLoader.prototype._loadBones = function (context, skin) {
  110507. var babylonBones = {};
  110508. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  110509. var index = _a[_i];
  110510. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  110511. this._loadBone(node, skin, babylonBones);
  110512. }
  110513. };
  110514. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  110515. var babylonBone = babylonBones[node._index];
  110516. if (babylonBone) {
  110517. return babylonBone;
  110518. }
  110519. var babylonParentBone = null;
  110520. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  110521. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  110522. }
  110523. var boneIndex = skin.joints.indexOf(node._index);
  110524. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  110525. babylonBones[node._index] = babylonBone;
  110526. node._babylonBones = node._babylonBones || [];
  110527. node._babylonBones.push(babylonBone);
  110528. return babylonBone;
  110529. };
  110530. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  110531. if (skin.inverseBindMatrices == undefined) {
  110532. return Promise.resolve(null);
  110533. }
  110534. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  110535. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  110536. };
  110537. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  110538. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  110539. var babylonBone = _a[_i];
  110540. var baseMatrix = BABYLON.Matrix.Identity();
  110541. var boneIndex = babylonBone._index;
  110542. if (inverseBindMatricesData && boneIndex !== -1) {
  110543. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  110544. baseMatrix.invertToRef(baseMatrix);
  110545. }
  110546. var babylonParentBone = babylonBone.getParent();
  110547. if (babylonParentBone) {
  110548. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  110549. }
  110550. babylonBone.updateMatrix(baseMatrix, false, false);
  110551. babylonBone._updateDifferenceMatrix(undefined, false);
  110552. }
  110553. };
  110554. GLTFLoader.prototype._getNodeMatrix = function (node) {
  110555. return node.matrix ?
  110556. BABYLON.Matrix.FromArray(node.matrix) :
  110557. 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());
  110558. };
  110559. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  110560. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  110561. babylonCamera.parent = babylonMesh;
  110562. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  110563. switch (camera.type) {
  110564. case "perspective" /* PERSPECTIVE */: {
  110565. var perspective = camera.perspective;
  110566. if (!perspective) {
  110567. throw new Error(context + ": Camera perspective properties are missing");
  110568. }
  110569. babylonCamera.fov = perspective.yfov;
  110570. babylonCamera.minZ = perspective.znear;
  110571. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  110572. break;
  110573. }
  110574. case "orthographic" /* ORTHOGRAPHIC */: {
  110575. if (!camera.orthographic) {
  110576. throw new Error(context + ": Camera orthographic properties are missing");
  110577. }
  110578. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  110579. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  110580. babylonCamera.orthoRight = camera.orthographic.xmag;
  110581. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  110582. babylonCamera.orthoTop = camera.orthographic.ymag;
  110583. babylonCamera.minZ = camera.orthographic.znear;
  110584. babylonCamera.maxZ = camera.orthographic.zfar;
  110585. break;
  110586. }
  110587. default: {
  110588. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  110589. }
  110590. }
  110591. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  110592. };
  110593. GLTFLoader.prototype._loadAnimationsAsync = function () {
  110594. var animations = this._gltf.animations;
  110595. if (!animations) {
  110596. return Promise.resolve();
  110597. }
  110598. var promises = new Array();
  110599. for (var index = 0; index < animations.length; index++) {
  110600. var animation = animations[index];
  110601. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  110602. }
  110603. return Promise.all(promises).then(function () { });
  110604. };
  110605. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  110606. var _this = this;
  110607. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  110608. animation._babylonAnimationGroup = babylonAnimationGroup;
  110609. var promises = new Array();
  110610. _ArrayItem.Assign(animation.channels);
  110611. _ArrayItem.Assign(animation.samplers);
  110612. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  110613. var channel = _a[_i];
  110614. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  110615. }
  110616. return Promise.all(promises).then(function () {
  110617. babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  110618. });
  110619. };
  110620. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  110621. var _this = this;
  110622. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  110623. // Ignore animations that have no animation targets.
  110624. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  110625. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  110626. return Promise.resolve();
  110627. }
  110628. // Ignore animations targeting TRS of skinned nodes.
  110629. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  110630. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  110631. return Promise.resolve();
  110632. }
  110633. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  110634. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  110635. var targetPath;
  110636. var animationType;
  110637. switch (channel.target.path) {
  110638. case "translation" /* TRANSLATION */: {
  110639. targetPath = "position";
  110640. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  110641. break;
  110642. }
  110643. case "rotation" /* ROTATION */: {
  110644. targetPath = "rotationQuaternion";
  110645. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  110646. break;
  110647. }
  110648. case "scale" /* SCALE */: {
  110649. targetPath = "scaling";
  110650. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  110651. break;
  110652. }
  110653. case "weights" /* WEIGHTS */: {
  110654. targetPath = "influence";
  110655. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  110656. break;
  110657. }
  110658. default: {
  110659. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  110660. }
  110661. }
  110662. var outputBufferOffset = 0;
  110663. var getNextOutputValue;
  110664. switch (targetPath) {
  110665. case "position": {
  110666. getNextOutputValue = function () {
  110667. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  110668. outputBufferOffset += 3;
  110669. return value;
  110670. };
  110671. break;
  110672. }
  110673. case "rotationQuaternion": {
  110674. getNextOutputValue = function () {
  110675. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  110676. outputBufferOffset += 4;
  110677. return value;
  110678. };
  110679. break;
  110680. }
  110681. case "scaling": {
  110682. getNextOutputValue = function () {
  110683. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  110684. outputBufferOffset += 3;
  110685. return value;
  110686. };
  110687. break;
  110688. }
  110689. case "influence": {
  110690. getNextOutputValue = function () {
  110691. var value = new Array(targetNode._numMorphTargets);
  110692. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  110693. value[i] = data.output[outputBufferOffset++];
  110694. }
  110695. return value;
  110696. };
  110697. break;
  110698. }
  110699. }
  110700. var getNextKey;
  110701. switch (data.interpolation) {
  110702. case "STEP" /* STEP */: {
  110703. getNextKey = function (frameIndex) { return ({
  110704. frame: data.input[frameIndex],
  110705. value: getNextOutputValue(),
  110706. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  110707. }); };
  110708. break;
  110709. }
  110710. case "LINEAR" /* LINEAR */: {
  110711. getNextKey = function (frameIndex) { return ({
  110712. frame: data.input[frameIndex],
  110713. value: getNextOutputValue()
  110714. }); };
  110715. break;
  110716. }
  110717. case "CUBICSPLINE" /* CUBICSPLINE */: {
  110718. getNextKey = function (frameIndex) { return ({
  110719. frame: data.input[frameIndex],
  110720. inTangent: getNextOutputValue(),
  110721. value: getNextOutputValue(),
  110722. outTangent: getNextOutputValue()
  110723. }); };
  110724. break;
  110725. }
  110726. }
  110727. var keys = new Array(data.input.length);
  110728. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  110729. keys[frameIndex] = getNextKey(frameIndex);
  110730. }
  110731. if (targetPath === "influence") {
  110732. var _loop_1 = function (targetIndex) {
  110733. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  110734. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  110735. babylonAnimation.setKeys(keys.map(function (key) { return ({
  110736. frame: key.frame,
  110737. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  110738. value: key.value[targetIndex],
  110739. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  110740. }); }));
  110741. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  110742. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  110743. var babylonAnimationClone = babylonAnimation.clone();
  110744. morphTarget.animations.push(babylonAnimationClone);
  110745. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  110746. });
  110747. };
  110748. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  110749. _loop_1(targetIndex);
  110750. }
  110751. }
  110752. else {
  110753. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  110754. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  110755. babylonAnimation.setKeys(keys);
  110756. if (targetNode._babylonBones) {
  110757. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  110758. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  110759. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  110760. babylonAnimationTarget.animations.push(babylonAnimation);
  110761. }
  110762. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  110763. }
  110764. else {
  110765. targetNode._babylonMesh.animations.push(babylonAnimation);
  110766. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  110767. }
  110768. }
  110769. });
  110770. };
  110771. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  110772. if (sampler._data) {
  110773. return sampler._data;
  110774. }
  110775. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  110776. switch (interpolation) {
  110777. case "STEP" /* STEP */:
  110778. case "LINEAR" /* LINEAR */:
  110779. case "CUBICSPLINE" /* CUBICSPLINE */: {
  110780. break;
  110781. }
  110782. default: {
  110783. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  110784. }
  110785. }
  110786. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  110787. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  110788. sampler._data = Promise.all([
  110789. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  110790. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  110791. ]).then(function (_a) {
  110792. var inputData = _a[0], outputData = _a[1];
  110793. return {
  110794. input: inputData,
  110795. interpolation: interpolation,
  110796. output: outputData,
  110797. };
  110798. });
  110799. return sampler._data;
  110800. };
  110801. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  110802. if (buffer._data) {
  110803. return buffer._data;
  110804. }
  110805. if (!buffer.uri) {
  110806. throw new Error(context + ": Uri is missing");
  110807. }
  110808. buffer._data = this._loadUriAsync(context, buffer.uri);
  110809. return buffer._data;
  110810. };
  110811. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  110812. if (bufferView._data) {
  110813. return bufferView._data;
  110814. }
  110815. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  110816. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  110817. try {
  110818. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  110819. }
  110820. catch (e) {
  110821. throw new Error(context + ": " + e.message);
  110822. }
  110823. });
  110824. return bufferView._data;
  110825. };
  110826. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  110827. if (accessor.type !== "SCALAR" /* SCALAR */) {
  110828. throw new Error(context + ": Invalid type " + accessor.type);
  110829. }
  110830. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  110831. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  110832. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  110833. throw new Error(context + ": Invalid component type " + accessor.componentType);
  110834. }
  110835. if (accessor._data) {
  110836. return accessor._data;
  110837. }
  110838. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  110839. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110840. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  110841. });
  110842. return accessor._data;
  110843. };
  110844. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  110845. // TODO: support normalized and stride
  110846. var _this = this;
  110847. if (accessor.componentType !== 5126 /* FLOAT */) {
  110848. throw new Error("Invalid component type " + accessor.componentType);
  110849. }
  110850. if (accessor._data) {
  110851. return accessor._data;
  110852. }
  110853. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  110854. var length = numComponents * accessor.count;
  110855. if (accessor.bufferView == undefined) {
  110856. accessor._data = Promise.resolve(new Float32Array(length));
  110857. }
  110858. else {
  110859. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  110860. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110861. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  110862. });
  110863. }
  110864. if (accessor.sparse) {
  110865. var sparse_1 = accessor.sparse;
  110866. accessor._data = accessor._data.then(function (data) {
  110867. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  110868. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  110869. return Promise.all([
  110870. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  110871. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  110872. ]).then(function (_a) {
  110873. var indicesData = _a[0], valuesData = _a[1];
  110874. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  110875. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  110876. var valuesIndex = 0;
  110877. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  110878. var dataIndex = indices[indicesIndex] * numComponents;
  110879. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  110880. data[dataIndex++] = values[valuesIndex++];
  110881. }
  110882. }
  110883. return data;
  110884. });
  110885. });
  110886. }
  110887. return accessor._data;
  110888. };
  110889. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  110890. var _this = this;
  110891. if (bufferView._babylonBuffer) {
  110892. return bufferView._babylonBuffer;
  110893. }
  110894. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  110895. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  110896. });
  110897. return bufferView._babylonBuffer;
  110898. };
  110899. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  110900. var _this = this;
  110901. if (accessor._babylonVertexBuffer) {
  110902. return accessor._babylonVertexBuffer;
  110903. }
  110904. if (accessor.sparse) {
  110905. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  110906. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  110907. });
  110908. }
  110909. else {
  110910. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  110911. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  110912. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  110913. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  110914. });
  110915. }
  110916. return accessor._babylonVertexBuffer;
  110917. };
  110918. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  110919. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  110920. if (!babylonMaterial) {
  110921. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  110922. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  110923. babylonMaterial.metallic = 1;
  110924. babylonMaterial.roughness = 1;
  110925. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110926. }
  110927. return babylonMaterial;
  110928. };
  110929. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  110930. var promises = new Array();
  110931. // Ensure metallic workflow
  110932. babylonMaterial.metallic = 1;
  110933. babylonMaterial.roughness = 1;
  110934. var properties = material.pbrMetallicRoughness;
  110935. if (properties) {
  110936. if (properties.baseColorFactor) {
  110937. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  110938. babylonMaterial.alpha = properties.baseColorFactor[3];
  110939. }
  110940. else {
  110941. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110942. }
  110943. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  110944. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  110945. if (properties.baseColorTexture) {
  110946. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  110947. babylonMaterial.albedoTexture = texture;
  110948. }));
  110949. }
  110950. if (properties.metallicRoughnessTexture) {
  110951. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  110952. babylonMaterial.metallicTexture = texture;
  110953. }));
  110954. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  110955. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  110956. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  110957. }
  110958. }
  110959. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  110960. return Promise.all(promises).then(function () { });
  110961. };
  110962. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110963. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  110964. if (promise) {
  110965. return promise;
  110966. }
  110967. material._babylonData = material._babylonData || {};
  110968. var babylonData = material._babylonData[babylonDrawMode];
  110969. if (!babylonData) {
  110970. this._parent._logOpen(context + " " + (material.name || ""));
  110971. var name_4 = material.name || "material" + material._index;
  110972. var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);
  110973. babylonData = {
  110974. material: babylonMaterial,
  110975. meshes: [],
  110976. loaded: this._loadMaterialPropertiesAsync(context, material, babylonMaterial)
  110977. };
  110978. material._babylonData[babylonDrawMode] = babylonData;
  110979. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110980. this._parent._logClose();
  110981. }
  110982. babylonData.meshes.push(babylonMesh);
  110983. babylonMesh.onDisposeObservable.addOnce(function () {
  110984. var index = babylonData.meshes.indexOf(babylonMesh);
  110985. if (index !== -1) {
  110986. babylonData.meshes.splice(index, 1);
  110987. }
  110988. });
  110989. assign(babylonData.material);
  110990. return babylonData.loaded;
  110991. };
  110992. GLTFLoader.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  110993. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialPropertiesAsync(this, context, material, babylonMaterial);
  110994. if (promise) {
  110995. return promise;
  110996. }
  110997. var promises = new Array();
  110998. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  110999. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  111000. return Promise.all(promises).then(function () { });
  111001. };
  111002. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  111003. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  111004. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  111005. babylonMaterial.fillMode = drawMode;
  111006. babylonMaterial.enableSpecularAntiAliasing = true;
  111007. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  111008. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  111009. return babylonMaterial;
  111010. };
  111011. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  111012. var promises = new Array();
  111013. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  111014. if (material.doubleSided) {
  111015. babylonMaterial.backFaceCulling = false;
  111016. babylonMaterial.twoSidedLighting = true;
  111017. }
  111018. if (material.normalTexture) {
  111019. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  111020. babylonMaterial.bumpTexture = texture;
  111021. }));
  111022. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  111023. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  111024. if (material.normalTexture.scale != undefined) {
  111025. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  111026. }
  111027. }
  111028. if (material.occlusionTexture) {
  111029. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  111030. babylonMaterial.ambientTexture = texture;
  111031. }));
  111032. babylonMaterial.useAmbientInGrayScale = true;
  111033. if (material.occlusionTexture.strength != undefined) {
  111034. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  111035. }
  111036. }
  111037. if (material.emissiveTexture) {
  111038. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  111039. babylonMaterial.emissiveTexture = texture;
  111040. }));
  111041. }
  111042. return Promise.all(promises).then(function () { });
  111043. };
  111044. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  111045. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  111046. switch (alphaMode) {
  111047. case "OPAQUE" /* OPAQUE */: {
  111048. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  111049. break;
  111050. }
  111051. case "MASK" /* MASK */: {
  111052. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  111053. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  111054. if (babylonMaterial.albedoTexture) {
  111055. babylonMaterial.albedoTexture.hasAlpha = true;
  111056. }
  111057. break;
  111058. }
  111059. case "BLEND" /* BLEND */: {
  111060. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  111061. if (babylonMaterial.albedoTexture) {
  111062. babylonMaterial.albedoTexture.hasAlpha = true;
  111063. babylonMaterial.useAlphaFromAlbedoTexture = true;
  111064. }
  111065. break;
  111066. }
  111067. default: {
  111068. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  111069. }
  111070. }
  111071. };
  111072. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  111073. var _this = this;
  111074. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  111075. if (promise) {
  111076. return promise;
  111077. }
  111078. this._parent._logOpen("" + context);
  111079. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  111080. context = "#/textures/" + textureInfo.index;
  111081. var promises = new Array();
  111082. this._parent._logOpen(context + " " + (texture.name || ""));
  111083. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  111084. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  111085. var deferred = new BABYLON.Deferred();
  111086. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  111087. if (!_this._disposed) {
  111088. deferred.resolve();
  111089. }
  111090. }, function (message, exception) {
  111091. if (!_this._disposed) {
  111092. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  111093. }
  111094. });
  111095. promises.push(deferred.promise);
  111096. babylonTexture.name = texture.name || "texture" + texture._index;
  111097. babylonTexture.wrapU = samplerData.wrapU;
  111098. babylonTexture.wrapV = samplerData.wrapV;
  111099. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  111100. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  111101. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) {
  111102. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  111103. babylonTexture.updateURL(dataUrl, blob);
  111104. }));
  111105. assign(babylonTexture);
  111106. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  111107. this._parent._logClose();
  111108. this._parent._logClose();
  111109. return Promise.all(promises).then(function () { });
  111110. };
  111111. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  111112. if (!sampler._data) {
  111113. sampler._data = {
  111114. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  111115. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  111116. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  111117. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  111118. };
  111119. }
  111120. ;
  111121. return sampler._data;
  111122. };
  111123. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  111124. if (!image._blob) {
  111125. this._parent._logOpen(context + " " + (image.name || ""));
  111126. var promise = void 0;
  111127. if (image.uri) {
  111128. promise = this._loadUriAsync(context, image.uri);
  111129. }
  111130. else {
  111131. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  111132. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  111133. }
  111134. image._blob = promise.then(function (data) {
  111135. return new Blob([data], { type: image.mimeType });
  111136. });
  111137. this._parent._logClose();
  111138. }
  111139. return image._blob;
  111140. };
  111141. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  111142. var _this = this;
  111143. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  111144. if (promise) {
  111145. return promise;
  111146. }
  111147. if (!GLTFLoader._ValidateUri(uri)) {
  111148. throw new Error(context + ": Uri '" + uri + "' is invalid");
  111149. }
  111150. if (BABYLON.Tools.IsBase64(uri)) {
  111151. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  111152. this._parent._log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  111153. return Promise.resolve(data);
  111154. }
  111155. this._parent._log("Loading " + uri);
  111156. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  111157. return new Promise(function (resolve, reject) {
  111158. if (!_this._disposed) {
  111159. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  111160. if (!_this._disposed) {
  111161. var data = new Uint8Array(fileData);
  111162. _this._parent._log("Loaded " + uri + " (" + data.length + " bytes)");
  111163. resolve(data);
  111164. }
  111165. }, function (event) {
  111166. if (!_this._disposed) {
  111167. if (request_1) {
  111168. request_1._lengthComputable = event.lengthComputable;
  111169. request_1._loaded = event.loaded;
  111170. request_1._total = event.total;
  111171. }
  111172. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  111173. try {
  111174. _this._onProgress();
  111175. }
  111176. catch (e) {
  111177. reject(e);
  111178. }
  111179. }
  111180. }
  111181. }, _this._babylonScene.database, true, function (request, exception) {
  111182. if (!_this._disposed) {
  111183. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  111184. }
  111185. });
  111186. _this._requests.push(request_1);
  111187. }
  111188. });
  111189. });
  111190. };
  111191. GLTFLoader.prototype._onProgress = function () {
  111192. if (!this._progressCallback) {
  111193. return;
  111194. }
  111195. var lengthComputable = true;
  111196. var loaded = 0;
  111197. var total = 0;
  111198. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  111199. var request = _a[_i];
  111200. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  111201. return;
  111202. }
  111203. lengthComputable = lengthComputable && request._lengthComputable;
  111204. loaded += request._loaded;
  111205. total += request._total;
  111206. }
  111207. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  111208. };
  111209. GLTFLoader._GetProperty = function (context, array, index) {
  111210. if (!array || index == undefined || !array[index]) {
  111211. throw new Error(context + ": Failed to find index (" + index + ")");
  111212. }
  111213. return array[index];
  111214. };
  111215. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  111216. // Set defaults if undefined
  111217. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  111218. switch (mode) {
  111219. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  111220. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  111221. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  111222. default:
  111223. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  111224. return BABYLON.Texture.WRAP_ADDRESSMODE;
  111225. }
  111226. };
  111227. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  111228. // Set defaults if undefined
  111229. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  111230. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  111231. if (magFilter === 9729 /* LINEAR */) {
  111232. switch (minFilter) {
  111233. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  111234. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  111235. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  111236. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  111237. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  111238. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  111239. default:
  111240. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  111241. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  111242. }
  111243. }
  111244. else {
  111245. if (magFilter !== 9728 /* NEAREST */) {
  111246. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  111247. }
  111248. switch (minFilter) {
  111249. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  111250. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  111251. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  111252. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  111253. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  111254. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  111255. default:
  111256. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  111257. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  111258. }
  111259. }
  111260. };
  111261. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  111262. var buffer = bufferView.buffer;
  111263. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  111264. try {
  111265. switch (componentType) {
  111266. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  111267. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  111268. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  111269. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  111270. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  111271. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  111272. default: throw new Error("Invalid component type " + componentType);
  111273. }
  111274. }
  111275. catch (e) {
  111276. throw new Error(context + ": " + e);
  111277. }
  111278. };
  111279. GLTFLoader._GetNumComponents = function (context, type) {
  111280. switch (type) {
  111281. case "SCALAR": return 1;
  111282. case "VEC2": return 2;
  111283. case "VEC3": return 3;
  111284. case "VEC4": return 4;
  111285. case "MAT2": return 4;
  111286. case "MAT3": return 9;
  111287. case "MAT4": return 16;
  111288. }
  111289. throw new Error(context + ": Invalid type (" + type + ")");
  111290. };
  111291. GLTFLoader._ValidateUri = function (uri) {
  111292. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  111293. };
  111294. GLTFLoader._GetDrawMode = function (context, mode) {
  111295. if (mode == undefined) {
  111296. mode = 4 /* TRIANGLES */;
  111297. }
  111298. switch (mode) {
  111299. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  111300. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  111301. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  111302. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  111303. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  111304. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  111305. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  111306. }
  111307. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  111308. };
  111309. GLTFLoader.prototype._compileMaterialsAsync = function () {
  111310. var _this = this;
  111311. this._parent._startPerformanceCounter("Compile materials");
  111312. var promises = new Array();
  111313. if (this._gltf.materials) {
  111314. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  111315. var material = _a[_i];
  111316. if (material._babylonData) {
  111317. for (var babylonDrawMode in material._babylonData) {
  111318. var babylonData = material._babylonData[babylonDrawMode];
  111319. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  111320. var babylonMesh = _c[_b];
  111321. // Ensure nonUniformScaling is set if necessary.
  111322. babylonMesh.computeWorldMatrix(true);
  111323. var babylonMaterial = babylonData.material;
  111324. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  111325. if (this._parent.useClipPlane) {
  111326. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  111327. }
  111328. }
  111329. }
  111330. }
  111331. }
  111332. }
  111333. return Promise.all(promises).then(function () {
  111334. _this._parent._endPerformanceCounter("Compile materials");
  111335. });
  111336. };
  111337. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  111338. var _this = this;
  111339. this._parent._startPerformanceCounter("Compile shadow generators");
  111340. var promises = new Array();
  111341. var lights = this._babylonScene.lights;
  111342. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  111343. var light = lights_1[_i];
  111344. var generator = light.getShadowGenerator();
  111345. if (generator) {
  111346. promises.push(generator.forceCompilationAsync());
  111347. }
  111348. }
  111349. return Promise.all(promises).then(function () {
  111350. _this._parent._endPerformanceCounter("Compile shadow generators");
  111351. });
  111352. };
  111353. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  111354. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  111355. var name_5 = _a[_i];
  111356. var extension = this._extensions[name_5];
  111357. if (extension.enabled) {
  111358. var promise = actionAsync(extension);
  111359. if (promise) {
  111360. return promise;
  111361. }
  111362. }
  111363. }
  111364. return null;
  111365. };
  111366. GLTFLoader._ExtensionNames = new Array();
  111367. GLTFLoader._ExtensionFactories = {};
  111368. return GLTFLoader;
  111369. }());
  111370. GLTF2.GLTFLoader = GLTFLoader;
  111371. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  111372. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111373. })(BABYLON || (BABYLON = {}));
  111374. //# sourceMappingURL=babylon.glTFLoader.js.map
  111375. var BABYLON;
  111376. (function (BABYLON) {
  111377. var GLTF2;
  111378. (function (GLTF2) {
  111379. /**
  111380. * Abstract class that can be implemented to extend existing glTF loader behavior.
  111381. */
  111382. var GLTFLoaderExtension = /** @class */ (function () {
  111383. /**
  111384. * Creates new GLTFLoaderExtension
  111385. * @param loader defines the GLTFLoader to use
  111386. */
  111387. function GLTFLoaderExtension(loader) {
  111388. /**
  111389. * Gets or sets a boolean indicating if the extension is enabled
  111390. */
  111391. this.enabled = true;
  111392. this._loader = loader;
  111393. }
  111394. /**
  111395. * Release all resources
  111396. */
  111397. GLTFLoaderExtension.prototype.dispose = function () {
  111398. delete this._loader;
  111399. };
  111400. // #region Overridable Methods
  111401. /**
  111402. * Override this method to modify the default behavior for loading scenes.
  111403. * @hidden
  111404. */
  111405. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  111406. /**
  111407. * Override this method to modify the default behavior for loading nodes.
  111408. * @hidden
  111409. */
  111410. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  111411. /**
  111412. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  111413. * @hidden
  111414. */
  111415. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  111416. /**
  111417. * Override this method to modify the default behavior for loading materials.
  111418. * @hidden
  111419. */
  111420. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  111421. /**
  111422. * Override this method to modify the default behavior for loading material properties.
  111423. * @hidden
  111424. */
  111425. GLTFLoaderExtension.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { return null; };
  111426. /**
  111427. * Override this method to modify the default behavior for loading textures.
  111428. * @hidden
  111429. */
  111430. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  111431. /**
  111432. * Override this method to modify the default behavior for loading uris.
  111433. * @hidden
  111434. */
  111435. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  111436. // #endregion
  111437. /**
  111438. * Helper method called by a loader extension to load an glTF extension.
  111439. * @hidden
  111440. */
  111441. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  111442. if (!property.extensions) {
  111443. return null;
  111444. }
  111445. var extensions = property.extensions;
  111446. var extension = extensions[this.name];
  111447. if (!extension) {
  111448. return null;
  111449. }
  111450. // Clear out the extension before executing the action to avoid infinite recursion.
  111451. delete extensions[this.name];
  111452. try {
  111453. return actionAsync(context + "/extensions/" + this.name, extension);
  111454. }
  111455. finally {
  111456. // Restore the extension after executing the action.
  111457. extensions[this.name] = extension;
  111458. }
  111459. };
  111460. /**
  111461. * Helper method called by the loader to allow extensions to override loading scenes.
  111462. * @hidden
  111463. */
  111464. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  111465. if (!property.extras) {
  111466. return null;
  111467. }
  111468. var extras = property.extras;
  111469. var value = extras[this.name];
  111470. if (value === undefined) {
  111471. return null;
  111472. }
  111473. // Clear out the extras value before executing the action to avoid infinite recursion.
  111474. delete extras[this.name];
  111475. try {
  111476. return actionAsync(context + "/extras/" + this.name, value);
  111477. }
  111478. finally {
  111479. // Restore the extras value after executing the action.
  111480. extras[this.name] = value;
  111481. }
  111482. };
  111483. /**
  111484. * Helper method called by the loader to allow extensions to override loading scenes.
  111485. * @hidden
  111486. */
  111487. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  111488. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  111489. };
  111490. /**
  111491. * Helper method called by the loader to allow extensions to override loading nodes.
  111492. * @hidden
  111493. */
  111494. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  111495. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  111496. };
  111497. /**
  111498. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  111499. * @hidden
  111500. */
  111501. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  111502. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  111503. };
  111504. /**
  111505. * Helper method called by the loader to allow extensions to override loading materials.
  111506. * @hidden
  111507. */
  111508. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111509. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  111510. };
  111511. /**
  111512. * Helper method called by the loader to allow extensions to override loading material properties.
  111513. * @hidden
  111514. */
  111515. GLTFLoaderExtension._LoadMaterialPropertiesAsync = function (loader, context, material, babylonMaterial) {
  111516. return loader._applyExtensions(function (extension) { return extension._loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  111517. };
  111518. /**
  111519. * Helper method called by the loader to allow extensions to override loading textures.
  111520. * @hidden
  111521. */
  111522. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  111523. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  111524. };
  111525. /**
  111526. * Helper method called by the loader to allow extensions to override loading uris.
  111527. * @hidden
  111528. */
  111529. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  111530. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  111531. };
  111532. return GLTFLoaderExtension;
  111533. }());
  111534. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  111535. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111536. })(BABYLON || (BABYLON = {}));
  111537. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  111538. var BABYLON;
  111539. (function (BABYLON) {
  111540. var GLTF2;
  111541. (function (GLTF2) {
  111542. var Extensions;
  111543. (function (Extensions) {
  111544. var NAME = "MSFT_lod";
  111545. /**
  111546. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  111547. */
  111548. var MSFT_lod = /** @class */ (function (_super) {
  111549. __extends(MSFT_lod, _super);
  111550. function MSFT_lod(loader) {
  111551. var _this = _super.call(this, loader) || this;
  111552. _this.name = NAME;
  111553. /**
  111554. * Maximum number of LODs to load, starting from the lowest LOD.
  111555. */
  111556. _this.maxLODsToLoad = Number.MAX_VALUE;
  111557. /**
  111558. * Observable raised when all node LODs of one level are loaded.
  111559. * The event data is the index of the loaded LOD starting from zero.
  111560. * Dispose the loader to cancel the loading of the next level of LODs.
  111561. */
  111562. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  111563. /**
  111564. * Observable raised when all material LODs of one level are loaded.
  111565. * The event data is the index of the loaded LOD starting from zero.
  111566. * Dispose the loader to cancel the loading of the next level of LODs.
  111567. */
  111568. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  111569. _this._nodeIndexLOD = null;
  111570. _this._nodeSignalLODs = new Array();
  111571. _this._nodePromiseLODs = new Array();
  111572. _this._materialIndexLOD = null;
  111573. _this._materialSignalLODs = new Array();
  111574. _this._materialPromiseLODs = new Array();
  111575. _this._loader._readyPromise.then(function () {
  111576. var _loop_1 = function (indexLOD) {
  111577. var promise = Promise.all(_this._nodePromiseLODs[indexLOD]).then(function () {
  111578. if (indexLOD !== 0) {
  111579. _this._loader._parent._endPerformanceCounter("Node LOD " + indexLOD);
  111580. }
  111581. _this._loader._parent._log("Loaded node LOD " + indexLOD);
  111582. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  111583. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  111584. _this._loader._parent._startPerformanceCounter("Node LOD " + (indexLOD + 1));
  111585. _this._nodeSignalLODs[indexLOD].resolve();
  111586. }
  111587. });
  111588. _this._loader._completePromises.push(promise);
  111589. };
  111590. for (var indexLOD = 0; indexLOD < _this._nodePromiseLODs.length; indexLOD++) {
  111591. _loop_1(indexLOD);
  111592. }
  111593. var _loop_2 = function (indexLOD) {
  111594. var promise = Promise.all(_this._materialPromiseLODs[indexLOD]).then(function () {
  111595. if (indexLOD !== 0) {
  111596. _this._loader._parent._endPerformanceCounter("Material LOD " + indexLOD);
  111597. }
  111598. _this._loader._parent._log("Loaded material LOD " + indexLOD);
  111599. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  111600. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  111601. _this._loader._parent._startPerformanceCounter("Material LOD " + (indexLOD + 1));
  111602. _this._materialSignalLODs[indexLOD].resolve();
  111603. }
  111604. });
  111605. _this._loader._completePromises.push(promise);
  111606. };
  111607. for (var indexLOD = 0; indexLOD < _this._materialPromiseLODs.length; indexLOD++) {
  111608. _loop_2(indexLOD);
  111609. }
  111610. });
  111611. return _this;
  111612. }
  111613. MSFT_lod.prototype.dispose = function () {
  111614. _super.prototype.dispose.call(this);
  111615. this._nodeIndexLOD = null;
  111616. this._nodeSignalLODs.length = 0;
  111617. this._nodePromiseLODs.length = 0;
  111618. this._materialIndexLOD = null;
  111619. this._materialSignalLODs.length = 0;
  111620. this._materialPromiseLODs.length = 0;
  111621. this.onMaterialLODsLoadedObservable.clear();
  111622. this.onNodeLODsLoadedObservable.clear();
  111623. };
  111624. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  111625. var _this = this;
  111626. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  111627. var firstPromise;
  111628. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  111629. _this._loader._parent._logOpen("" + extensionContext);
  111630. var _loop_3 = function (indexLOD) {
  111631. var nodeLOD = nodeLODs[indexLOD];
  111632. if (indexLOD !== 0) {
  111633. _this._nodeIndexLOD = indexLOD;
  111634. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  111635. }
  111636. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  111637. if (indexLOD !== 0) {
  111638. var previousNodeLOD = nodeLODs[indexLOD - 1];
  111639. if (previousNodeLOD._babylonMesh) {
  111640. previousNodeLOD._babylonMesh.dispose();
  111641. delete previousNodeLOD._babylonMesh;
  111642. _this._disposeUnusedMaterials();
  111643. }
  111644. }
  111645. });
  111646. if (indexLOD === 0) {
  111647. firstPromise = promise;
  111648. }
  111649. else {
  111650. _this._nodeIndexLOD = null;
  111651. }
  111652. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  111653. _this._nodePromiseLODs[indexLOD].push(promise);
  111654. };
  111655. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  111656. _loop_3(indexLOD);
  111657. }
  111658. _this._loader._parent._logClose();
  111659. return firstPromise;
  111660. });
  111661. };
  111662. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111663. var _this = this;
  111664. // Don't load material LODs if already loading a node LOD.
  111665. if (this._nodeIndexLOD) {
  111666. return null;
  111667. }
  111668. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  111669. var firstPromise;
  111670. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  111671. _this._loader._parent._logOpen("" + extensionContext);
  111672. var _loop_4 = function (indexLOD) {
  111673. var materialLOD = materialLODs[indexLOD];
  111674. if (indexLOD !== 0) {
  111675. _this._materialIndexLOD = indexLOD;
  111676. }
  111677. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  111678. if (indexLOD !== 0) {
  111679. var babylonDataLOD = materialLOD._babylonData;
  111680. assign(babylonDataLOD[babylonDrawMode].material);
  111681. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  111682. if (previousBabylonDataLOD[babylonDrawMode]) {
  111683. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  111684. delete previousBabylonDataLOD[babylonDrawMode];
  111685. }
  111686. }
  111687. });
  111688. if (indexLOD === 0) {
  111689. firstPromise = promise;
  111690. }
  111691. else {
  111692. _this._materialIndexLOD = null;
  111693. }
  111694. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  111695. _this._materialPromiseLODs[indexLOD].push(promise);
  111696. };
  111697. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  111698. _loop_4(indexLOD);
  111699. }
  111700. _this._loader._parent._logClose();
  111701. return firstPromise;
  111702. });
  111703. };
  111704. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  111705. var _this = this;
  111706. // Defer the loading of uris if loading a material or node LOD.
  111707. if (this._materialIndexLOD !== null) {
  111708. this._loader._parent._log("deferred");
  111709. var previousIndexLOD = this._materialIndexLOD - 1;
  111710. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  111711. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  111712. return _this._loader._loadUriAsync(context, uri);
  111713. });
  111714. }
  111715. else if (this._nodeIndexLOD !== null) {
  111716. this._loader._parent._log("deferred");
  111717. var previousIndexLOD = this._nodeIndexLOD - 1;
  111718. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  111719. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  111720. return _this._loader._loadUriAsync(context, uri);
  111721. });
  111722. }
  111723. return null;
  111724. };
  111725. /**
  111726. * Gets an array of LOD properties from lowest to highest.
  111727. */
  111728. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  111729. if (this.maxLODsToLoad <= 0) {
  111730. throw new Error("maxLODsToLoad must be greater than zero");
  111731. }
  111732. var properties = new Array();
  111733. for (var i = ids.length - 1; i >= 0; i--) {
  111734. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  111735. if (properties.length === this.maxLODsToLoad) {
  111736. return properties;
  111737. }
  111738. }
  111739. properties.push(property);
  111740. return properties;
  111741. };
  111742. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  111743. var materials = this._loader._gltf.materials;
  111744. if (materials) {
  111745. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  111746. var material = materials_1[_i];
  111747. if (material._babylonData) {
  111748. for (var drawMode in material._babylonData) {
  111749. var babylonData = material._babylonData[drawMode];
  111750. if (babylonData.meshes.length === 0) {
  111751. babylonData.material.dispose(false, true);
  111752. delete material._babylonData[drawMode];
  111753. }
  111754. }
  111755. }
  111756. }
  111757. }
  111758. };
  111759. return MSFT_lod;
  111760. }(GLTF2.GLTFLoaderExtension));
  111761. Extensions.MSFT_lod = MSFT_lod;
  111762. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  111763. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111764. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111765. })(BABYLON || (BABYLON = {}));
  111766. //# sourceMappingURL=MSFT_lod.js.map
  111767. var BABYLON;
  111768. (function (BABYLON) {
  111769. var GLTF2;
  111770. (function (GLTF2) {
  111771. var Extensions;
  111772. (function (Extensions) {
  111773. var NAME = "MSFT_minecraftMesh";
  111774. /** @hidden */
  111775. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  111776. __extends(MSFT_minecraftMesh, _super);
  111777. function MSFT_minecraftMesh() {
  111778. var _this = _super !== null && _super.apply(this, arguments) || this;
  111779. _this.name = NAME;
  111780. return _this;
  111781. }
  111782. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111783. var _this = this;
  111784. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  111785. if (value) {
  111786. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  111787. if (babylonMaterial.needAlphaBlending()) {
  111788. babylonMaterial.forceDepthWrite = true;
  111789. babylonMaterial.separateCullingPass = true;
  111790. }
  111791. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  111792. babylonMaterial.twoSidedLighting = true;
  111793. assign(babylonMaterial);
  111794. });
  111795. }
  111796. return null;
  111797. });
  111798. };
  111799. return MSFT_minecraftMesh;
  111800. }(GLTF2.GLTFLoaderExtension));
  111801. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  111802. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  111803. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111804. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111805. })(BABYLON || (BABYLON = {}));
  111806. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  111807. var BABYLON;
  111808. (function (BABYLON) {
  111809. var GLTF2;
  111810. (function (GLTF2) {
  111811. var Extensions;
  111812. (function (Extensions) {
  111813. var NAME = "MSFT_sRGBFactors";
  111814. /** @hidden */
  111815. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  111816. __extends(MSFT_sRGBFactors, _super);
  111817. function MSFT_sRGBFactors() {
  111818. var _this = _super !== null && _super.apply(this, arguments) || this;
  111819. _this.name = NAME;
  111820. return _this;
  111821. }
  111822. MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111823. var _this = this;
  111824. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  111825. if (value) {
  111826. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  111827. if (!babylonMaterial.albedoTexture) {
  111828. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  111829. }
  111830. if (!babylonMaterial.reflectivityTexture) {
  111831. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  111832. }
  111833. assign(babylonMaterial);
  111834. });
  111835. }
  111836. return null;
  111837. });
  111838. };
  111839. return MSFT_sRGBFactors;
  111840. }(GLTF2.GLTFLoaderExtension));
  111841. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  111842. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  111843. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111844. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111845. })(BABYLON || (BABYLON = {}));
  111846. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  111847. var BABYLON;
  111848. (function (BABYLON) {
  111849. var GLTF2;
  111850. (function (GLTF2) {
  111851. var Extensions;
  111852. (function (Extensions) {
  111853. var NAME = "KHR_draco_mesh_compression";
  111854. /**
  111855. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  111856. */
  111857. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  111858. __extends(KHR_draco_mesh_compression, _super);
  111859. function KHR_draco_mesh_compression(loader) {
  111860. var _this = _super.call(this, loader) || this;
  111861. _this.name = NAME;
  111862. _this._dracoCompression = null;
  111863. // Disable extension if decoder is not available.
  111864. if (!BABYLON.DracoCompression.DecoderAvailable) {
  111865. _this.enabled = false;
  111866. }
  111867. return _this;
  111868. }
  111869. KHR_draco_mesh_compression.prototype.dispose = function () {
  111870. if (this._dracoCompression) {
  111871. this._dracoCompression.dispose();
  111872. }
  111873. _super.prototype.dispose.call(this);
  111874. };
  111875. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  111876. var _this = this;
  111877. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  111878. if (primitive.mode != undefined) {
  111879. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  111880. primitive.mode !== 4 /* TRIANGLES */) {
  111881. throw new Error(context + ": Unsupported mode " + primitive.mode);
  111882. }
  111883. // TODO: handle triangle strips
  111884. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  111885. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  111886. }
  111887. }
  111888. var attributes = {};
  111889. var loadAttribute = function (name, kind) {
  111890. var uniqueId = extension.attributes[name];
  111891. if (uniqueId == undefined) {
  111892. return;
  111893. }
  111894. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  111895. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  111896. babylonMesh._delayInfo.push(kind);
  111897. }
  111898. attributes[kind] = uniqueId;
  111899. };
  111900. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  111901. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  111902. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  111903. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  111904. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  111905. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  111906. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  111907. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  111908. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  111909. if (!bufferView._dracoBabylonGeometry) {
  111910. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  111911. if (!_this._dracoCompression) {
  111912. _this._dracoCompression = new BABYLON.DracoCompression();
  111913. }
  111914. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  111915. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  111916. babylonVertexData.applyToGeometry(babylonGeometry);
  111917. return babylonGeometry;
  111918. }).catch(function (error) {
  111919. throw new Error(context + ": " + error.message);
  111920. });
  111921. });
  111922. }
  111923. return bufferView._dracoBabylonGeometry;
  111924. });
  111925. };
  111926. return KHR_draco_mesh_compression;
  111927. }(GLTF2.GLTFLoaderExtension));
  111928. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  111929. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  111930. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111931. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111932. })(BABYLON || (BABYLON = {}));
  111933. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  111934. var BABYLON;
  111935. (function (BABYLON) {
  111936. var GLTF2;
  111937. (function (GLTF2) {
  111938. var Extensions;
  111939. (function (Extensions) {
  111940. var NAME = "KHR_materials_pbrSpecularGlossiness";
  111941. /**
  111942. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  111943. */
  111944. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  111945. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  111946. function KHR_materials_pbrSpecularGlossiness() {
  111947. var _this = _super !== null && _super.apply(this, arguments) || this;
  111948. _this.name = NAME;
  111949. return _this;
  111950. }
  111951. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  111952. var _this = this;
  111953. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  111954. var promises = new Array();
  111955. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  111956. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  111957. return Promise.all(promises).then(function () { });
  111958. });
  111959. };
  111960. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  111961. var promises = new Array();
  111962. if (properties.diffuseFactor) {
  111963. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  111964. babylonMaterial.alpha = properties.diffuseFactor[3];
  111965. }
  111966. else {
  111967. babylonMaterial.albedoColor = BABYLON.Color3.White();
  111968. }
  111969. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  111970. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  111971. if (properties.diffuseTexture) {
  111972. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  111973. babylonMaterial.albedoTexture = texture;
  111974. }));
  111975. }
  111976. if (properties.specularGlossinessTexture) {
  111977. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  111978. babylonMaterial.reflectivityTexture = texture;
  111979. }));
  111980. babylonMaterial.reflectivityTexture.hasAlpha = true;
  111981. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  111982. }
  111983. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  111984. return Promise.all(promises).then(function () { });
  111985. };
  111986. return KHR_materials_pbrSpecularGlossiness;
  111987. }(GLTF2.GLTFLoaderExtension));
  111988. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  111989. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  111990. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111991. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111992. })(BABYLON || (BABYLON = {}));
  111993. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  111994. var BABYLON;
  111995. (function (BABYLON) {
  111996. var GLTF2;
  111997. (function (GLTF2) {
  111998. var Extensions;
  111999. (function (Extensions) {
  112000. var NAME = "KHR_materials_unlit";
  112001. /**
  112002. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  112003. */
  112004. var KHR_materials_unlit = /** @class */ (function (_super) {
  112005. __extends(KHR_materials_unlit, _super);
  112006. function KHR_materials_unlit() {
  112007. var _this = _super !== null && _super.apply(this, arguments) || this;
  112008. _this.name = NAME;
  112009. return _this;
  112010. }
  112011. KHR_materials_unlit.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  112012. var _this = this;
  112013. return this._loadExtensionAsync(context, material, function () {
  112014. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  112015. });
  112016. };
  112017. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  112018. var promises = new Array();
  112019. babylonMaterial.unlit = true;
  112020. // Ensure metallic workflow
  112021. babylonMaterial.metallic = 1;
  112022. babylonMaterial.roughness = 1;
  112023. var properties = material.pbrMetallicRoughness;
  112024. if (properties) {
  112025. if (properties.baseColorFactor) {
  112026. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  112027. babylonMaterial.alpha = properties.baseColorFactor[3];
  112028. }
  112029. else {
  112030. babylonMaterial.albedoColor = BABYLON.Color3.White();
  112031. }
  112032. if (properties.baseColorTexture) {
  112033. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  112034. babylonMaterial.albedoTexture = texture;
  112035. }));
  112036. }
  112037. }
  112038. if (material.doubleSided) {
  112039. babylonMaterial.backFaceCulling = false;
  112040. babylonMaterial.twoSidedLighting = true;
  112041. }
  112042. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  112043. return Promise.all(promises).then(function () { });
  112044. };
  112045. return KHR_materials_unlit;
  112046. }(GLTF2.GLTFLoaderExtension));
  112047. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  112048. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  112049. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112050. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112051. })(BABYLON || (BABYLON = {}));
  112052. //# sourceMappingURL=KHR_materials_unlit.js.map
  112053. var BABYLON;
  112054. (function (BABYLON) {
  112055. var GLTF2;
  112056. (function (GLTF2) {
  112057. var Extensions;
  112058. (function (Extensions) {
  112059. var NAME = "KHR_lights";
  112060. var LightType;
  112061. (function (LightType) {
  112062. LightType["AMBIENT"] = "ambient";
  112063. LightType["DIRECTIONAL"] = "directional";
  112064. LightType["POINT"] = "point";
  112065. LightType["SPOT"] = "spot";
  112066. })(LightType || (LightType = {}));
  112067. /**
  112068. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  112069. */
  112070. var KHR_lights = /** @class */ (function (_super) {
  112071. __extends(KHR_lights, _super);
  112072. function KHR_lights() {
  112073. var _this = _super !== null && _super.apply(this, arguments) || this;
  112074. _this.name = NAME;
  112075. return _this;
  112076. }
  112077. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  112078. var _this = this;
  112079. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  112080. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  112081. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  112082. if (light.type !== LightType.AMBIENT) {
  112083. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  112084. }
  112085. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  112086. return promise;
  112087. });
  112088. };
  112089. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  112090. var _this = this;
  112091. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  112092. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  112093. var babylonLight;
  112094. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  112095. var name = node._babylonMesh.name;
  112096. switch (light.type) {
  112097. case LightType.AMBIENT: {
  112098. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  112099. }
  112100. case LightType.DIRECTIONAL: {
  112101. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  112102. break;
  112103. }
  112104. case LightType.POINT: {
  112105. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  112106. break;
  112107. }
  112108. case LightType.SPOT: {
  112109. var spotLight = light;
  112110. // TODO: support inner and outer cone angles
  112111. //const innerConeAngle = spotLight.innerConeAngle || 0;
  112112. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  112113. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  112114. break;
  112115. }
  112116. default: {
  112117. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  112118. }
  112119. }
  112120. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  112121. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  112122. babylonLight.parent = node._babylonMesh;
  112123. return promise;
  112124. });
  112125. };
  112126. Object.defineProperty(KHR_lights.prototype, "_lights", {
  112127. get: function () {
  112128. var extensions = this._loader._gltf.extensions;
  112129. if (!extensions || !extensions[this.name]) {
  112130. throw new Error("#/extensions: '" + this.name + "' not found");
  112131. }
  112132. var extension = extensions[this.name];
  112133. return extension.lights;
  112134. },
  112135. enumerable: true,
  112136. configurable: true
  112137. });
  112138. return KHR_lights;
  112139. }(GLTF2.GLTFLoaderExtension));
  112140. Extensions.KHR_lights = KHR_lights;
  112141. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  112142. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112143. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112144. })(BABYLON || (BABYLON = {}));
  112145. var BABYLON;
  112146. (function (BABYLON) {
  112147. var GLTF2;
  112148. (function (GLTF2) {
  112149. var Extensions;
  112150. (function (Extensions) {
  112151. var NAME = "KHR_texture_transform";
  112152. /**
  112153. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  112154. */
  112155. var KHR_texture_transform = /** @class */ (function (_super) {
  112156. __extends(KHR_texture_transform, _super);
  112157. function KHR_texture_transform() {
  112158. var _this = _super !== null && _super.apply(this, arguments) || this;
  112159. _this.name = NAME;
  112160. return _this;
  112161. }
  112162. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  112163. var _this = this;
  112164. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  112165. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  112166. if (extension.offset) {
  112167. babylonTexture.uOffset = extension.offset[0];
  112168. babylonTexture.vOffset = extension.offset[1];
  112169. }
  112170. // Always rotate around the origin.
  112171. babylonTexture.uRotationCenter = 0;
  112172. babylonTexture.vRotationCenter = 0;
  112173. if (extension.rotation) {
  112174. babylonTexture.wAng = -extension.rotation;
  112175. }
  112176. if (extension.scale) {
  112177. babylonTexture.uScale = extension.scale[0];
  112178. babylonTexture.vScale = extension.scale[1];
  112179. }
  112180. if (extension.texCoord != undefined) {
  112181. babylonTexture.coordinatesIndex = extension.texCoord;
  112182. }
  112183. assign(babylonTexture);
  112184. });
  112185. });
  112186. };
  112187. return KHR_texture_transform;
  112188. }(GLTF2.GLTFLoaderExtension));
  112189. Extensions.KHR_texture_transform = KHR_texture_transform;
  112190. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  112191. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  112192. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  112193. })(BABYLON || (BABYLON = {}));
  112194. return BABYLON;
  112195. });
  112196. /***/ }),
  112197. /* 15 */
  112198. /***/ (function(module, exports, __webpack_require__) {
  112199. /**!
  112200. @license
  112201. handlebars v4.0.11
  112202. Copyright (C) 2011-2017 by Yehuda Katz
  112203. Permission is hereby granted, free of charge, to any person obtaining a copy
  112204. of this software and associated documentation files (the "Software"), to deal
  112205. in the Software without restriction, including without limitation the rights
  112206. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  112207. copies of the Software, and to permit persons to whom the Software is
  112208. furnished to do so, subject to the following conditions:
  112209. The above copyright notice and this permission notice shall be included in
  112210. all copies or substantial portions of the Software.
  112211. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  112212. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  112213. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  112214. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  112215. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  112216. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  112217. THE SOFTWARE.
  112218. */
  112219. (function webpackUniversalModuleDefinition(root, factory) {
  112220. if(true)
  112221. module.exports = factory();
  112222. else if(typeof define === 'function' && define.amd)
  112223. define([], factory);
  112224. else if(typeof exports === 'object')
  112225. exports["Handlebars"] = factory();
  112226. else
  112227. root["Handlebars"] = factory();
  112228. })(this, function() {
  112229. return /******/ (function(modules) { // webpackBootstrap
  112230. /******/ // The module cache
  112231. /******/ var installedModules = {};
  112232. /******/ // The require function
  112233. /******/ function __webpack_require__(moduleId) {
  112234. /******/ // Check if module is in cache
  112235. /******/ if(installedModules[moduleId])
  112236. /******/ return installedModules[moduleId].exports;
  112237. /******/ // Create a new module (and put it into the cache)
  112238. /******/ var module = installedModules[moduleId] = {
  112239. /******/ exports: {},
  112240. /******/ id: moduleId,
  112241. /******/ loaded: false
  112242. /******/ };
  112243. /******/ // Execute the module function
  112244. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  112245. /******/ // Flag the module as loaded
  112246. /******/ module.loaded = true;
  112247. /******/ // Return the exports of the module
  112248. /******/ return module.exports;
  112249. /******/ }
  112250. /******/ // expose the modules object (__webpack_modules__)
  112251. /******/ __webpack_require__.m = modules;
  112252. /******/ // expose the module cache
  112253. /******/ __webpack_require__.c = installedModules;
  112254. /******/ // __webpack_public_path__
  112255. /******/ __webpack_require__.p = "";
  112256. /******/ // Load entry module and return exports
  112257. /******/ return __webpack_require__(0);
  112258. /******/ })
  112259. /************************************************************************/
  112260. /******/ ([
  112261. /* 0 */
  112262. /***/ (function(module, exports, __webpack_require__) {
  112263. 'use strict';
  112264. var _interopRequireDefault = __webpack_require__(1)['default'];
  112265. exports.__esModule = true;
  112266. var _handlebarsRuntime = __webpack_require__(2);
  112267. var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);
  112268. // Compiler imports
  112269. var _handlebarsCompilerAst = __webpack_require__(35);
  112270. var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);
  112271. var _handlebarsCompilerBase = __webpack_require__(36);
  112272. var _handlebarsCompilerCompiler = __webpack_require__(41);
  112273. var _handlebarsCompilerJavascriptCompiler = __webpack_require__(42);
  112274. var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);
  112275. var _handlebarsCompilerVisitor = __webpack_require__(39);
  112276. var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);
  112277. var _handlebarsNoConflict = __webpack_require__(34);
  112278. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  112279. var _create = _handlebarsRuntime2['default'].create;
  112280. function create() {
  112281. var hb = _create();
  112282. hb.compile = function (input, options) {
  112283. return _handlebarsCompilerCompiler.compile(input, options, hb);
  112284. };
  112285. hb.precompile = function (input, options) {
  112286. return _handlebarsCompilerCompiler.precompile(input, options, hb);
  112287. };
  112288. hb.AST = _handlebarsCompilerAst2['default'];
  112289. hb.Compiler = _handlebarsCompilerCompiler.Compiler;
  112290. hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default'];
  112291. hb.Parser = _handlebarsCompilerBase.parser;
  112292. hb.parse = _handlebarsCompilerBase.parse;
  112293. return hb;
  112294. }
  112295. var inst = create();
  112296. inst.create = create;
  112297. _handlebarsNoConflict2['default'](inst);
  112298. inst.Visitor = _handlebarsCompilerVisitor2['default'];
  112299. inst['default'] = inst;
  112300. exports['default'] = inst;
  112301. module.exports = exports['default'];
  112302. /***/ }),
  112303. /* 1 */
  112304. /***/ (function(module, exports) {
  112305. "use strict";
  112306. exports["default"] = function (obj) {
  112307. return obj && obj.__esModule ? obj : {
  112308. "default": obj
  112309. };
  112310. };
  112311. exports.__esModule = true;
  112312. /***/ }),
  112313. /* 2 */
  112314. /***/ (function(module, exports, __webpack_require__) {
  112315. 'use strict';
  112316. var _interopRequireWildcard = __webpack_require__(3)['default'];
  112317. var _interopRequireDefault = __webpack_require__(1)['default'];
  112318. exports.__esModule = true;
  112319. var _handlebarsBase = __webpack_require__(4);
  112320. var base = _interopRequireWildcard(_handlebarsBase);
  112321. // Each of these augment the Handlebars object. No need to setup here.
  112322. // (This is done to easily share code between commonjs and browse envs)
  112323. var _handlebarsSafeString = __webpack_require__(21);
  112324. var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
  112325. var _handlebarsException = __webpack_require__(6);
  112326. var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
  112327. var _handlebarsUtils = __webpack_require__(5);
  112328. var Utils = _interopRequireWildcard(_handlebarsUtils);
  112329. var _handlebarsRuntime = __webpack_require__(22);
  112330. var runtime = _interopRequireWildcard(_handlebarsRuntime);
  112331. var _handlebarsNoConflict = __webpack_require__(34);
  112332. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  112333. // For compatibility and usage outside of module systems, make the Handlebars object a namespace
  112334. function create() {
  112335. var hb = new base.HandlebarsEnvironment();
  112336. Utils.extend(hb, base);
  112337. hb.SafeString = _handlebarsSafeString2['default'];
  112338. hb.Exception = _handlebarsException2['default'];
  112339. hb.Utils = Utils;
  112340. hb.escapeExpression = Utils.escapeExpression;
  112341. hb.VM = runtime;
  112342. hb.template = function (spec) {
  112343. return runtime.template(spec, hb);
  112344. };
  112345. return hb;
  112346. }
  112347. var inst = create();
  112348. inst.create = create;
  112349. _handlebarsNoConflict2['default'](inst);
  112350. inst['default'] = inst;
  112351. exports['default'] = inst;
  112352. module.exports = exports['default'];
  112353. /***/ }),
  112354. /* 3 */
  112355. /***/ (function(module, exports) {
  112356. "use strict";
  112357. exports["default"] = function (obj) {
  112358. if (obj && obj.__esModule) {
  112359. return obj;
  112360. } else {
  112361. var newObj = {};
  112362. if (obj != null) {
  112363. for (var key in obj) {
  112364. if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
  112365. }
  112366. }
  112367. newObj["default"] = obj;
  112368. return newObj;
  112369. }
  112370. };
  112371. exports.__esModule = true;
  112372. /***/ }),
  112373. /* 4 */
  112374. /***/ (function(module, exports, __webpack_require__) {
  112375. 'use strict';
  112376. var _interopRequireDefault = __webpack_require__(1)['default'];
  112377. exports.__esModule = true;
  112378. exports.HandlebarsEnvironment = HandlebarsEnvironment;
  112379. var _utils = __webpack_require__(5);
  112380. var _exception = __webpack_require__(6);
  112381. var _exception2 = _interopRequireDefault(_exception);
  112382. var _helpers = __webpack_require__(10);
  112383. var _decorators = __webpack_require__(18);
  112384. var _logger = __webpack_require__(20);
  112385. var _logger2 = _interopRequireDefault(_logger);
  112386. var VERSION = '4.0.11';
  112387. exports.VERSION = VERSION;
  112388. var COMPILER_REVISION = 7;
  112389. exports.COMPILER_REVISION = COMPILER_REVISION;
  112390. var REVISION_CHANGES = {
  112391. 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
  112392. 2: '== 1.0.0-rc.3',
  112393. 3: '== 1.0.0-rc.4',
  112394. 4: '== 1.x.x',
  112395. 5: '== 2.0.0-alpha.x',
  112396. 6: '>= 2.0.0-beta.1',
  112397. 7: '>= 4.0.0'
  112398. };
  112399. exports.REVISION_CHANGES = REVISION_CHANGES;
  112400. var objectType = '[object Object]';
  112401. function HandlebarsEnvironment(helpers, partials, decorators) {
  112402. this.helpers = helpers || {};
  112403. this.partials = partials || {};
  112404. this.decorators = decorators || {};
  112405. _helpers.registerDefaultHelpers(this);
  112406. _decorators.registerDefaultDecorators(this);
  112407. }
  112408. HandlebarsEnvironment.prototype = {
  112409. constructor: HandlebarsEnvironment,
  112410. logger: _logger2['default'],
  112411. log: _logger2['default'].log,
  112412. registerHelper: function registerHelper(name, fn) {
  112413. if (_utils.toString.call(name) === objectType) {
  112414. if (fn) {
  112415. throw new _exception2['default']('Arg not supported with multiple helpers');
  112416. }
  112417. _utils.extend(this.helpers, name);
  112418. } else {
  112419. this.helpers[name] = fn;
  112420. }
  112421. },
  112422. unregisterHelper: function unregisterHelper(name) {
  112423. delete this.helpers[name];
  112424. },
  112425. registerPartial: function registerPartial(name, partial) {
  112426. if (_utils.toString.call(name) === objectType) {
  112427. _utils.extend(this.partials, name);
  112428. } else {
  112429. if (typeof partial === 'undefined') {
  112430. throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
  112431. }
  112432. this.partials[name] = partial;
  112433. }
  112434. },
  112435. unregisterPartial: function unregisterPartial(name) {
  112436. delete this.partials[name];
  112437. },
  112438. registerDecorator: function registerDecorator(name, fn) {
  112439. if (_utils.toString.call(name) === objectType) {
  112440. if (fn) {
  112441. throw new _exception2['default']('Arg not supported with multiple decorators');
  112442. }
  112443. _utils.extend(this.decorators, name);
  112444. } else {
  112445. this.decorators[name] = fn;
  112446. }
  112447. },
  112448. unregisterDecorator: function unregisterDecorator(name) {
  112449. delete this.decorators[name];
  112450. }
  112451. };
  112452. var log = _logger2['default'].log;
  112453. exports.log = log;
  112454. exports.createFrame = _utils.createFrame;
  112455. exports.logger = _logger2['default'];
  112456. /***/ }),
  112457. /* 5 */
  112458. /***/ (function(module, exports) {
  112459. 'use strict';
  112460. exports.__esModule = true;
  112461. exports.extend = extend;
  112462. exports.indexOf = indexOf;
  112463. exports.escapeExpression = escapeExpression;
  112464. exports.isEmpty = isEmpty;
  112465. exports.createFrame = createFrame;
  112466. exports.blockParams = blockParams;
  112467. exports.appendContextPath = appendContextPath;
  112468. var escape = {
  112469. '&': '&amp;',
  112470. '<': '&lt;',
  112471. '>': '&gt;',
  112472. '"': '&quot;',
  112473. "'": '&#x27;',
  112474. '`': '&#x60;',
  112475. '=': '&#x3D;'
  112476. };
  112477. var badChars = /[&<>"'`=]/g,
  112478. possible = /[&<>"'`=]/;
  112479. function escapeChar(chr) {
  112480. return escape[chr];
  112481. }
  112482. function extend(obj /* , ...source */) {
  112483. for (var i = 1; i < arguments.length; i++) {
  112484. for (var key in arguments[i]) {
  112485. if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
  112486. obj[key] = arguments[i][key];
  112487. }
  112488. }
  112489. }
  112490. return obj;
  112491. }
  112492. var toString = Object.prototype.toString;
  112493. exports.toString = toString;
  112494. // Sourced from lodash
  112495. // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
  112496. /* eslint-disable func-style */
  112497. var isFunction = function isFunction(value) {
  112498. return typeof value === 'function';
  112499. };
  112500. // fallback for older versions of Chrome and Safari
  112501. /* istanbul ignore next */
  112502. if (isFunction(/x/)) {
  112503. exports.isFunction = isFunction = function (value) {
  112504. return typeof value === 'function' && toString.call(value) === '[object Function]';
  112505. };
  112506. }
  112507. exports.isFunction = isFunction;
  112508. /* eslint-enable func-style */
  112509. /* istanbul ignore next */
  112510. var isArray = Array.isArray || function (value) {
  112511. return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false;
  112512. };
  112513. exports.isArray = isArray;
  112514. // Older IE versions do not directly support indexOf so we must implement our own, sadly.
  112515. function indexOf(array, value) {
  112516. for (var i = 0, len = array.length; i < len; i++) {
  112517. if (array[i] === value) {
  112518. return i;
  112519. }
  112520. }
  112521. return -1;
  112522. }
  112523. function escapeExpression(string) {
  112524. if (typeof string !== 'string') {
  112525. // don't escape SafeStrings, since they're already safe
  112526. if (string && string.toHTML) {
  112527. return string.toHTML();
  112528. } else if (string == null) {
  112529. return '';
  112530. } else if (!string) {
  112531. return string + '';
  112532. }
  112533. // Force a string conversion as this will be done by the append regardless and
  112534. // the regex test will do this transparently behind the scenes, causing issues if
  112535. // an object's to string has escaped characters in it.
  112536. string = '' + string;
  112537. }
  112538. if (!possible.test(string)) {
  112539. return string;
  112540. }
  112541. return string.replace(badChars, escapeChar);
  112542. }
  112543. function isEmpty(value) {
  112544. if (!value && value !== 0) {
  112545. return true;
  112546. } else if (isArray(value) && value.length === 0) {
  112547. return true;
  112548. } else {
  112549. return false;
  112550. }
  112551. }
  112552. function createFrame(object) {
  112553. var frame = extend({}, object);
  112554. frame._parent = object;
  112555. return frame;
  112556. }
  112557. function blockParams(params, ids) {
  112558. params.path = ids;
  112559. return params;
  112560. }
  112561. function appendContextPath(contextPath, id) {
  112562. return (contextPath ? contextPath + '.' : '') + id;
  112563. }
  112564. /***/ }),
  112565. /* 6 */
  112566. /***/ (function(module, exports, __webpack_require__) {
  112567. 'use strict';
  112568. var _Object$defineProperty = __webpack_require__(7)['default'];
  112569. exports.__esModule = true;
  112570. var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
  112571. function Exception(message, node) {
  112572. var loc = node && node.loc,
  112573. line = undefined,
  112574. column = undefined;
  112575. if (loc) {
  112576. line = loc.start.line;
  112577. column = loc.start.column;
  112578. message += ' - ' + line + ':' + column;
  112579. }
  112580. var tmp = Error.prototype.constructor.call(this, message);
  112581. // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
  112582. for (var idx = 0; idx < errorProps.length; idx++) {
  112583. this[errorProps[idx]] = tmp[errorProps[idx]];
  112584. }
  112585. /* istanbul ignore else */
  112586. if (Error.captureStackTrace) {
  112587. Error.captureStackTrace(this, Exception);
  112588. }
  112589. try {
  112590. if (loc) {
  112591. this.lineNumber = line;
  112592. // Work around issue under safari where we can't directly set the column value
  112593. /* istanbul ignore next */
  112594. if (_Object$defineProperty) {
  112595. Object.defineProperty(this, 'column', {
  112596. value: column,
  112597. enumerable: true
  112598. });
  112599. } else {
  112600. this.column = column;
  112601. }
  112602. }
  112603. } catch (nop) {
  112604. /* Ignore if the browser is very particular */
  112605. }
  112606. }
  112607. Exception.prototype = new Error();
  112608. exports['default'] = Exception;
  112609. module.exports = exports['default'];
  112610. /***/ }),
  112611. /* 7 */
  112612. /***/ (function(module, exports, __webpack_require__) {
  112613. module.exports = { "default": __webpack_require__(8), __esModule: true };
  112614. /***/ }),
  112615. /* 8 */
  112616. /***/ (function(module, exports, __webpack_require__) {
  112617. var $ = __webpack_require__(9);
  112618. module.exports = function defineProperty(it, key, desc){
  112619. return $.setDesc(it, key, desc);
  112620. };
  112621. /***/ }),
  112622. /* 9 */
  112623. /***/ (function(module, exports) {
  112624. var $Object = Object;
  112625. module.exports = {
  112626. create: $Object.create,
  112627. getProto: $Object.getPrototypeOf,
  112628. isEnum: {}.propertyIsEnumerable,
  112629. getDesc: $Object.getOwnPropertyDescriptor,
  112630. setDesc: $Object.defineProperty,
  112631. setDescs: $Object.defineProperties,
  112632. getKeys: $Object.keys,
  112633. getNames: $Object.getOwnPropertyNames,
  112634. getSymbols: $Object.getOwnPropertySymbols,
  112635. each: [].forEach
  112636. };
  112637. /***/ }),
  112638. /* 10 */
  112639. /***/ (function(module, exports, __webpack_require__) {
  112640. 'use strict';
  112641. var _interopRequireDefault = __webpack_require__(1)['default'];
  112642. exports.__esModule = true;
  112643. exports.registerDefaultHelpers = registerDefaultHelpers;
  112644. var _helpersBlockHelperMissing = __webpack_require__(11);
  112645. var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);
  112646. var _helpersEach = __webpack_require__(12);
  112647. var _helpersEach2 = _interopRequireDefault(_helpersEach);
  112648. var _helpersHelperMissing = __webpack_require__(13);
  112649. var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);
  112650. var _helpersIf = __webpack_require__(14);
  112651. var _helpersIf2 = _interopRequireDefault(_helpersIf);
  112652. var _helpersLog = __webpack_require__(15);
  112653. var _helpersLog2 = _interopRequireDefault(_helpersLog);
  112654. var _helpersLookup = __webpack_require__(16);
  112655. var _helpersLookup2 = _interopRequireDefault(_helpersLookup);
  112656. var _helpersWith = __webpack_require__(17);
  112657. var _helpersWith2 = _interopRequireDefault(_helpersWith);
  112658. function registerDefaultHelpers(instance) {
  112659. _helpersBlockHelperMissing2['default'](instance);
  112660. _helpersEach2['default'](instance);
  112661. _helpersHelperMissing2['default'](instance);
  112662. _helpersIf2['default'](instance);
  112663. _helpersLog2['default'](instance);
  112664. _helpersLookup2['default'](instance);
  112665. _helpersWith2['default'](instance);
  112666. }
  112667. /***/ }),
  112668. /* 11 */
  112669. /***/ (function(module, exports, __webpack_require__) {
  112670. 'use strict';
  112671. exports.__esModule = true;
  112672. var _utils = __webpack_require__(5);
  112673. exports['default'] = function (instance) {
  112674. instance.registerHelper('blockHelperMissing', function (context, options) {
  112675. var inverse = options.inverse,
  112676. fn = options.fn;
  112677. if (context === true) {
  112678. return fn(this);
  112679. } else if (context === false || context == null) {
  112680. return inverse(this);
  112681. } else if (_utils.isArray(context)) {
  112682. if (context.length > 0) {
  112683. if (options.ids) {
  112684. options.ids = [options.name];
  112685. }
  112686. return instance.helpers.each(context, options);
  112687. } else {
  112688. return inverse(this);
  112689. }
  112690. } else {
  112691. if (options.data && options.ids) {
  112692. var data = _utils.createFrame(options.data);
  112693. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
  112694. options = { data: data };
  112695. }
  112696. return fn(context, options);
  112697. }
  112698. });
  112699. };
  112700. module.exports = exports['default'];
  112701. /***/ }),
  112702. /* 12 */
  112703. /***/ (function(module, exports, __webpack_require__) {
  112704. 'use strict';
  112705. var _interopRequireDefault = __webpack_require__(1)['default'];
  112706. exports.__esModule = true;
  112707. var _utils = __webpack_require__(5);
  112708. var _exception = __webpack_require__(6);
  112709. var _exception2 = _interopRequireDefault(_exception);
  112710. exports['default'] = function (instance) {
  112711. instance.registerHelper('each', function (context, options) {
  112712. if (!options) {
  112713. throw new _exception2['default']('Must pass iterator to #each');
  112714. }
  112715. var fn = options.fn,
  112716. inverse = options.inverse,
  112717. i = 0,
  112718. ret = '',
  112719. data = undefined,
  112720. contextPath = undefined;
  112721. if (options.data && options.ids) {
  112722. contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
  112723. }
  112724. if (_utils.isFunction(context)) {
  112725. context = context.call(this);
  112726. }
  112727. if (options.data) {
  112728. data = _utils.createFrame(options.data);
  112729. }
  112730. function execIteration(field, index, last) {
  112731. if (data) {
  112732. data.key = field;
  112733. data.index = index;
  112734. data.first = index === 0;
  112735. data.last = !!last;
  112736. if (contextPath) {
  112737. data.contextPath = contextPath + field;
  112738. }
  112739. }
  112740. ret = ret + fn(context[field], {
  112741. data: data,
  112742. blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
  112743. });
  112744. }
  112745. if (context && typeof context === 'object') {
  112746. if (_utils.isArray(context)) {
  112747. for (var j = context.length; i < j; i++) {
  112748. if (i in context) {
  112749. execIteration(i, i, i === context.length - 1);
  112750. }
  112751. }
  112752. } else {
  112753. var priorKey = undefined;
  112754. for (var key in context) {
  112755. if (context.hasOwnProperty(key)) {
  112756. // We're running the iterations one step out of sync so we can detect
  112757. // the last iteration without have to scan the object twice and create
  112758. // an itermediate keys array.
  112759. if (priorKey !== undefined) {
  112760. execIteration(priorKey, i - 1);
  112761. }
  112762. priorKey = key;
  112763. i++;
  112764. }
  112765. }
  112766. if (priorKey !== undefined) {
  112767. execIteration(priorKey, i - 1, true);
  112768. }
  112769. }
  112770. }
  112771. if (i === 0) {
  112772. ret = inverse(this);
  112773. }
  112774. return ret;
  112775. });
  112776. };
  112777. module.exports = exports['default'];
  112778. /***/ }),
  112779. /* 13 */
  112780. /***/ (function(module, exports, __webpack_require__) {
  112781. 'use strict';
  112782. var _interopRequireDefault = __webpack_require__(1)['default'];
  112783. exports.__esModule = true;
  112784. var _exception = __webpack_require__(6);
  112785. var _exception2 = _interopRequireDefault(_exception);
  112786. exports['default'] = function (instance) {
  112787. instance.registerHelper('helperMissing', function () /* [args, ]options */{
  112788. if (arguments.length === 1) {
  112789. // A missing field in a {{foo}} construct.
  112790. return undefined;
  112791. } else {
  112792. // Someone is actually trying to call something, blow up.
  112793. throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
  112794. }
  112795. });
  112796. };
  112797. module.exports = exports['default'];
  112798. /***/ }),
  112799. /* 14 */
  112800. /***/ (function(module, exports, __webpack_require__) {
  112801. 'use strict';
  112802. exports.__esModule = true;
  112803. var _utils = __webpack_require__(5);
  112804. exports['default'] = function (instance) {
  112805. instance.registerHelper('if', function (conditional, options) {
  112806. if (_utils.isFunction(conditional)) {
  112807. conditional = conditional.call(this);
  112808. }
  112809. // Default behavior is to render the positive path if the value is truthy and not empty.
  112810. // The `includeZero` option may be set to treat the condtional as purely not empty based on the
  112811. // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
  112812. if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
  112813. return options.inverse(this);
  112814. } else {
  112815. return options.fn(this);
  112816. }
  112817. });
  112818. instance.registerHelper('unless', function (conditional, options) {
  112819. return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
  112820. });
  112821. };
  112822. module.exports = exports['default'];
  112823. /***/ }),
  112824. /* 15 */
  112825. /***/ (function(module, exports) {
  112826. 'use strict';
  112827. exports.__esModule = true;
  112828. exports['default'] = function (instance) {
  112829. instance.registerHelper('log', function () /* message, options */{
  112830. var args = [undefined],
  112831. options = arguments[arguments.length - 1];
  112832. for (var i = 0; i < arguments.length - 1; i++) {
  112833. args.push(arguments[i]);
  112834. }
  112835. var level = 1;
  112836. if (options.hash.level != null) {
  112837. level = options.hash.level;
  112838. } else if (options.data && options.data.level != null) {
  112839. level = options.data.level;
  112840. }
  112841. args[0] = level;
  112842. instance.log.apply(instance, args);
  112843. });
  112844. };
  112845. module.exports = exports['default'];
  112846. /***/ }),
  112847. /* 16 */
  112848. /***/ (function(module, exports) {
  112849. 'use strict';
  112850. exports.__esModule = true;
  112851. exports['default'] = function (instance) {
  112852. instance.registerHelper('lookup', function (obj, field) {
  112853. return obj && obj[field];
  112854. });
  112855. };
  112856. module.exports = exports['default'];
  112857. /***/ }),
  112858. /* 17 */
  112859. /***/ (function(module, exports, __webpack_require__) {
  112860. 'use strict';
  112861. exports.__esModule = true;
  112862. var _utils = __webpack_require__(5);
  112863. exports['default'] = function (instance) {
  112864. instance.registerHelper('with', function (context, options) {
  112865. if (_utils.isFunction(context)) {
  112866. context = context.call(this);
  112867. }
  112868. var fn = options.fn;
  112869. if (!_utils.isEmpty(context)) {
  112870. var data = options.data;
  112871. if (options.data && options.ids) {
  112872. data = _utils.createFrame(options.data);
  112873. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
  112874. }
  112875. return fn(context, {
  112876. data: data,
  112877. blockParams: _utils.blockParams([context], [data && data.contextPath])
  112878. });
  112879. } else {
  112880. return options.inverse(this);
  112881. }
  112882. });
  112883. };
  112884. module.exports = exports['default'];
  112885. /***/ }),
  112886. /* 18 */
  112887. /***/ (function(module, exports, __webpack_require__) {
  112888. 'use strict';
  112889. var _interopRequireDefault = __webpack_require__(1)['default'];
  112890. exports.__esModule = true;
  112891. exports.registerDefaultDecorators = registerDefaultDecorators;
  112892. var _decoratorsInline = __webpack_require__(19);
  112893. var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);
  112894. function registerDefaultDecorators(instance) {
  112895. _decoratorsInline2['default'](instance);
  112896. }
  112897. /***/ }),
  112898. /* 19 */
  112899. /***/ (function(module, exports, __webpack_require__) {
  112900. 'use strict';
  112901. exports.__esModule = true;
  112902. var _utils = __webpack_require__(5);
  112903. exports['default'] = function (instance) {
  112904. instance.registerDecorator('inline', function (fn, props, container, options) {
  112905. var ret = fn;
  112906. if (!props.partials) {
  112907. props.partials = {};
  112908. ret = function (context, options) {
  112909. // Create a new partials stack frame prior to exec.
  112910. var original = container.partials;
  112911. container.partials = _utils.extend({}, original, props.partials);
  112912. var ret = fn(context, options);
  112913. container.partials = original;
  112914. return ret;
  112915. };
  112916. }
  112917. props.partials[options.args[0]] = options.fn;
  112918. return ret;
  112919. });
  112920. };
  112921. module.exports = exports['default'];
  112922. /***/ }),
  112923. /* 20 */
  112924. /***/ (function(module, exports, __webpack_require__) {
  112925. 'use strict';
  112926. exports.__esModule = true;
  112927. var _utils = __webpack_require__(5);
  112928. var logger = {
  112929. methodMap: ['debug', 'info', 'warn', 'error'],
  112930. level: 'info',
  112931. // Maps a given level value to the `methodMap` indexes above.
  112932. lookupLevel: function lookupLevel(level) {
  112933. if (typeof level === 'string') {
  112934. var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
  112935. if (levelMap >= 0) {
  112936. level = levelMap;
  112937. } else {
  112938. level = parseInt(level, 10);
  112939. }
  112940. }
  112941. return level;
  112942. },
  112943. // Can be overridden in the host environment
  112944. log: function log(level) {
  112945. level = logger.lookupLevel(level);
  112946. if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
  112947. var method = logger.methodMap[level];
  112948. if (!console[method]) {
  112949. // eslint-disable-line no-console
  112950. method = 'log';
  112951. }
  112952. for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  112953. message[_key - 1] = arguments[_key];
  112954. }
  112955. console[method].apply(console, message); // eslint-disable-line no-console
  112956. }
  112957. }
  112958. };
  112959. exports['default'] = logger;
  112960. module.exports = exports['default'];
  112961. /***/ }),
  112962. /* 21 */
  112963. /***/ (function(module, exports) {
  112964. // Build out our basic SafeString type
  112965. 'use strict';
  112966. exports.__esModule = true;
  112967. function SafeString(string) {
  112968. this.string = string;
  112969. }
  112970. SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
  112971. return '' + this.string;
  112972. };
  112973. exports['default'] = SafeString;
  112974. module.exports = exports['default'];
  112975. /***/ }),
  112976. /* 22 */
  112977. /***/ (function(module, exports, __webpack_require__) {
  112978. 'use strict';
  112979. var _Object$seal = __webpack_require__(23)['default'];
  112980. var _interopRequireWildcard = __webpack_require__(3)['default'];
  112981. var _interopRequireDefault = __webpack_require__(1)['default'];
  112982. exports.__esModule = true;
  112983. exports.checkRevision = checkRevision;
  112984. exports.template = template;
  112985. exports.wrapProgram = wrapProgram;
  112986. exports.resolvePartial = resolvePartial;
  112987. exports.invokePartial = invokePartial;
  112988. exports.noop = noop;
  112989. var _utils = __webpack_require__(5);
  112990. var Utils = _interopRequireWildcard(_utils);
  112991. var _exception = __webpack_require__(6);
  112992. var _exception2 = _interopRequireDefault(_exception);
  112993. var _base = __webpack_require__(4);
  112994. function checkRevision(compilerInfo) {
  112995. var compilerRevision = compilerInfo && compilerInfo[0] || 1,
  112996. currentRevision = _base.COMPILER_REVISION;
  112997. if (compilerRevision !== currentRevision) {
  112998. if (compilerRevision < currentRevision) {
  112999. var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
  113000. compilerVersions = _base.REVISION_CHANGES[compilerRevision];
  113001. 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 + ').');
  113002. } else {
  113003. // Use the embedded version info since the runtime doesn't know about this revision yet
  113004. 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] + ').');
  113005. }
  113006. }
  113007. }
  113008. function template(templateSpec, env) {
  113009. /* istanbul ignore next */
  113010. if (!env) {
  113011. throw new _exception2['default']('No environment passed to template');
  113012. }
  113013. if (!templateSpec || !templateSpec.main) {
  113014. throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
  113015. }
  113016. templateSpec.main.decorator = templateSpec.main_d;
  113017. // Note: Using env.VM references rather than local var references throughout this section to allow
  113018. // for external users to override these as psuedo-supported APIs.
  113019. env.VM.checkRevision(templateSpec.compiler);
  113020. function invokePartialWrapper(partial, context, options) {
  113021. if (options.hash) {
  113022. context = Utils.extend({}, context, options.hash);
  113023. if (options.ids) {
  113024. options.ids[0] = true;
  113025. }
  113026. }
  113027. partial = env.VM.resolvePartial.call(this, partial, context, options);
  113028. var result = env.VM.invokePartial.call(this, partial, context, options);
  113029. if (result == null && env.compile) {
  113030. options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
  113031. result = options.partials[options.name](context, options);
  113032. }
  113033. if (result != null) {
  113034. if (options.indent) {
  113035. var lines = result.split('\n');
  113036. for (var i = 0, l = lines.length; i < l; i++) {
  113037. if (!lines[i] && i + 1 === l) {
  113038. break;
  113039. }
  113040. lines[i] = options.indent + lines[i];
  113041. }
  113042. result = lines.join('\n');
  113043. }
  113044. return result;
  113045. } else {
  113046. throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
  113047. }
  113048. }
  113049. // Just add water
  113050. var container = {
  113051. strict: function strict(obj, name) {
  113052. if (!(name in obj)) {
  113053. throw new _exception2['default']('"' + name + '" not defined in ' + obj);
  113054. }
  113055. return obj[name];
  113056. },
  113057. lookup: function lookup(depths, name) {
  113058. var len = depths.length;
  113059. for (var i = 0; i < len; i++) {
  113060. if (depths[i] && depths[i][name] != null) {
  113061. return depths[i][name];
  113062. }
  113063. }
  113064. },
  113065. lambda: function lambda(current, context) {
  113066. return typeof current === 'function' ? current.call(context) : current;
  113067. },
  113068. escapeExpression: Utils.escapeExpression,
  113069. invokePartial: invokePartialWrapper,
  113070. fn: function fn(i) {
  113071. var ret = templateSpec[i];
  113072. ret.decorator = templateSpec[i + '_d'];
  113073. return ret;
  113074. },
  113075. programs: [],
  113076. program: function program(i, data, declaredBlockParams, blockParams, depths) {
  113077. var programWrapper = this.programs[i],
  113078. fn = this.fn(i);
  113079. if (data || depths || blockParams || declaredBlockParams) {
  113080. programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
  113081. } else if (!programWrapper) {
  113082. programWrapper = this.programs[i] = wrapProgram(this, i, fn);
  113083. }
  113084. return programWrapper;
  113085. },
  113086. data: function data(value, depth) {
  113087. while (value && depth--) {
  113088. value = value._parent;
  113089. }
  113090. return value;
  113091. },
  113092. merge: function merge(param, common) {
  113093. var obj = param || common;
  113094. if (param && common && param !== common) {
  113095. obj = Utils.extend({}, common, param);
  113096. }
  113097. return obj;
  113098. },
  113099. // An empty object to use as replacement for null-contexts
  113100. nullContext: _Object$seal({}),
  113101. noop: env.VM.noop,
  113102. compilerInfo: templateSpec.compiler
  113103. };
  113104. function ret(context) {
  113105. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  113106. var data = options.data;
  113107. ret._setup(options);
  113108. if (!options.partial && templateSpec.useData) {
  113109. data = initData(context, data);
  113110. }
  113111. var depths = undefined,
  113112. blockParams = templateSpec.useBlockParams ? [] : undefined;
  113113. if (templateSpec.useDepths) {
  113114. if (options.depths) {
  113115. depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
  113116. } else {
  113117. depths = [context];
  113118. }
  113119. }
  113120. function main(context /*, options*/) {
  113121. return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
  113122. }
  113123. main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
  113124. return main(context, options);
  113125. }
  113126. ret.isTop = true;
  113127. ret._setup = function (options) {
  113128. if (!options.partial) {
  113129. container.helpers = container.merge(options.helpers, env.helpers);
  113130. if (templateSpec.usePartial) {
  113131. container.partials = container.merge(options.partials, env.partials);
  113132. }
  113133. if (templateSpec.usePartial || templateSpec.useDecorators) {
  113134. container.decorators = container.merge(options.decorators, env.decorators);
  113135. }
  113136. } else {
  113137. container.helpers = options.helpers;
  113138. container.partials = options.partials;
  113139. container.decorators = options.decorators;
  113140. }
  113141. };
  113142. ret._child = function (i, data, blockParams, depths) {
  113143. if (templateSpec.useBlockParams && !blockParams) {
  113144. throw new _exception2['default']('must pass block params');
  113145. }
  113146. if (templateSpec.useDepths && !depths) {
  113147. throw new _exception2['default']('must pass parent depths');
  113148. }
  113149. return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
  113150. };
  113151. return ret;
  113152. }
  113153. function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
  113154. function prog(context) {
  113155. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  113156. var currentDepths = depths;
  113157. if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
  113158. currentDepths = [context].concat(depths);
  113159. }
  113160. return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
  113161. }
  113162. prog = executeDecorators(fn, prog, container, depths, data, blockParams);
  113163. prog.program = i;
  113164. prog.depth = depths ? depths.length : 0;
  113165. prog.blockParams = declaredBlockParams || 0;
  113166. return prog;
  113167. }
  113168. function resolvePartial(partial, context, options) {
  113169. if (!partial) {
  113170. if (options.name === '@partial-block') {
  113171. partial = options.data['partial-block'];
  113172. } else {
  113173. partial = options.partials[options.name];
  113174. }
  113175. } else if (!partial.call && !options.name) {
  113176. // This is a dynamic partial that returned a string
  113177. options.name = partial;
  113178. partial = options.partials[partial];
  113179. }
  113180. return partial;
  113181. }
  113182. function invokePartial(partial, context, options) {
  113183. // Use the current closure context to save the partial-block if this partial
  113184. var currentPartialBlock = options.data && options.data['partial-block'];
  113185. options.partial = true;
  113186. if (options.ids) {
  113187. options.data.contextPath = options.ids[0] || options.data.contextPath;
  113188. }
  113189. var partialBlock = undefined;
  113190. if (options.fn && options.fn !== noop) {
  113191. (function () {
  113192. options.data = _base.createFrame(options.data);
  113193. // Wrapper function to get access to currentPartialBlock from the closure
  113194. var fn = options.fn;
  113195. partialBlock = options.data['partial-block'] = function partialBlockWrapper(context) {
  113196. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  113197. // Restore the partial-block from the closure for the execution of the block
  113198. // i.e. the part inside the block of the partial call.
  113199. options.data = _base.createFrame(options.data);
  113200. options.data['partial-block'] = currentPartialBlock;
  113201. return fn(context, options);
  113202. };
  113203. if (fn.partials) {
  113204. options.partials = Utils.extend({}, options.partials, fn.partials);
  113205. }
  113206. })();
  113207. }
  113208. if (partial === undefined && partialBlock) {
  113209. partial = partialBlock;
  113210. }
  113211. if (partial === undefined) {
  113212. throw new _exception2['default']('The partial ' + options.name + ' could not be found');
  113213. } else if (partial instanceof Function) {
  113214. return partial(context, options);
  113215. }
  113216. }
  113217. function noop() {
  113218. return '';
  113219. }
  113220. function initData(context, data) {
  113221. if (!data || !('root' in data)) {
  113222. data = data ? _base.createFrame(data) : {};
  113223. data.root = context;
  113224. }
  113225. return data;
  113226. }
  113227. function executeDecorators(fn, prog, container, depths, data, blockParams) {
  113228. if (fn.decorator) {
  113229. var props = {};
  113230. prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
  113231. Utils.extend(prog, props);
  113232. }
  113233. return prog;
  113234. }
  113235. /***/ }),
  113236. /* 23 */
  113237. /***/ (function(module, exports, __webpack_require__) {
  113238. module.exports = { "default": __webpack_require__(24), __esModule: true };
  113239. /***/ }),
  113240. /* 24 */
  113241. /***/ (function(module, exports, __webpack_require__) {
  113242. __webpack_require__(25);
  113243. module.exports = __webpack_require__(30).Object.seal;
  113244. /***/ }),
  113245. /* 25 */
  113246. /***/ (function(module, exports, __webpack_require__) {
  113247. // 19.1.2.17 Object.seal(O)
  113248. var isObject = __webpack_require__(26);
  113249. __webpack_require__(27)('seal', function($seal){
  113250. return function seal(it){
  113251. return $seal && isObject(it) ? $seal(it) : it;
  113252. };
  113253. });
  113254. /***/ }),
  113255. /* 26 */
  113256. /***/ (function(module, exports) {
  113257. module.exports = function(it){
  113258. return typeof it === 'object' ? it !== null : typeof it === 'function';
  113259. };
  113260. /***/ }),
  113261. /* 27 */
  113262. /***/ (function(module, exports, __webpack_require__) {
  113263. // most Object methods by ES6 should accept primitives
  113264. var $export = __webpack_require__(28)
  113265. , core = __webpack_require__(30)
  113266. , fails = __webpack_require__(33);
  113267. module.exports = function(KEY, exec){
  113268. var fn = (core.Object || {})[KEY] || Object[KEY]
  113269. , exp = {};
  113270. exp[KEY] = exec(fn);
  113271. $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
  113272. };
  113273. /***/ }),
  113274. /* 28 */
  113275. /***/ (function(module, exports, __webpack_require__) {
  113276. var global = __webpack_require__(29)
  113277. , core = __webpack_require__(30)
  113278. , ctx = __webpack_require__(31)
  113279. , PROTOTYPE = 'prototype';
  113280. var $export = function(type, name, source){
  113281. var IS_FORCED = type & $export.F
  113282. , IS_GLOBAL = type & $export.G
  113283. , IS_STATIC = type & $export.S
  113284. , IS_PROTO = type & $export.P
  113285. , IS_BIND = type & $export.B
  113286. , IS_WRAP = type & $export.W
  113287. , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
  113288. , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  113289. , key, own, out;
  113290. if(IS_GLOBAL)source = name;
  113291. for(key in source){
  113292. // contains in native
  113293. own = !IS_FORCED && target && key in target;
  113294. if(own && key in exports)continue;
  113295. // export native or passed
  113296. out = own ? target[key] : source[key];
  113297. // prevent global pollution for namespaces
  113298. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  113299. // bind timers to global for call from export context
  113300. : IS_BIND && own ? ctx(out, global)
  113301. // wrap global constructors for prevent change them in library
  113302. : IS_WRAP && target[key] == out ? (function(C){
  113303. var F = function(param){
  113304. return this instanceof C ? new C(param) : C(param);
  113305. };
  113306. F[PROTOTYPE] = C[PROTOTYPE];
  113307. return F;
  113308. // make static versions for prototype methods
  113309. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  113310. if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
  113311. }
  113312. };
  113313. // type bitmap
  113314. $export.F = 1; // forced
  113315. $export.G = 2; // global
  113316. $export.S = 4; // static
  113317. $export.P = 8; // proto
  113318. $export.B = 16; // bind
  113319. $export.W = 32; // wrap
  113320. module.exports = $export;
  113321. /***/ }),
  113322. /* 29 */
  113323. /***/ (function(module, exports) {
  113324. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  113325. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  113326. ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  113327. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  113328. /***/ }),
  113329. /* 30 */
  113330. /***/ (function(module, exports) {
  113331. var core = module.exports = {version: '1.2.6'};
  113332. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  113333. /***/ }),
  113334. /* 31 */
  113335. /***/ (function(module, exports, __webpack_require__) {
  113336. // optional / simple context binding
  113337. var aFunction = __webpack_require__(32);
  113338. module.exports = function(fn, that, length){
  113339. aFunction(fn);
  113340. if(that === undefined)return fn;
  113341. switch(length){
  113342. case 1: return function(a){
  113343. return fn.call(that, a);
  113344. };
  113345. case 2: return function(a, b){
  113346. return fn.call(that, a, b);
  113347. };
  113348. case 3: return function(a, b, c){
  113349. return fn.call(that, a, b, c);
  113350. };
  113351. }
  113352. return function(/* ...args */){
  113353. return fn.apply(that, arguments);
  113354. };
  113355. };
  113356. /***/ }),
  113357. /* 32 */
  113358. /***/ (function(module, exports) {
  113359. module.exports = function(it){
  113360. if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  113361. return it;
  113362. };
  113363. /***/ }),
  113364. /* 33 */
  113365. /***/ (function(module, exports) {
  113366. module.exports = function(exec){
  113367. try {
  113368. return !!exec();
  113369. } catch(e){
  113370. return true;
  113371. }
  113372. };
  113373. /***/ }),
  113374. /* 34 */
  113375. /***/ (function(module, exports) {
  113376. /* WEBPACK VAR INJECTION */(function(global) {/* global window */
  113377. 'use strict';
  113378. exports.__esModule = true;
  113379. exports['default'] = function (Handlebars) {
  113380. /* istanbul ignore next */
  113381. var root = typeof global !== 'undefined' ? global : window,
  113382. $Handlebars = root.Handlebars;
  113383. /* istanbul ignore next */
  113384. Handlebars.noConflict = function () {
  113385. if (root.Handlebars === Handlebars) {
  113386. root.Handlebars = $Handlebars;
  113387. }
  113388. return Handlebars;
  113389. };
  113390. };
  113391. module.exports = exports['default'];
  113392. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  113393. /***/ }),
  113394. /* 35 */
  113395. /***/ (function(module, exports) {
  113396. 'use strict';
  113397. exports.__esModule = true;
  113398. var AST = {
  113399. // Public API used to evaluate derived attributes regarding AST nodes
  113400. helpers: {
  113401. // a mustache is definitely a helper if:
  113402. // * it is an eligible helper, and
  113403. // * it has at least one parameter or hash segment
  113404. helperExpression: function helperExpression(node) {
  113405. return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash);
  113406. },
  113407. scopedId: function scopedId(path) {
  113408. return (/^\.|this\b/.test(path.original)
  113409. );
  113410. },
  113411. // an ID is simple if it only has one part, and that part is not
  113412. // `..` or `this`.
  113413. simpleId: function simpleId(path) {
  113414. return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
  113415. }
  113416. }
  113417. };
  113418. // Must be exported as an object rather than the root of the module as the jison lexer
  113419. // must modify the object to operate properly.
  113420. exports['default'] = AST;
  113421. module.exports = exports['default'];
  113422. /***/ }),
  113423. /* 36 */
  113424. /***/ (function(module, exports, __webpack_require__) {
  113425. 'use strict';
  113426. var _interopRequireDefault = __webpack_require__(1)['default'];
  113427. var _interopRequireWildcard = __webpack_require__(3)['default'];
  113428. exports.__esModule = true;
  113429. exports.parse = parse;
  113430. var _parser = __webpack_require__(37);
  113431. var _parser2 = _interopRequireDefault(_parser);
  113432. var _whitespaceControl = __webpack_require__(38);
  113433. var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);
  113434. var _helpers = __webpack_require__(40);
  113435. var Helpers = _interopRequireWildcard(_helpers);
  113436. var _utils = __webpack_require__(5);
  113437. exports.parser = _parser2['default'];
  113438. var yy = {};
  113439. _utils.extend(yy, Helpers);
  113440. function parse(input, options) {
  113441. // Just return if an already-compiled AST was passed in.
  113442. if (input.type === 'Program') {
  113443. return input;
  113444. }
  113445. _parser2['default'].yy = yy;
  113446. // Altering the shared object here, but this is ok as parser is a sync operation
  113447. yy.locInfo = function (locInfo) {
  113448. return new yy.SourceLocation(options && options.srcName, locInfo);
  113449. };
  113450. var strip = new _whitespaceControl2['default'](options);
  113451. return strip.accept(_parser2['default'].parse(input));
  113452. }
  113453. /***/ }),
  113454. /* 37 */
  113455. /***/ (function(module, exports) {
  113456. // File ignored in coverage tests via setting in .istanbul.yml
  113457. /* Jison generated parser */
  113458. "use strict";
  113459. exports.__esModule = true;
  113460. var handlebars = (function () {
  113461. var parser = { trace: function trace() {},
  113462. yy: {},
  113463. 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 },
  113464. 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" },
  113465. 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]],
  113466. performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$
  113467. /**/) {
  113468. var $0 = $$.length - 1;
  113469. switch (yystate) {
  113470. case 1:
  113471. return $$[$0 - 1];
  113472. break;
  113473. case 2:
  113474. this.$ = yy.prepareProgram($$[$0]);
  113475. break;
  113476. case 3:
  113477. this.$ = $$[$0];
  113478. break;
  113479. case 4:
  113480. this.$ = $$[$0];
  113481. break;
  113482. case 5:
  113483. this.$ = $$[$0];
  113484. break;
  113485. case 6:
  113486. this.$ = $$[$0];
  113487. break;
  113488. case 7:
  113489. this.$ = $$[$0];
  113490. break;
  113491. case 8:
  113492. this.$ = $$[$0];
  113493. break;
  113494. case 9:
  113495. this.$ = {
  113496. type: 'CommentStatement',
  113497. value: yy.stripComment($$[$0]),
  113498. strip: yy.stripFlags($$[$0], $$[$0]),
  113499. loc: yy.locInfo(this._$)
  113500. };
  113501. break;
  113502. case 10:
  113503. this.$ = {
  113504. type: 'ContentStatement',
  113505. original: $$[$0],
  113506. value: $$[$0],
  113507. loc: yy.locInfo(this._$)
  113508. };
  113509. break;
  113510. case 11:
  113511. this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  113512. break;
  113513. case 12:
  113514. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
  113515. break;
  113516. case 13:
  113517. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
  113518. break;
  113519. case 14:
  113520. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
  113521. break;
  113522. case 15:
  113523. this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  113524. break;
  113525. case 16:
  113526. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  113527. break;
  113528. case 17:
  113529. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  113530. break;
  113531. case 18:
  113532. this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
  113533. break;
  113534. case 19:
  113535. var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$),
  113536. program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
  113537. program.chained = true;
  113538. this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true };
  113539. break;
  113540. case 20:
  113541. this.$ = $$[$0];
  113542. break;
  113543. case 21:
  113544. this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
  113545. break;
  113546. case 22:
  113547. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  113548. break;
  113549. case 23:
  113550. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  113551. break;
  113552. case 24:
  113553. this.$ = {
  113554. type: 'PartialStatement',
  113555. name: $$[$0 - 3],
  113556. params: $$[$0 - 2],
  113557. hash: $$[$0 - 1],
  113558. indent: '',
  113559. strip: yy.stripFlags($$[$0 - 4], $$[$0]),
  113560. loc: yy.locInfo(this._$)
  113561. };
  113562. break;
  113563. case 25:
  113564. this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  113565. break;
  113566. case 26:
  113567. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
  113568. break;
  113569. case 27:
  113570. this.$ = $$[$0];
  113571. break;
  113572. case 28:
  113573. this.$ = $$[$0];
  113574. break;
  113575. case 29:
  113576. this.$ = {
  113577. type: 'SubExpression',
  113578. path: $$[$0 - 3],
  113579. params: $$[$0 - 2],
  113580. hash: $$[$0 - 1],
  113581. loc: yy.locInfo(this._$)
  113582. };
  113583. break;
  113584. case 30:
  113585. this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) };
  113586. break;
  113587. case 31:
  113588. this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
  113589. break;
  113590. case 32:
  113591. this.$ = yy.id($$[$0 - 1]);
  113592. break;
  113593. case 33:
  113594. this.$ = $$[$0];
  113595. break;
  113596. case 34:
  113597. this.$ = $$[$0];
  113598. break;
  113599. case 35:
  113600. this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
  113601. break;
  113602. case 36:
  113603. this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
  113604. break;
  113605. case 37:
  113606. this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) };
  113607. break;
  113608. case 38:
  113609. this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) };
  113610. break;
  113611. case 39:
  113612. this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) };
  113613. break;
  113614. case 40:
  113615. this.$ = $$[$0];
  113616. break;
  113617. case 41:
  113618. this.$ = $$[$0];
  113619. break;
  113620. case 42:
  113621. this.$ = yy.preparePath(true, $$[$0], this._$);
  113622. break;
  113623. case 43:
  113624. this.$ = yy.preparePath(false, $$[$0], this._$);
  113625. break;
  113626. case 44:
  113627. $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2];
  113628. break;
  113629. case 45:
  113630. this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
  113631. break;
  113632. case 46:
  113633. this.$ = [];
  113634. break;
  113635. case 47:
  113636. $$[$0 - 1].push($$[$0]);
  113637. break;
  113638. case 48:
  113639. this.$ = [$$[$0]];
  113640. break;
  113641. case 49:
  113642. $$[$0 - 1].push($$[$0]);
  113643. break;
  113644. case 50:
  113645. this.$ = [];
  113646. break;
  113647. case 51:
  113648. $$[$0 - 1].push($$[$0]);
  113649. break;
  113650. case 58:
  113651. this.$ = [];
  113652. break;
  113653. case 59:
  113654. $$[$0 - 1].push($$[$0]);
  113655. break;
  113656. case 64:
  113657. this.$ = [];
  113658. break;
  113659. case 65:
  113660. $$[$0 - 1].push($$[$0]);
  113661. break;
  113662. case 70:
  113663. this.$ = [];
  113664. break;
  113665. case 71:
  113666. $$[$0 - 1].push($$[$0]);
  113667. break;
  113668. case 78:
  113669. this.$ = [];
  113670. break;
  113671. case 79:
  113672. $$[$0 - 1].push($$[$0]);
  113673. break;
  113674. case 82:
  113675. this.$ = [];
  113676. break;
  113677. case 83:
  113678. $$[$0 - 1].push($$[$0]);
  113679. break;
  113680. case 86:
  113681. this.$ = [];
  113682. break;
  113683. case 87:
  113684. $$[$0 - 1].push($$[$0]);
  113685. break;
  113686. case 90:
  113687. this.$ = [];
  113688. break;
  113689. case 91:
  113690. $$[$0 - 1].push($$[$0]);
  113691. break;
  113692. case 94:
  113693. this.$ = [];
  113694. break;
  113695. case 95:
  113696. $$[$0 - 1].push($$[$0]);
  113697. break;
  113698. case 98:
  113699. this.$ = [$$[$0]];
  113700. break;
  113701. case 99:
  113702. $$[$0 - 1].push($$[$0]);
  113703. break;
  113704. case 100:
  113705. this.$ = [$$[$0]];
  113706. break;
  113707. case 101:
  113708. $$[$0 - 1].push($$[$0]);
  113709. break;
  113710. }
  113711. },
  113712. 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] }],
  113713. 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] },
  113714. parseError: function parseError(str, hash) {
  113715. throw new Error(str);
  113716. },
  113717. parse: function parse(input) {
  113718. var self = this,
  113719. stack = [0],
  113720. vstack = [null],
  113721. lstack = [],
  113722. table = this.table,
  113723. yytext = "",
  113724. yylineno = 0,
  113725. yyleng = 0,
  113726. recovering = 0,
  113727. TERROR = 2,
  113728. EOF = 1;
  113729. this.lexer.setInput(input);
  113730. this.lexer.yy = this.yy;
  113731. this.yy.lexer = this.lexer;
  113732. this.yy.parser = this;
  113733. if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
  113734. var yyloc = this.lexer.yylloc;
  113735. lstack.push(yyloc);
  113736. var ranges = this.lexer.options && this.lexer.options.ranges;
  113737. if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
  113738. function popStack(n) {
  113739. stack.length = stack.length - 2 * n;
  113740. vstack.length = vstack.length - n;
  113741. lstack.length = lstack.length - n;
  113742. }
  113743. function lex() {
  113744. var token;
  113745. token = self.lexer.lex() || 1;
  113746. if (typeof token !== "number") {
  113747. token = self.symbols_[token] || token;
  113748. }
  113749. return token;
  113750. }
  113751. var symbol,
  113752. preErrorSymbol,
  113753. state,
  113754. action,
  113755. a,
  113756. r,
  113757. yyval = {},
  113758. p,
  113759. len,
  113760. newState,
  113761. expected;
  113762. while (true) {
  113763. state = stack[stack.length - 1];
  113764. if (this.defaultActions[state]) {
  113765. action = this.defaultActions[state];
  113766. } else {
  113767. if (symbol === null || typeof symbol == "undefined") {
  113768. symbol = lex();
  113769. }
  113770. action = table[state] && table[state][symbol];
  113771. }
  113772. if (typeof action === "undefined" || !action.length || !action[0]) {
  113773. var errStr = "";
  113774. if (!recovering) {
  113775. expected = [];
  113776. for (p in table[state]) if (this.terminals_[p] && p > 2) {
  113777. expected.push("'" + this.terminals_[p] + "'");
  113778. }
  113779. if (this.lexer.showPosition) {
  113780. errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
  113781. } else {
  113782. errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
  113783. }
  113784. this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected });
  113785. }
  113786. }
  113787. if (action[0] instanceof Array && action.length > 1) {
  113788. throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
  113789. }
  113790. switch (action[0]) {
  113791. case 1:
  113792. stack.push(symbol);
  113793. vstack.push(this.lexer.yytext);
  113794. lstack.push(this.lexer.yylloc);
  113795. stack.push(action[1]);
  113796. symbol = null;
  113797. if (!preErrorSymbol) {
  113798. yyleng = this.lexer.yyleng;
  113799. yytext = this.lexer.yytext;
  113800. yylineno = this.lexer.yylineno;
  113801. yyloc = this.lexer.yylloc;
  113802. if (recovering > 0) recovering--;
  113803. } else {
  113804. symbol = preErrorSymbol;
  113805. preErrorSymbol = null;
  113806. }
  113807. break;
  113808. case 2:
  113809. len = this.productions_[action[1]][1];
  113810. yyval.$ = vstack[vstack.length - len];
  113811. 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 };
  113812. if (ranges) {
  113813. yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
  113814. }
  113815. r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
  113816. if (typeof r !== "undefined") {
  113817. return r;
  113818. }
  113819. if (len) {
  113820. stack = stack.slice(0, -1 * len * 2);
  113821. vstack = vstack.slice(0, -1 * len);
  113822. lstack = lstack.slice(0, -1 * len);
  113823. }
  113824. stack.push(this.productions_[action[1]][0]);
  113825. vstack.push(yyval.$);
  113826. lstack.push(yyval._$);
  113827. newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
  113828. stack.push(newState);
  113829. break;
  113830. case 3:
  113831. return true;
  113832. }
  113833. }
  113834. return true;
  113835. }
  113836. };
  113837. /* Jison generated lexer */
  113838. var lexer = (function () {
  113839. var lexer = { EOF: 1,
  113840. parseError: function parseError(str, hash) {
  113841. if (this.yy.parser) {
  113842. this.yy.parser.parseError(str, hash);
  113843. } else {
  113844. throw new Error(str);
  113845. }
  113846. },
  113847. setInput: function setInput(input) {
  113848. this._input = input;
  113849. this._more = this._less = this.done = false;
  113850. this.yylineno = this.yyleng = 0;
  113851. this.yytext = this.matched = this.match = '';
  113852. this.conditionStack = ['INITIAL'];
  113853. this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
  113854. if (this.options.ranges) this.yylloc.range = [0, 0];
  113855. this.offset = 0;
  113856. return this;
  113857. },
  113858. input: function input() {
  113859. var ch = this._input[0];
  113860. this.yytext += ch;
  113861. this.yyleng++;
  113862. this.offset++;
  113863. this.match += ch;
  113864. this.matched += ch;
  113865. var lines = ch.match(/(?:\r\n?|\n).*/g);
  113866. if (lines) {
  113867. this.yylineno++;
  113868. this.yylloc.last_line++;
  113869. } else {
  113870. this.yylloc.last_column++;
  113871. }
  113872. if (this.options.ranges) this.yylloc.range[1]++;
  113873. this._input = this._input.slice(1);
  113874. return ch;
  113875. },
  113876. unput: function unput(ch) {
  113877. var len = ch.length;
  113878. var lines = ch.split(/(?:\r\n?|\n)/g);
  113879. this._input = ch + this._input;
  113880. this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
  113881. //this.yyleng -= len;
  113882. this.offset -= len;
  113883. var oldLines = this.match.split(/(?:\r\n?|\n)/g);
  113884. this.match = this.match.substr(0, this.match.length - 1);
  113885. this.matched = this.matched.substr(0, this.matched.length - 1);
  113886. if (lines.length - 1) this.yylineno -= lines.length - 1;
  113887. var r = this.yylloc.range;
  113888. this.yylloc = { first_line: this.yylloc.first_line,
  113889. last_line: this.yylineno + 1,
  113890. first_column: this.yylloc.first_column,
  113891. 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
  113892. };
  113893. if (this.options.ranges) {
  113894. this.yylloc.range = [r[0], r[0] + this.yyleng - len];
  113895. }
  113896. return this;
  113897. },
  113898. more: function more() {
  113899. this._more = true;
  113900. return this;
  113901. },
  113902. less: function less(n) {
  113903. this.unput(this.match.slice(n));
  113904. },
  113905. pastInput: function pastInput() {
  113906. var past = this.matched.substr(0, this.matched.length - this.match.length);
  113907. return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
  113908. },
  113909. upcomingInput: function upcomingInput() {
  113910. var next = this.match;
  113911. if (next.length < 20) {
  113912. next += this._input.substr(0, 20 - next.length);
  113913. }
  113914. return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
  113915. },
  113916. showPosition: function showPosition() {
  113917. var pre = this.pastInput();
  113918. var c = new Array(pre.length + 1).join("-");
  113919. return pre + this.upcomingInput() + "\n" + c + "^";
  113920. },
  113921. next: function next() {
  113922. if (this.done) {
  113923. return this.EOF;
  113924. }
  113925. if (!this._input) this.done = true;
  113926. var token, match, tempMatch, index, col, lines;
  113927. if (!this._more) {
  113928. this.yytext = '';
  113929. this.match = '';
  113930. }
  113931. var rules = this._currentRules();
  113932. for (var i = 0; i < rules.length; i++) {
  113933. tempMatch = this._input.match(this.rules[rules[i]]);
  113934. if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
  113935. match = tempMatch;
  113936. index = i;
  113937. if (!this.options.flex) break;
  113938. }
  113939. }
  113940. if (match) {
  113941. lines = match[0].match(/(?:\r\n?|\n).*/g);
  113942. if (lines) this.yylineno += lines.length;
  113943. this.yylloc = { first_line: this.yylloc.last_line,
  113944. last_line: this.yylineno + 1,
  113945. first_column: this.yylloc.last_column,
  113946. last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length };
  113947. this.yytext += match[0];
  113948. this.match += match[0];
  113949. this.matches = match;
  113950. this.yyleng = this.yytext.length;
  113951. if (this.options.ranges) {
  113952. this.yylloc.range = [this.offset, this.offset += this.yyleng];
  113953. }
  113954. this._more = false;
  113955. this._input = this._input.slice(match[0].length);
  113956. this.matched += match[0];
  113957. token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
  113958. if (this.done && this._input) this.done = false;
  113959. if (token) return token;else return;
  113960. }
  113961. if (this._input === "") {
  113962. return this.EOF;
  113963. } else {
  113964. return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno });
  113965. }
  113966. },
  113967. lex: function lex() {
  113968. var r = this.next();
  113969. if (typeof r !== 'undefined') {
  113970. return r;
  113971. } else {
  113972. return this.lex();
  113973. }
  113974. },
  113975. begin: function begin(condition) {
  113976. this.conditionStack.push(condition);
  113977. },
  113978. popState: function popState() {
  113979. return this.conditionStack.pop();
  113980. },
  113981. _currentRules: function _currentRules() {
  113982. return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
  113983. },
  113984. topState: function topState() {
  113985. return this.conditionStack[this.conditionStack.length - 2];
  113986. },
  113987. pushState: function begin(condition) {
  113988. this.begin(condition);
  113989. } };
  113990. lexer.options = {};
  113991. lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START
  113992. /**/) {
  113993. function strip(start, end) {
  113994. return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end);
  113995. }
  113996. var YYSTATE = YY_START;
  113997. switch ($avoiding_name_collisions) {
  113998. case 0:
  113999. if (yy_.yytext.slice(-2) === "\\\\") {
  114000. strip(0, 1);
  114001. this.begin("mu");
  114002. } else if (yy_.yytext.slice(-1) === "\\") {
  114003. strip(0, 1);
  114004. this.begin("emu");
  114005. } else {
  114006. this.begin("mu");
  114007. }
  114008. if (yy_.yytext) return 15;
  114009. break;
  114010. case 1:
  114011. return 15;
  114012. break;
  114013. case 2:
  114014. this.popState();
  114015. return 15;
  114016. break;
  114017. case 3:
  114018. this.begin('raw');return 15;
  114019. break;
  114020. case 4:
  114021. this.popState();
  114022. // Should be using `this.topState()` below, but it currently
  114023. // returns the second top instead of the first top. Opened an
  114024. // issue about it at https://github.com/zaach/jison/issues/291
  114025. if (this.conditionStack[this.conditionStack.length - 1] === 'raw') {
  114026. return 15;
  114027. } else {
  114028. yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9);
  114029. return 'END_RAW_BLOCK';
  114030. }
  114031. break;
  114032. case 5:
  114033. return 15;
  114034. break;
  114035. case 6:
  114036. this.popState();
  114037. return 14;
  114038. break;
  114039. case 7:
  114040. return 65;
  114041. break;
  114042. case 8:
  114043. return 68;
  114044. break;
  114045. case 9:
  114046. return 19;
  114047. break;
  114048. case 10:
  114049. this.popState();
  114050. this.begin('raw');
  114051. return 23;
  114052. break;
  114053. case 11:
  114054. return 55;
  114055. break;
  114056. case 12:
  114057. return 60;
  114058. break;
  114059. case 13:
  114060. return 29;
  114061. break;
  114062. case 14:
  114063. return 47;
  114064. break;
  114065. case 15:
  114066. this.popState();return 44;
  114067. break;
  114068. case 16:
  114069. this.popState();return 44;
  114070. break;
  114071. case 17:
  114072. return 34;
  114073. break;
  114074. case 18:
  114075. return 39;
  114076. break;
  114077. case 19:
  114078. return 51;
  114079. break;
  114080. case 20:
  114081. return 48;
  114082. break;
  114083. case 21:
  114084. this.unput(yy_.yytext);
  114085. this.popState();
  114086. this.begin('com');
  114087. break;
  114088. case 22:
  114089. this.popState();
  114090. return 14;
  114091. break;
  114092. case 23:
  114093. return 48;
  114094. break;
  114095. case 24:
  114096. return 73;
  114097. break;
  114098. case 25:
  114099. return 72;
  114100. break;
  114101. case 26:
  114102. return 72;
  114103. break;
  114104. case 27:
  114105. return 87;
  114106. break;
  114107. case 28:
  114108. // ignore whitespace
  114109. break;
  114110. case 29:
  114111. this.popState();return 54;
  114112. break;
  114113. case 30:
  114114. this.popState();return 33;
  114115. break;
  114116. case 31:
  114117. yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80;
  114118. break;
  114119. case 32:
  114120. yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80;
  114121. break;
  114122. case 33:
  114123. return 85;
  114124. break;
  114125. case 34:
  114126. return 82;
  114127. break;
  114128. case 35:
  114129. return 82;
  114130. break;
  114131. case 36:
  114132. return 83;
  114133. break;
  114134. case 37:
  114135. return 84;
  114136. break;
  114137. case 38:
  114138. return 81;
  114139. break;
  114140. case 39:
  114141. return 75;
  114142. break;
  114143. case 40:
  114144. return 77;
  114145. break;
  114146. case 41:
  114147. return 72;
  114148. break;
  114149. case 42:
  114150. yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72;
  114151. break;
  114152. case 43:
  114153. return 'INVALID';
  114154. break;
  114155. case 44:
  114156. return 5;
  114157. break;
  114158. }
  114159. };
  114160. 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\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
  114161. 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 } };
  114162. return lexer;
  114163. })();
  114164. parser.lexer = lexer;
  114165. function Parser() {
  114166. this.yy = {};
  114167. }Parser.prototype = parser;parser.Parser = Parser;
  114168. return new Parser();
  114169. })();exports["default"] = handlebars;
  114170. module.exports = exports["default"];
  114171. /***/ }),
  114172. /* 38 */
  114173. /***/ (function(module, exports, __webpack_require__) {
  114174. 'use strict';
  114175. var _interopRequireDefault = __webpack_require__(1)['default'];
  114176. exports.__esModule = true;
  114177. var _visitor = __webpack_require__(39);
  114178. var _visitor2 = _interopRequireDefault(_visitor);
  114179. function WhitespaceControl() {
  114180. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  114181. this.options = options;
  114182. }
  114183. WhitespaceControl.prototype = new _visitor2['default']();
  114184. WhitespaceControl.prototype.Program = function (program) {
  114185. var doStandalone = !this.options.ignoreStandalone;
  114186. var isRoot = !this.isRootSeen;
  114187. this.isRootSeen = true;
  114188. var body = program.body;
  114189. for (var i = 0, l = body.length; i < l; i++) {
  114190. var current = body[i],
  114191. strip = this.accept(current);
  114192. if (!strip) {
  114193. continue;
  114194. }
  114195. var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
  114196. _isNextWhitespace = isNextWhitespace(body, i, isRoot),
  114197. openStandalone = strip.openStandalone && _isPrevWhitespace,
  114198. closeStandalone = strip.closeStandalone && _isNextWhitespace,
  114199. inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
  114200. if (strip.close) {
  114201. omitRight(body, i, true);
  114202. }
  114203. if (strip.open) {
  114204. omitLeft(body, i, true);
  114205. }
  114206. if (doStandalone && inlineStandalone) {
  114207. omitRight(body, i);
  114208. if (omitLeft(body, i)) {
  114209. // If we are on a standalone node, save the indent info for partials
  114210. if (current.type === 'PartialStatement') {
  114211. // Pull out the whitespace from the final line
  114212. current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
  114213. }
  114214. }
  114215. }
  114216. if (doStandalone && openStandalone) {
  114217. omitRight((current.program || current.inverse).body);
  114218. // Strip out the previous content node if it's whitespace only
  114219. omitLeft(body, i);
  114220. }
  114221. if (doStandalone && closeStandalone) {
  114222. // Always strip the next node
  114223. omitRight(body, i);
  114224. omitLeft((current.inverse || current.program).body);
  114225. }
  114226. }
  114227. return program;
  114228. };
  114229. WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
  114230. this.accept(block.program);
  114231. this.accept(block.inverse);
  114232. // Find the inverse program that is involed with whitespace stripping.
  114233. var program = block.program || block.inverse,
  114234. inverse = block.program && block.inverse,
  114235. firstInverse = inverse,
  114236. lastInverse = inverse;
  114237. if (inverse && inverse.chained) {
  114238. firstInverse = inverse.body[0].program;
  114239. // Walk the inverse chain to find the last inverse that is actually in the chain.
  114240. while (lastInverse.chained) {
  114241. lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
  114242. }
  114243. }
  114244. var strip = {
  114245. open: block.openStrip.open,
  114246. close: block.closeStrip.close,
  114247. // Determine the standalone candiacy. Basically flag our content as being possibly standalone
  114248. // so our parent can determine if we actually are standalone
  114249. openStandalone: isNextWhitespace(program.body),
  114250. closeStandalone: isPrevWhitespace((firstInverse || program).body)
  114251. };
  114252. if (block.openStrip.close) {
  114253. omitRight(program.body, null, true);
  114254. }
  114255. if (inverse) {
  114256. var inverseStrip = block.inverseStrip;
  114257. if (inverseStrip.open) {
  114258. omitLeft(program.body, null, true);
  114259. }
  114260. if (inverseStrip.close) {
  114261. omitRight(firstInverse.body, null, true);
  114262. }
  114263. if (block.closeStrip.open) {
  114264. omitLeft(lastInverse.body, null, true);
  114265. }
  114266. // Find standalone else statments
  114267. if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
  114268. omitLeft(program.body);
  114269. omitRight(firstInverse.body);
  114270. }
  114271. } else if (block.closeStrip.open) {
  114272. omitLeft(program.body, null, true);
  114273. }
  114274. return strip;
  114275. };
  114276. WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
  114277. return mustache.strip;
  114278. };
  114279. WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
  114280. /* istanbul ignore next */
  114281. var strip = node.strip || {};
  114282. return {
  114283. inlineStandalone: true,
  114284. open: strip.open,
  114285. close: strip.close
  114286. };
  114287. };
  114288. function isPrevWhitespace(body, i, isRoot) {
  114289. if (i === undefined) {
  114290. i = body.length;
  114291. }
  114292. // Nodes that end with newlines are considered whitespace (but are special
  114293. // cased for strip operations)
  114294. var prev = body[i - 1],
  114295. sibling = body[i - 2];
  114296. if (!prev) {
  114297. return isRoot;
  114298. }
  114299. if (prev.type === 'ContentStatement') {
  114300. return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
  114301. }
  114302. }
  114303. function isNextWhitespace(body, i, isRoot) {
  114304. if (i === undefined) {
  114305. i = -1;
  114306. }
  114307. var next = body[i + 1],
  114308. sibling = body[i + 2];
  114309. if (!next) {
  114310. return isRoot;
  114311. }
  114312. if (next.type === 'ContentStatement') {
  114313. return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
  114314. }
  114315. }
  114316. // Marks the node to the right of the position as omitted.
  114317. // I.e. {{foo}}' ' will mark the ' ' node as omitted.
  114318. //
  114319. // If i is undefined, then the first child will be marked as such.
  114320. //
  114321. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  114322. // content is met.
  114323. function omitRight(body, i, multiple) {
  114324. var current = body[i == null ? 0 : i + 1];
  114325. if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
  114326. return;
  114327. }
  114328. var original = current.value;
  114329. current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
  114330. current.rightStripped = current.value !== original;
  114331. }
  114332. // Marks the node to the left of the position as omitted.
  114333. // I.e. ' '{{foo}} will mark the ' ' node as omitted.
  114334. //
  114335. // If i is undefined then the last child will be marked as such.
  114336. //
  114337. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  114338. // content is met.
  114339. function omitLeft(body, i, multiple) {
  114340. var current = body[i == null ? body.length - 1 : i - 1];
  114341. if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
  114342. return;
  114343. }
  114344. // We omit the last node if it's whitespace only and not preceeded by a non-content node.
  114345. var original = current.value;
  114346. current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
  114347. current.leftStripped = current.value !== original;
  114348. return current.leftStripped;
  114349. }
  114350. exports['default'] = WhitespaceControl;
  114351. module.exports = exports['default'];
  114352. /***/ }),
  114353. /* 39 */
  114354. /***/ (function(module, exports, __webpack_require__) {
  114355. 'use strict';
  114356. var _interopRequireDefault = __webpack_require__(1)['default'];
  114357. exports.__esModule = true;
  114358. var _exception = __webpack_require__(6);
  114359. var _exception2 = _interopRequireDefault(_exception);
  114360. function Visitor() {
  114361. this.parents = [];
  114362. }
  114363. Visitor.prototype = {
  114364. constructor: Visitor,
  114365. mutating: false,
  114366. // Visits a given value. If mutating, will replace the value if necessary.
  114367. acceptKey: function acceptKey(node, name) {
  114368. var value = this.accept(node[name]);
  114369. if (this.mutating) {
  114370. // Hacky sanity check: This may have a few false positives for type for the helper
  114371. // methods but will generally do the right thing without a lot of overhead.
  114372. if (value && !Visitor.prototype[value.type]) {
  114373. throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
  114374. }
  114375. node[name] = value;
  114376. }
  114377. },
  114378. // Performs an accept operation with added sanity check to ensure
  114379. // required keys are not removed.
  114380. acceptRequired: function acceptRequired(node, name) {
  114381. this.acceptKey(node, name);
  114382. if (!node[name]) {
  114383. throw new _exception2['default'](node.type + ' requires ' + name);
  114384. }
  114385. },
  114386. // Traverses a given array. If mutating, empty respnses will be removed
  114387. // for child elements.
  114388. acceptArray: function acceptArray(array) {
  114389. for (var i = 0, l = array.length; i < l; i++) {
  114390. this.acceptKey(array, i);
  114391. if (!array[i]) {
  114392. array.splice(i, 1);
  114393. i--;
  114394. l--;
  114395. }
  114396. }
  114397. },
  114398. accept: function accept(object) {
  114399. if (!object) {
  114400. return;
  114401. }
  114402. /* istanbul ignore next: Sanity code */
  114403. if (!this[object.type]) {
  114404. throw new _exception2['default']('Unknown type: ' + object.type, object);
  114405. }
  114406. if (this.current) {
  114407. this.parents.unshift(this.current);
  114408. }
  114409. this.current = object;
  114410. var ret = this[object.type](object);
  114411. this.current = this.parents.shift();
  114412. if (!this.mutating || ret) {
  114413. return ret;
  114414. } else if (ret !== false) {
  114415. return object;
  114416. }
  114417. },
  114418. Program: function Program(program) {
  114419. this.acceptArray(program.body);
  114420. },
  114421. MustacheStatement: visitSubExpression,
  114422. Decorator: visitSubExpression,
  114423. BlockStatement: visitBlock,
  114424. DecoratorBlock: visitBlock,
  114425. PartialStatement: visitPartial,
  114426. PartialBlockStatement: function PartialBlockStatement(partial) {
  114427. visitPartial.call(this, partial);
  114428. this.acceptKey(partial, 'program');
  114429. },
  114430. ContentStatement: function ContentStatement() /* content */{},
  114431. CommentStatement: function CommentStatement() /* comment */{},
  114432. SubExpression: visitSubExpression,
  114433. PathExpression: function PathExpression() /* path */{},
  114434. StringLiteral: function StringLiteral() /* string */{},
  114435. NumberLiteral: function NumberLiteral() /* number */{},
  114436. BooleanLiteral: function BooleanLiteral() /* bool */{},
  114437. UndefinedLiteral: function UndefinedLiteral() /* literal */{},
  114438. NullLiteral: function NullLiteral() /* literal */{},
  114439. Hash: function Hash(hash) {
  114440. this.acceptArray(hash.pairs);
  114441. },
  114442. HashPair: function HashPair(pair) {
  114443. this.acceptRequired(pair, 'value');
  114444. }
  114445. };
  114446. function visitSubExpression(mustache) {
  114447. this.acceptRequired(mustache, 'path');
  114448. this.acceptArray(mustache.params);
  114449. this.acceptKey(mustache, 'hash');
  114450. }
  114451. function visitBlock(block) {
  114452. visitSubExpression.call(this, block);
  114453. this.acceptKey(block, 'program');
  114454. this.acceptKey(block, 'inverse');
  114455. }
  114456. function visitPartial(partial) {
  114457. this.acceptRequired(partial, 'name');
  114458. this.acceptArray(partial.params);
  114459. this.acceptKey(partial, 'hash');
  114460. }
  114461. exports['default'] = Visitor;
  114462. module.exports = exports['default'];
  114463. /***/ }),
  114464. /* 40 */
  114465. /***/ (function(module, exports, __webpack_require__) {
  114466. 'use strict';
  114467. var _interopRequireDefault = __webpack_require__(1)['default'];
  114468. exports.__esModule = true;
  114469. exports.SourceLocation = SourceLocation;
  114470. exports.id = id;
  114471. exports.stripFlags = stripFlags;
  114472. exports.stripComment = stripComment;
  114473. exports.preparePath = preparePath;
  114474. exports.prepareMustache = prepareMustache;
  114475. exports.prepareRawBlock = prepareRawBlock;
  114476. exports.prepareBlock = prepareBlock;
  114477. exports.prepareProgram = prepareProgram;
  114478. exports.preparePartialBlock = preparePartialBlock;
  114479. var _exception = __webpack_require__(6);
  114480. var _exception2 = _interopRequireDefault(_exception);
  114481. function validateClose(open, close) {
  114482. close = close.path ? close.path.original : close;
  114483. if (open.path.original !== close) {
  114484. var errorNode = { loc: open.path.loc };
  114485. throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode);
  114486. }
  114487. }
  114488. function SourceLocation(source, locInfo) {
  114489. this.source = source;
  114490. this.start = {
  114491. line: locInfo.first_line,
  114492. column: locInfo.first_column
  114493. };
  114494. this.end = {
  114495. line: locInfo.last_line,
  114496. column: locInfo.last_column
  114497. };
  114498. }
  114499. function id(token) {
  114500. if (/^\[.*\]$/.test(token)) {
  114501. return token.substr(1, token.length - 2);
  114502. } else {
  114503. return token;
  114504. }
  114505. }
  114506. function stripFlags(open, close) {
  114507. return {
  114508. open: open.charAt(2) === '~',
  114509. close: close.charAt(close.length - 3) === '~'
  114510. };
  114511. }
  114512. function stripComment(comment) {
  114513. return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, '');
  114514. }
  114515. function preparePath(data, parts, loc) {
  114516. loc = this.locInfo(loc);
  114517. var original = data ? '@' : '',
  114518. dig = [],
  114519. depth = 0,
  114520. depthString = '';
  114521. for (var i = 0, l = parts.length; i < l; i++) {
  114522. var part = parts[i].part,
  114523. // If we have [] syntax then we do not treat path references as operators,
  114524. // i.e. foo.[this] resolves to approximately context.foo['this']
  114525. isLiteral = parts[i].original !== part;
  114526. original += (parts[i].separator || '') + part;
  114527. if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
  114528. if (dig.length > 0) {
  114529. throw new _exception2['default']('Invalid path: ' + original, { loc: loc });
  114530. } else if (part === '..') {
  114531. depth++;
  114532. depthString += '../';
  114533. }
  114534. } else {
  114535. dig.push(part);
  114536. }
  114537. }
  114538. return {
  114539. type: 'PathExpression',
  114540. data: data,
  114541. depth: depth,
  114542. parts: dig,
  114543. original: original,
  114544. loc: loc
  114545. };
  114546. }
  114547. function prepareMustache(path, params, hash, open, strip, locInfo) {
  114548. // Must use charAt to support IE pre-10
  114549. var escapeFlag = open.charAt(3) || open.charAt(2),
  114550. escaped = escapeFlag !== '{' && escapeFlag !== '&';
  114551. var decorator = /\*/.test(open);
  114552. return {
  114553. type: decorator ? 'Decorator' : 'MustacheStatement',
  114554. path: path,
  114555. params: params,
  114556. hash: hash,
  114557. escaped: escaped,
  114558. strip: strip,
  114559. loc: this.locInfo(locInfo)
  114560. };
  114561. }
  114562. function prepareRawBlock(openRawBlock, contents, close, locInfo) {
  114563. validateClose(openRawBlock, close);
  114564. locInfo = this.locInfo(locInfo);
  114565. var program = {
  114566. type: 'Program',
  114567. body: contents,
  114568. strip: {},
  114569. loc: locInfo
  114570. };
  114571. return {
  114572. type: 'BlockStatement',
  114573. path: openRawBlock.path,
  114574. params: openRawBlock.params,
  114575. hash: openRawBlock.hash,
  114576. program: program,
  114577. openStrip: {},
  114578. inverseStrip: {},
  114579. closeStrip: {},
  114580. loc: locInfo
  114581. };
  114582. }
  114583. function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
  114584. if (close && close.path) {
  114585. validateClose(openBlock, close);
  114586. }
  114587. var decorator = /\*/.test(openBlock.open);
  114588. program.blockParams = openBlock.blockParams;
  114589. var inverse = undefined,
  114590. inverseStrip = undefined;
  114591. if (inverseAndProgram) {
  114592. if (decorator) {
  114593. throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram);
  114594. }
  114595. if (inverseAndProgram.chain) {
  114596. inverseAndProgram.program.body[0].closeStrip = close.strip;
  114597. }
  114598. inverseStrip = inverseAndProgram.strip;
  114599. inverse = inverseAndProgram.program;
  114600. }
  114601. if (inverted) {
  114602. inverted = inverse;
  114603. inverse = program;
  114604. program = inverted;
  114605. }
  114606. return {
  114607. type: decorator ? 'DecoratorBlock' : 'BlockStatement',
  114608. path: openBlock.path,
  114609. params: openBlock.params,
  114610. hash: openBlock.hash,
  114611. program: program,
  114612. inverse: inverse,
  114613. openStrip: openBlock.strip,
  114614. inverseStrip: inverseStrip,
  114615. closeStrip: close && close.strip,
  114616. loc: this.locInfo(locInfo)
  114617. };
  114618. }
  114619. function prepareProgram(statements, loc) {
  114620. if (!loc && statements.length) {
  114621. var firstLoc = statements[0].loc,
  114622. lastLoc = statements[statements.length - 1].loc;
  114623. /* istanbul ignore else */
  114624. if (firstLoc && lastLoc) {
  114625. loc = {
  114626. source: firstLoc.source,
  114627. start: {
  114628. line: firstLoc.start.line,
  114629. column: firstLoc.start.column
  114630. },
  114631. end: {
  114632. line: lastLoc.end.line,
  114633. column: lastLoc.end.column
  114634. }
  114635. };
  114636. }
  114637. }
  114638. return {
  114639. type: 'Program',
  114640. body: statements,
  114641. strip: {},
  114642. loc: loc
  114643. };
  114644. }
  114645. function preparePartialBlock(open, program, close, locInfo) {
  114646. validateClose(open, close);
  114647. return {
  114648. type: 'PartialBlockStatement',
  114649. name: open.path,
  114650. params: open.params,
  114651. hash: open.hash,
  114652. program: program,
  114653. openStrip: open.strip,
  114654. closeStrip: close && close.strip,
  114655. loc: this.locInfo(locInfo)
  114656. };
  114657. }
  114658. /***/ }),
  114659. /* 41 */
  114660. /***/ (function(module, exports, __webpack_require__) {
  114661. /* eslint-disable new-cap */
  114662. 'use strict';
  114663. var _interopRequireDefault = __webpack_require__(1)['default'];
  114664. exports.__esModule = true;
  114665. exports.Compiler = Compiler;
  114666. exports.precompile = precompile;
  114667. exports.compile = compile;
  114668. var _exception = __webpack_require__(6);
  114669. var _exception2 = _interopRequireDefault(_exception);
  114670. var _utils = __webpack_require__(5);
  114671. var _ast = __webpack_require__(35);
  114672. var _ast2 = _interopRequireDefault(_ast);
  114673. var slice = [].slice;
  114674. function Compiler() {}
  114675. // the foundHelper register will disambiguate helper lookup from finding a
  114676. // function in a context. This is necessary for mustache compatibility, which
  114677. // requires that context functions in blocks are evaluated by blockHelperMissing,
  114678. // and then proceed as if the resulting value was provided to blockHelperMissing.
  114679. Compiler.prototype = {
  114680. compiler: Compiler,
  114681. equals: function equals(other) {
  114682. var len = this.opcodes.length;
  114683. if (other.opcodes.length !== len) {
  114684. return false;
  114685. }
  114686. for (var i = 0; i < len; i++) {
  114687. var opcode = this.opcodes[i],
  114688. otherOpcode = other.opcodes[i];
  114689. if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
  114690. return false;
  114691. }
  114692. }
  114693. // We know that length is the same between the two arrays because they are directly tied
  114694. // to the opcode behavior above.
  114695. len = this.children.length;
  114696. for (var i = 0; i < len; i++) {
  114697. if (!this.children[i].equals(other.children[i])) {
  114698. return false;
  114699. }
  114700. }
  114701. return true;
  114702. },
  114703. guid: 0,
  114704. compile: function compile(program, options) {
  114705. this.sourceNode = [];
  114706. this.opcodes = [];
  114707. this.children = [];
  114708. this.options = options;
  114709. this.stringParams = options.stringParams;
  114710. this.trackIds = options.trackIds;
  114711. options.blockParams = options.blockParams || [];
  114712. // These changes will propagate to the other compiler components
  114713. var knownHelpers = options.knownHelpers;
  114714. options.knownHelpers = {
  114715. 'helperMissing': true,
  114716. 'blockHelperMissing': true,
  114717. 'each': true,
  114718. 'if': true,
  114719. 'unless': true,
  114720. 'with': true,
  114721. 'log': true,
  114722. 'lookup': true
  114723. };
  114724. if (knownHelpers) {
  114725. for (var _name in knownHelpers) {
  114726. /* istanbul ignore else */
  114727. if (_name in knownHelpers) {
  114728. this.options.knownHelpers[_name] = knownHelpers[_name];
  114729. }
  114730. }
  114731. }
  114732. return this.accept(program);
  114733. },
  114734. compileProgram: function compileProgram(program) {
  114735. var childCompiler = new this.compiler(),
  114736. // eslint-disable-line new-cap
  114737. result = childCompiler.compile(program, this.options),
  114738. guid = this.guid++;
  114739. this.usePartial = this.usePartial || result.usePartial;
  114740. this.children[guid] = result;
  114741. this.useDepths = this.useDepths || result.useDepths;
  114742. return guid;
  114743. },
  114744. accept: function accept(node) {
  114745. /* istanbul ignore next: Sanity code */
  114746. if (!this[node.type]) {
  114747. throw new _exception2['default']('Unknown type: ' + node.type, node);
  114748. }
  114749. this.sourceNode.unshift(node);
  114750. var ret = this[node.type](node);
  114751. this.sourceNode.shift();
  114752. return ret;
  114753. },
  114754. Program: function Program(program) {
  114755. this.options.blockParams.unshift(program.blockParams);
  114756. var body = program.body,
  114757. bodyLength = body.length;
  114758. for (var i = 0; i < bodyLength; i++) {
  114759. this.accept(body[i]);
  114760. }
  114761. this.options.blockParams.shift();
  114762. this.isSimple = bodyLength === 1;
  114763. this.blockParams = program.blockParams ? program.blockParams.length : 0;
  114764. return this;
  114765. },
  114766. BlockStatement: function BlockStatement(block) {
  114767. transformLiteralToPath(block);
  114768. var program = block.program,
  114769. inverse = block.inverse;
  114770. program = program && this.compileProgram(program);
  114771. inverse = inverse && this.compileProgram(inverse);
  114772. var type = this.classifySexpr(block);
  114773. if (type === 'helper') {
  114774. this.helperSexpr(block, program, inverse);
  114775. } else if (type === 'simple') {
  114776. this.simpleSexpr(block);
  114777. // now that the simple mustache is resolved, we need to
  114778. // evaluate it by executing `blockHelperMissing`
  114779. this.opcode('pushProgram', program);
  114780. this.opcode('pushProgram', inverse);
  114781. this.opcode('emptyHash');
  114782. this.opcode('blockValue', block.path.original);
  114783. } else {
  114784. this.ambiguousSexpr(block, program, inverse);
  114785. // now that the simple mustache is resolved, we need to
  114786. // evaluate it by executing `blockHelperMissing`
  114787. this.opcode('pushProgram', program);
  114788. this.opcode('pushProgram', inverse);
  114789. this.opcode('emptyHash');
  114790. this.opcode('ambiguousBlockValue');
  114791. }
  114792. this.opcode('append');
  114793. },
  114794. DecoratorBlock: function DecoratorBlock(decorator) {
  114795. var program = decorator.program && this.compileProgram(decorator.program);
  114796. var params = this.setupFullMustacheParams(decorator, program, undefined),
  114797. path = decorator.path;
  114798. this.useDecorators = true;
  114799. this.opcode('registerDecorator', params.length, path.original);
  114800. },
  114801. PartialStatement: function PartialStatement(partial) {
  114802. this.usePartial = true;
  114803. var program = partial.program;
  114804. if (program) {
  114805. program = this.compileProgram(partial.program);
  114806. }
  114807. var params = partial.params;
  114808. if (params.length > 1) {
  114809. throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial);
  114810. } else if (!params.length) {
  114811. if (this.options.explicitPartialContext) {
  114812. this.opcode('pushLiteral', 'undefined');
  114813. } else {
  114814. params.push({ type: 'PathExpression', parts: [], depth: 0 });
  114815. }
  114816. }
  114817. var partialName = partial.name.original,
  114818. isDynamic = partial.name.type === 'SubExpression';
  114819. if (isDynamic) {
  114820. this.accept(partial.name);
  114821. }
  114822. this.setupFullMustacheParams(partial, program, undefined, true);
  114823. var indent = partial.indent || '';
  114824. if (this.options.preventIndent && indent) {
  114825. this.opcode('appendContent', indent);
  114826. indent = '';
  114827. }
  114828. this.opcode('invokePartial', isDynamic, partialName, indent);
  114829. this.opcode('append');
  114830. },
  114831. PartialBlockStatement: function PartialBlockStatement(partialBlock) {
  114832. this.PartialStatement(partialBlock);
  114833. },
  114834. MustacheStatement: function MustacheStatement(mustache) {
  114835. this.SubExpression(mustache);
  114836. if (mustache.escaped && !this.options.noEscape) {
  114837. this.opcode('appendEscaped');
  114838. } else {
  114839. this.opcode('append');
  114840. }
  114841. },
  114842. Decorator: function Decorator(decorator) {
  114843. this.DecoratorBlock(decorator);
  114844. },
  114845. ContentStatement: function ContentStatement(content) {
  114846. if (content.value) {
  114847. this.opcode('appendContent', content.value);
  114848. }
  114849. },
  114850. CommentStatement: function CommentStatement() {},
  114851. SubExpression: function SubExpression(sexpr) {
  114852. transformLiteralToPath(sexpr);
  114853. var type = this.classifySexpr(sexpr);
  114854. if (type === 'simple') {
  114855. this.simpleSexpr(sexpr);
  114856. } else if (type === 'helper') {
  114857. this.helperSexpr(sexpr);
  114858. } else {
  114859. this.ambiguousSexpr(sexpr);
  114860. }
  114861. },
  114862. ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
  114863. var path = sexpr.path,
  114864. name = path.parts[0],
  114865. isBlock = program != null || inverse != null;
  114866. this.opcode('getContext', path.depth);
  114867. this.opcode('pushProgram', program);
  114868. this.opcode('pushProgram', inverse);
  114869. path.strict = true;
  114870. this.accept(path);
  114871. this.opcode('invokeAmbiguous', name, isBlock);
  114872. },
  114873. simpleSexpr: function simpleSexpr(sexpr) {
  114874. var path = sexpr.path;
  114875. path.strict = true;
  114876. this.accept(path);
  114877. this.opcode('resolvePossibleLambda');
  114878. },
  114879. helperSexpr: function helperSexpr(sexpr, program, inverse) {
  114880. var params = this.setupFullMustacheParams(sexpr, program, inverse),
  114881. path = sexpr.path,
  114882. name = path.parts[0];
  114883. if (this.options.knownHelpers[name]) {
  114884. this.opcode('invokeKnownHelper', params.length, name);
  114885. } else if (this.options.knownHelpersOnly) {
  114886. throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
  114887. } else {
  114888. path.strict = true;
  114889. path.falsy = true;
  114890. this.accept(path);
  114891. this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path));
  114892. }
  114893. },
  114894. PathExpression: function PathExpression(path) {
  114895. this.addDepth(path.depth);
  114896. this.opcode('getContext', path.depth);
  114897. var name = path.parts[0],
  114898. scoped = _ast2['default'].helpers.scopedId(path),
  114899. blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
  114900. if (blockParamId) {
  114901. this.opcode('lookupBlockParam', blockParamId, path.parts);
  114902. } else if (!name) {
  114903. // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
  114904. this.opcode('pushContext');
  114905. } else if (path.data) {
  114906. this.options.data = true;
  114907. this.opcode('lookupData', path.depth, path.parts, path.strict);
  114908. } else {
  114909. this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
  114910. }
  114911. },
  114912. StringLiteral: function StringLiteral(string) {
  114913. this.opcode('pushString', string.value);
  114914. },
  114915. NumberLiteral: function NumberLiteral(number) {
  114916. this.opcode('pushLiteral', number.value);
  114917. },
  114918. BooleanLiteral: function BooleanLiteral(bool) {
  114919. this.opcode('pushLiteral', bool.value);
  114920. },
  114921. UndefinedLiteral: function UndefinedLiteral() {
  114922. this.opcode('pushLiteral', 'undefined');
  114923. },
  114924. NullLiteral: function NullLiteral() {
  114925. this.opcode('pushLiteral', 'null');
  114926. },
  114927. Hash: function Hash(hash) {
  114928. var pairs = hash.pairs,
  114929. i = 0,
  114930. l = pairs.length;
  114931. this.opcode('pushHash');
  114932. for (; i < l; i++) {
  114933. this.pushParam(pairs[i].value);
  114934. }
  114935. while (i--) {
  114936. this.opcode('assignToHash', pairs[i].key);
  114937. }
  114938. this.opcode('popHash');
  114939. },
  114940. // HELPERS
  114941. opcode: function opcode(name) {
  114942. this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
  114943. },
  114944. addDepth: function addDepth(depth) {
  114945. if (!depth) {
  114946. return;
  114947. }
  114948. this.useDepths = true;
  114949. },
  114950. classifySexpr: function classifySexpr(sexpr) {
  114951. var isSimple = _ast2['default'].helpers.simpleId(sexpr.path);
  114952. var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
  114953. // a mustache is an eligible helper if:
  114954. // * its id is simple (a single part, not `this` or `..`)
  114955. var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr);
  114956. // if a mustache is an eligible helper but not a definite
  114957. // helper, it is ambiguous, and will be resolved in a later
  114958. // pass or at runtime.
  114959. var isEligible = !isBlockParam && (isHelper || isSimple);
  114960. // if ambiguous, we can possibly resolve the ambiguity now
  114961. // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
  114962. if (isEligible && !isHelper) {
  114963. var _name2 = sexpr.path.parts[0],
  114964. options = this.options;
  114965. if (options.knownHelpers[_name2]) {
  114966. isHelper = true;
  114967. } else if (options.knownHelpersOnly) {
  114968. isEligible = false;
  114969. }
  114970. }
  114971. if (isHelper) {
  114972. return 'helper';
  114973. } else if (isEligible) {
  114974. return 'ambiguous';
  114975. } else {
  114976. return 'simple';
  114977. }
  114978. },
  114979. pushParams: function pushParams(params) {
  114980. for (var i = 0, l = params.length; i < l; i++) {
  114981. this.pushParam(params[i]);
  114982. }
  114983. },
  114984. pushParam: function pushParam(val) {
  114985. var value = val.value != null ? val.value : val.original || '';
  114986. if (this.stringParams) {
  114987. if (value.replace) {
  114988. value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
  114989. }
  114990. if (val.depth) {
  114991. this.addDepth(val.depth);
  114992. }
  114993. this.opcode('getContext', val.depth || 0);
  114994. this.opcode('pushStringParam', value, val.type);
  114995. if (val.type === 'SubExpression') {
  114996. // SubExpressions get evaluated and passed in
  114997. // in string params mode.
  114998. this.accept(val);
  114999. }
  115000. } else {
  115001. if (this.trackIds) {
  115002. var blockParamIndex = undefined;
  115003. if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) {
  115004. blockParamIndex = this.blockParamIndex(val.parts[0]);
  115005. }
  115006. if (blockParamIndex) {
  115007. var blockParamChild = val.parts.slice(1).join('.');
  115008. this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
  115009. } else {
  115010. value = val.original || value;
  115011. if (value.replace) {
  115012. value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, '');
  115013. }
  115014. this.opcode('pushId', val.type, value);
  115015. }
  115016. }
  115017. this.accept(val);
  115018. }
  115019. },
  115020. setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
  115021. var params = sexpr.params;
  115022. this.pushParams(params);
  115023. this.opcode('pushProgram', program);
  115024. this.opcode('pushProgram', inverse);
  115025. if (sexpr.hash) {
  115026. this.accept(sexpr.hash);
  115027. } else {
  115028. this.opcode('emptyHash', omitEmpty);
  115029. }
  115030. return params;
  115031. },
  115032. blockParamIndex: function blockParamIndex(name) {
  115033. for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
  115034. var blockParams = this.options.blockParams[depth],
  115035. param = blockParams && _utils.indexOf(blockParams, name);
  115036. if (blockParams && param >= 0) {
  115037. return [depth, param];
  115038. }
  115039. }
  115040. }
  115041. };
  115042. function precompile(input, options, env) {
  115043. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  115044. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
  115045. }
  115046. options = options || {};
  115047. if (!('data' in options)) {
  115048. options.data = true;
  115049. }
  115050. if (options.compat) {
  115051. options.useDepths = true;
  115052. }
  115053. var ast = env.parse(input, options),
  115054. environment = new env.Compiler().compile(ast, options);
  115055. return new env.JavaScriptCompiler().compile(environment, options);
  115056. }
  115057. function compile(input, options, env) {
  115058. if (options === undefined) options = {};
  115059. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  115060. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
  115061. }
  115062. options = _utils.extend({}, options);
  115063. if (!('data' in options)) {
  115064. options.data = true;
  115065. }
  115066. if (options.compat) {
  115067. options.useDepths = true;
  115068. }
  115069. var compiled = undefined;
  115070. function compileInput() {
  115071. var ast = env.parse(input, options),
  115072. environment = new env.Compiler().compile(ast, options),
  115073. templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
  115074. return env.template(templateSpec);
  115075. }
  115076. // Template is only compiled on first use and cached after that point.
  115077. function ret(context, execOptions) {
  115078. if (!compiled) {
  115079. compiled = compileInput();
  115080. }
  115081. return compiled.call(this, context, execOptions);
  115082. }
  115083. ret._setup = function (setupOptions) {
  115084. if (!compiled) {
  115085. compiled = compileInput();
  115086. }
  115087. return compiled._setup(setupOptions);
  115088. };
  115089. ret._child = function (i, data, blockParams, depths) {
  115090. if (!compiled) {
  115091. compiled = compileInput();
  115092. }
  115093. return compiled._child(i, data, blockParams, depths);
  115094. };
  115095. return ret;
  115096. }
  115097. function argEquals(a, b) {
  115098. if (a === b) {
  115099. return true;
  115100. }
  115101. if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
  115102. for (var i = 0; i < a.length; i++) {
  115103. if (!argEquals(a[i], b[i])) {
  115104. return false;
  115105. }
  115106. }
  115107. return true;
  115108. }
  115109. }
  115110. function transformLiteralToPath(sexpr) {
  115111. if (!sexpr.path.parts) {
  115112. var literal = sexpr.path;
  115113. // Casting to string here to make false and 0 literal values play nicely with the rest
  115114. // of the system.
  115115. sexpr.path = {
  115116. type: 'PathExpression',
  115117. data: false,
  115118. depth: 0,
  115119. parts: [literal.original + ''],
  115120. original: literal.original + '',
  115121. loc: literal.loc
  115122. };
  115123. }
  115124. }
  115125. /***/ }),
  115126. /* 42 */
  115127. /***/ (function(module, exports, __webpack_require__) {
  115128. 'use strict';
  115129. var _interopRequireDefault = __webpack_require__(1)['default'];
  115130. exports.__esModule = true;
  115131. var _base = __webpack_require__(4);
  115132. var _exception = __webpack_require__(6);
  115133. var _exception2 = _interopRequireDefault(_exception);
  115134. var _utils = __webpack_require__(5);
  115135. var _codeGen = __webpack_require__(43);
  115136. var _codeGen2 = _interopRequireDefault(_codeGen);
  115137. function Literal(value) {
  115138. this.value = value;
  115139. }
  115140. function JavaScriptCompiler() {}
  115141. JavaScriptCompiler.prototype = {
  115142. // PUBLIC API: You can override these methods in a subclass to provide
  115143. // alternative compiled forms for name lookup and buffering semantics
  115144. nameLookup: function nameLookup(parent, name /* , type*/) {
  115145. if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
  115146. return [parent, '.', name];
  115147. } else {
  115148. return [parent, '[', JSON.stringify(name), ']'];
  115149. }
  115150. },
  115151. depthedLookup: function depthedLookup(name) {
  115152. return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
  115153. },
  115154. compilerInfo: function compilerInfo() {
  115155. var revision = _base.COMPILER_REVISION,
  115156. versions = _base.REVISION_CHANGES[revision];
  115157. return [revision, versions];
  115158. },
  115159. appendToBuffer: function appendToBuffer(source, location, explicit) {
  115160. // Force a source as this simplifies the merge logic.
  115161. if (!_utils.isArray(source)) {
  115162. source = [source];
  115163. }
  115164. source = this.source.wrap(source, location);
  115165. if (this.environment.isSimple) {
  115166. return ['return ', source, ';'];
  115167. } else if (explicit) {
  115168. // This is a case where the buffer operation occurs as a child of another
  115169. // construct, generally braces. We have to explicitly output these buffer
  115170. // operations to ensure that the emitted code goes in the correct location.
  115171. return ['buffer += ', source, ';'];
  115172. } else {
  115173. source.appendToBuffer = true;
  115174. return source;
  115175. }
  115176. },
  115177. initializeBuffer: function initializeBuffer() {
  115178. return this.quotedString('');
  115179. },
  115180. // END PUBLIC API
  115181. compile: function compile(environment, options, context, asObject) {
  115182. this.environment = environment;
  115183. this.options = options;
  115184. this.stringParams = this.options.stringParams;
  115185. this.trackIds = this.options.trackIds;
  115186. this.precompile = !asObject;
  115187. this.name = this.environment.name;
  115188. this.isChild = !!context;
  115189. this.context = context || {
  115190. decorators: [],
  115191. programs: [],
  115192. environments: []
  115193. };
  115194. this.preamble();
  115195. this.stackSlot = 0;
  115196. this.stackVars = [];
  115197. this.aliases = {};
  115198. this.registers = { list: [] };
  115199. this.hashes = [];
  115200. this.compileStack = [];
  115201. this.inlineStack = [];
  115202. this.blockParams = [];
  115203. this.compileChildren(environment, options);
  115204. this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
  115205. this.useBlockParams = this.useBlockParams || environment.useBlockParams;
  115206. var opcodes = environment.opcodes,
  115207. opcode = undefined,
  115208. firstLoc = undefined,
  115209. i = undefined,
  115210. l = undefined;
  115211. for (i = 0, l = opcodes.length; i < l; i++) {
  115212. opcode = opcodes[i];
  115213. this.source.currentLocation = opcode.loc;
  115214. firstLoc = firstLoc || opcode.loc;
  115215. this[opcode.opcode].apply(this, opcode.args);
  115216. }
  115217. // Flush any trailing content that might be pending.
  115218. this.source.currentLocation = firstLoc;
  115219. this.pushSource('');
  115220. /* istanbul ignore next */
  115221. if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
  115222. throw new _exception2['default']('Compile completed with content left on stack');
  115223. }
  115224. if (!this.decorators.isEmpty()) {
  115225. this.useDecorators = true;
  115226. this.decorators.prepend('var decorators = container.decorators;\n');
  115227. this.decorators.push('return fn;');
  115228. if (asObject) {
  115229. this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
  115230. } else {
  115231. this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
  115232. this.decorators.push('}\n');
  115233. this.decorators = this.decorators.merge();
  115234. }
  115235. } else {
  115236. this.decorators = undefined;
  115237. }
  115238. var fn = this.createFunctionContext(asObject);
  115239. if (!this.isChild) {
  115240. var ret = {
  115241. compiler: this.compilerInfo(),
  115242. main: fn
  115243. };
  115244. if (this.decorators) {
  115245. ret.main_d = this.decorators; // eslint-disable-line camelcase
  115246. ret.useDecorators = true;
  115247. }
  115248. var _context = this.context;
  115249. var programs = _context.programs;
  115250. var decorators = _context.decorators;
  115251. for (i = 0, l = programs.length; i < l; i++) {
  115252. if (programs[i]) {
  115253. ret[i] = programs[i];
  115254. if (decorators[i]) {
  115255. ret[i + '_d'] = decorators[i];
  115256. ret.useDecorators = true;
  115257. }
  115258. }
  115259. }
  115260. if (this.environment.usePartial) {
  115261. ret.usePartial = true;
  115262. }
  115263. if (this.options.data) {
  115264. ret.useData = true;
  115265. }
  115266. if (this.useDepths) {
  115267. ret.useDepths = true;
  115268. }
  115269. if (this.useBlockParams) {
  115270. ret.useBlockParams = true;
  115271. }
  115272. if (this.options.compat) {
  115273. ret.compat = true;
  115274. }
  115275. if (!asObject) {
  115276. ret.compiler = JSON.stringify(ret.compiler);
  115277. this.source.currentLocation = { start: { line: 1, column: 0 } };
  115278. ret = this.objectLiteral(ret);
  115279. if (options.srcName) {
  115280. ret = ret.toStringWithSourceMap({ file: options.destName });
  115281. ret.map = ret.map && ret.map.toString();
  115282. } else {
  115283. ret = ret.toString();
  115284. }
  115285. } else {
  115286. ret.compilerOptions = this.options;
  115287. }
  115288. return ret;
  115289. } else {
  115290. return fn;
  115291. }
  115292. },
  115293. preamble: function preamble() {
  115294. // track the last context pushed into place to allow skipping the
  115295. // getContext opcode when it would be a noop
  115296. this.lastContext = 0;
  115297. this.source = new _codeGen2['default'](this.options.srcName);
  115298. this.decorators = new _codeGen2['default'](this.options.srcName);
  115299. },
  115300. createFunctionContext: function createFunctionContext(asObject) {
  115301. var varDeclarations = '';
  115302. var locals = this.stackVars.concat(this.registers.list);
  115303. if (locals.length > 0) {
  115304. varDeclarations += ', ' + locals.join(', ');
  115305. }
  115306. // Generate minimizer alias mappings
  115307. //
  115308. // When using true SourceNodes, this will update all references to the given alias
  115309. // as the source nodes are reused in situ. For the non-source node compilation mode,
  115310. // aliases will not be used, but this case is already being run on the client and
  115311. // we aren't concern about minimizing the template size.
  115312. var aliasCount = 0;
  115313. for (var alias in this.aliases) {
  115314. // eslint-disable-line guard-for-in
  115315. var node = this.aliases[alias];
  115316. if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) {
  115317. varDeclarations += ', alias' + ++aliasCount + '=' + alias;
  115318. node.children[0] = 'alias' + aliasCount;
  115319. }
  115320. }
  115321. var params = ['container', 'depth0', 'helpers', 'partials', 'data'];
  115322. if (this.useBlockParams || this.useDepths) {
  115323. params.push('blockParams');
  115324. }
  115325. if (this.useDepths) {
  115326. params.push('depths');
  115327. }
  115328. // Perform a second pass over the output to merge content when possible
  115329. var source = this.mergeSource(varDeclarations);
  115330. if (asObject) {
  115331. params.push(source);
  115332. return Function.apply(this, params);
  115333. } else {
  115334. return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']);
  115335. }
  115336. },
  115337. mergeSource: function mergeSource(varDeclarations) {
  115338. var isSimple = this.environment.isSimple,
  115339. appendOnly = !this.forceBuffer,
  115340. appendFirst = undefined,
  115341. sourceSeen = undefined,
  115342. bufferStart = undefined,
  115343. bufferEnd = undefined;
  115344. this.source.each(function (line) {
  115345. if (line.appendToBuffer) {
  115346. if (bufferStart) {
  115347. line.prepend(' + ');
  115348. } else {
  115349. bufferStart = line;
  115350. }
  115351. bufferEnd = line;
  115352. } else {
  115353. if (bufferStart) {
  115354. if (!sourceSeen) {
  115355. appendFirst = true;
  115356. } else {
  115357. bufferStart.prepend('buffer += ');
  115358. }
  115359. bufferEnd.add(';');
  115360. bufferStart = bufferEnd = undefined;
  115361. }
  115362. sourceSeen = true;
  115363. if (!isSimple) {
  115364. appendOnly = false;
  115365. }
  115366. }
  115367. });
  115368. if (appendOnly) {
  115369. if (bufferStart) {
  115370. bufferStart.prepend('return ');
  115371. bufferEnd.add(';');
  115372. } else if (!sourceSeen) {
  115373. this.source.push('return "";');
  115374. }
  115375. } else {
  115376. varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
  115377. if (bufferStart) {
  115378. bufferStart.prepend('return buffer + ');
  115379. bufferEnd.add(';');
  115380. } else {
  115381. this.source.push('return buffer;');
  115382. }
  115383. }
  115384. if (varDeclarations) {
  115385. this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
  115386. }
  115387. return this.source.merge();
  115388. },
  115389. // [blockValue]
  115390. //
  115391. // On stack, before: hash, inverse, program, value
  115392. // On stack, after: return value of blockHelperMissing
  115393. //
  115394. // The purpose of this opcode is to take a block of the form
  115395. // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
  115396. // replace it on the stack with the result of properly
  115397. // invoking blockHelperMissing.
  115398. blockValue: function blockValue(name) {
  115399. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  115400. params = [this.contextName(0)];
  115401. this.setupHelperArgs(name, 0, params);
  115402. var blockName = this.popStack();
  115403. params.splice(1, 0, blockName);
  115404. this.push(this.source.functionCall(blockHelperMissing, 'call', params));
  115405. },
  115406. // [ambiguousBlockValue]
  115407. //
  115408. // On stack, before: hash, inverse, program, value
  115409. // Compiler value, before: lastHelper=value of last found helper, if any
  115410. // On stack, after, if no lastHelper: same as [blockValue]
  115411. // On stack, after, if lastHelper: value
  115412. ambiguousBlockValue: function ambiguousBlockValue() {
  115413. // We're being a bit cheeky and reusing the options value from the prior exec
  115414. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  115415. params = [this.contextName(0)];
  115416. this.setupHelperArgs('', 0, params, true);
  115417. this.flushInline();
  115418. var current = this.topStack();
  115419. params.splice(1, 0, current);
  115420. this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']);
  115421. },
  115422. // [appendContent]
  115423. //
  115424. // On stack, before: ...
  115425. // On stack, after: ...
  115426. //
  115427. // Appends the string value of `content` to the current buffer
  115428. appendContent: function appendContent(content) {
  115429. if (this.pendingContent) {
  115430. content = this.pendingContent + content;
  115431. } else {
  115432. this.pendingLocation = this.source.currentLocation;
  115433. }
  115434. this.pendingContent = content;
  115435. },
  115436. // [append]
  115437. //
  115438. // On stack, before: value, ...
  115439. // On stack, after: ...
  115440. //
  115441. // Coerces `value` to a String and appends it to the current buffer.
  115442. //
  115443. // If `value` is truthy, or 0, it is coerced into a string and appended
  115444. // Otherwise, the empty string is appended
  115445. append: function append() {
  115446. if (this.isInline()) {
  115447. this.replaceStack(function (current) {
  115448. return [' != null ? ', current, ' : ""'];
  115449. });
  115450. this.pushSource(this.appendToBuffer(this.popStack()));
  115451. } else {
  115452. var local = this.popStack();
  115453. this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
  115454. if (this.environment.isSimple) {
  115455. this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
  115456. }
  115457. }
  115458. },
  115459. // [appendEscaped]
  115460. //
  115461. // On stack, before: value, ...
  115462. // On stack, after: ...
  115463. //
  115464. // Escape `value` and append it to the buffer
  115465. appendEscaped: function appendEscaped() {
  115466. this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
  115467. },
  115468. // [getContext]
  115469. //
  115470. // On stack, before: ...
  115471. // On stack, after: ...
  115472. // Compiler value, after: lastContext=depth
  115473. //
  115474. // Set the value of the `lastContext` compiler value to the depth
  115475. getContext: function getContext(depth) {
  115476. this.lastContext = depth;
  115477. },
  115478. // [pushContext]
  115479. //
  115480. // On stack, before: ...
  115481. // On stack, after: currentContext, ...
  115482. //
  115483. // Pushes the value of the current context onto the stack.
  115484. pushContext: function pushContext() {
  115485. this.pushStackLiteral(this.contextName(this.lastContext));
  115486. },
  115487. // [lookupOnContext]
  115488. //
  115489. // On stack, before: ...
  115490. // On stack, after: currentContext[name], ...
  115491. //
  115492. // Looks up the value of `name` on the current context and pushes
  115493. // it onto the stack.
  115494. lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
  115495. var i = 0;
  115496. if (!scoped && this.options.compat && !this.lastContext) {
  115497. // The depthed query is expected to handle the undefined logic for the root level that
  115498. // is implemented below, so we evaluate that directly in compat mode
  115499. this.push(this.depthedLookup(parts[i++]));
  115500. } else {
  115501. this.pushContext();
  115502. }
  115503. this.resolvePath('context', parts, i, falsy, strict);
  115504. },
  115505. // [lookupBlockParam]
  115506. //
  115507. // On stack, before: ...
  115508. // On stack, after: blockParam[name], ...
  115509. //
  115510. // Looks up the value of `parts` on the given block param and pushes
  115511. // it onto the stack.
  115512. lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
  115513. this.useBlockParams = true;
  115514. this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);
  115515. this.resolvePath('context', parts, 1);
  115516. },
  115517. // [lookupData]
  115518. //
  115519. // On stack, before: ...
  115520. // On stack, after: data, ...
  115521. //
  115522. // Push the data lookup operator
  115523. lookupData: function lookupData(depth, parts, strict) {
  115524. if (!depth) {
  115525. this.pushStackLiteral('data');
  115526. } else {
  115527. this.pushStackLiteral('container.data(data, ' + depth + ')');
  115528. }
  115529. this.resolvePath('data', parts, 0, true, strict);
  115530. },
  115531. resolvePath: function resolvePath(type, parts, i, falsy, strict) {
  115532. // istanbul ignore next
  115533. var _this = this;
  115534. if (this.options.strict || this.options.assumeObjects) {
  115535. this.push(strictLookup(this.options.strict && strict, this, parts, type));
  115536. return;
  115537. }
  115538. var len = parts.length;
  115539. for (; i < len; i++) {
  115540. /* eslint-disable no-loop-func */
  115541. this.replaceStack(function (current) {
  115542. var lookup = _this.nameLookup(current, parts[i], type);
  115543. // We want to ensure that zero and false are handled properly if the context (falsy flag)
  115544. // needs to have the special handling for these values.
  115545. if (!falsy) {
  115546. return [' != null ? ', lookup, ' : ', current];
  115547. } else {
  115548. // Otherwise we can use generic falsy handling
  115549. return [' && ', lookup];
  115550. }
  115551. });
  115552. /* eslint-enable no-loop-func */
  115553. }
  115554. },
  115555. // [resolvePossibleLambda]
  115556. //
  115557. // On stack, before: value, ...
  115558. // On stack, after: resolved value, ...
  115559. //
  115560. // If the `value` is a lambda, replace it on the stack by
  115561. // the return value of the lambda
  115562. resolvePossibleLambda: function resolvePossibleLambda() {
  115563. this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
  115564. },
  115565. // [pushStringParam]
  115566. //
  115567. // On stack, before: ...
  115568. // On stack, after: string, currentContext, ...
  115569. //
  115570. // This opcode is designed for use in string mode, which
  115571. // provides the string value of a parameter along with its
  115572. // depth rather than resolving it immediately.
  115573. pushStringParam: function pushStringParam(string, type) {
  115574. this.pushContext();
  115575. this.pushString(type);
  115576. // If it's a subexpression, the string result
  115577. // will be pushed after this opcode.
  115578. if (type !== 'SubExpression') {
  115579. if (typeof string === 'string') {
  115580. this.pushString(string);
  115581. } else {
  115582. this.pushStackLiteral(string);
  115583. }
  115584. }
  115585. },
  115586. emptyHash: function emptyHash(omitEmpty) {
  115587. if (this.trackIds) {
  115588. this.push('{}'); // hashIds
  115589. }
  115590. if (this.stringParams) {
  115591. this.push('{}'); // hashContexts
  115592. this.push('{}'); // hashTypes
  115593. }
  115594. this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');
  115595. },
  115596. pushHash: function pushHash() {
  115597. if (this.hash) {
  115598. this.hashes.push(this.hash);
  115599. }
  115600. this.hash = { values: [], types: [], contexts: [], ids: [] };
  115601. },
  115602. popHash: function popHash() {
  115603. var hash = this.hash;
  115604. this.hash = this.hashes.pop();
  115605. if (this.trackIds) {
  115606. this.push(this.objectLiteral(hash.ids));
  115607. }
  115608. if (this.stringParams) {
  115609. this.push(this.objectLiteral(hash.contexts));
  115610. this.push(this.objectLiteral(hash.types));
  115611. }
  115612. this.push(this.objectLiteral(hash.values));
  115613. },
  115614. // [pushString]
  115615. //
  115616. // On stack, before: ...
  115617. // On stack, after: quotedString(string), ...
  115618. //
  115619. // Push a quoted version of `string` onto the stack
  115620. pushString: function pushString(string) {
  115621. this.pushStackLiteral(this.quotedString(string));
  115622. },
  115623. // [pushLiteral]
  115624. //
  115625. // On stack, before: ...
  115626. // On stack, after: value, ...
  115627. //
  115628. // Pushes a value onto the stack. This operation prevents
  115629. // the compiler from creating a temporary variable to hold
  115630. // it.
  115631. pushLiteral: function pushLiteral(value) {
  115632. this.pushStackLiteral(value);
  115633. },
  115634. // [pushProgram]
  115635. //
  115636. // On stack, before: ...
  115637. // On stack, after: program(guid), ...
  115638. //
  115639. // Push a program expression onto the stack. This takes
  115640. // a compile-time guid and converts it into a runtime-accessible
  115641. // expression.
  115642. pushProgram: function pushProgram(guid) {
  115643. if (guid != null) {
  115644. this.pushStackLiteral(this.programExpression(guid));
  115645. } else {
  115646. this.pushStackLiteral(null);
  115647. }
  115648. },
  115649. // [registerDecorator]
  115650. //
  115651. // On stack, before: hash, program, params..., ...
  115652. // On stack, after: ...
  115653. //
  115654. // Pops off the decorator's parameters, invokes the decorator,
  115655. // and inserts the decorator into the decorators list.
  115656. registerDecorator: function registerDecorator(paramSize, name) {
  115657. var foundDecorator = this.nameLookup('decorators', name, 'decorator'),
  115658. options = this.setupHelperArgs(name, paramSize);
  115659. this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']);
  115660. },
  115661. // [invokeHelper]
  115662. //
  115663. // On stack, before: hash, inverse, program, params..., ...
  115664. // On stack, after: result of helper invocation
  115665. //
  115666. // Pops off the helper's parameters, invokes the helper,
  115667. // and pushes the helper's return value onto the stack.
  115668. //
  115669. // If the helper is not found, `helperMissing` is called.
  115670. invokeHelper: function invokeHelper(paramSize, name, isSimple) {
  115671. var nonHelper = this.popStack(),
  115672. helper = this.setupHelper(paramSize, name),
  115673. simple = isSimple ? [helper.name, ' || '] : '';
  115674. var lookup = ['('].concat(simple, nonHelper);
  115675. if (!this.options.strict) {
  115676. lookup.push(' || ', this.aliasable('helpers.helperMissing'));
  115677. }
  115678. lookup.push(')');
  115679. this.push(this.source.functionCall(lookup, 'call', helper.callParams));
  115680. },
  115681. // [invokeKnownHelper]
  115682. //
  115683. // On stack, before: hash, inverse, program, params..., ...
  115684. // On stack, after: result of helper invocation
  115685. //
  115686. // This operation is used when the helper is known to exist,
  115687. // so a `helperMissing` fallback is not required.
  115688. invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
  115689. var helper = this.setupHelper(paramSize, name);
  115690. this.push(this.source.functionCall(helper.name, 'call', helper.callParams));
  115691. },
  115692. // [invokeAmbiguous]
  115693. //
  115694. // On stack, before: hash, inverse, program, params..., ...
  115695. // On stack, after: result of disambiguation
  115696. //
  115697. // This operation is used when an expression like `{{foo}}`
  115698. // is provided, but we don't know at compile-time whether it
  115699. // is a helper or a path.
  115700. //
  115701. // This operation emits more code than the other options,
  115702. // and can be avoided by passing the `knownHelpers` and
  115703. // `knownHelpersOnly` flags at compile-time.
  115704. invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
  115705. this.useRegister('helper');
  115706. var nonHelper = this.popStack();
  115707. this.emptyHash();
  115708. var helper = this.setupHelper(0, name, helperCall);
  115709. var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
  115710. var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
  115711. if (!this.options.strict) {
  115712. lookup[0] = '(helper = ';
  115713. lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing'));
  115714. }
  115715. this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']);
  115716. },
  115717. // [invokePartial]
  115718. //
  115719. // On stack, before: context, ...
  115720. // On stack after: result of partial invocation
  115721. //
  115722. // This operation pops off a context, invokes a partial with that context,
  115723. // and pushes the result of the invocation back.
  115724. invokePartial: function invokePartial(isDynamic, name, indent) {
  115725. var params = [],
  115726. options = this.setupParams(name, 1, params);
  115727. if (isDynamic) {
  115728. name = this.popStack();
  115729. delete options.name;
  115730. }
  115731. if (indent) {
  115732. options.indent = JSON.stringify(indent);
  115733. }
  115734. options.helpers = 'helpers';
  115735. options.partials = 'partials';
  115736. options.decorators = 'container.decorators';
  115737. if (!isDynamic) {
  115738. params.unshift(this.nameLookup('partials', name, 'partial'));
  115739. } else {
  115740. params.unshift(name);
  115741. }
  115742. if (this.options.compat) {
  115743. options.depths = 'depths';
  115744. }
  115745. options = this.objectLiteral(options);
  115746. params.push(options);
  115747. this.push(this.source.functionCall('container.invokePartial', '', params));
  115748. },
  115749. // [assignToHash]
  115750. //
  115751. // On stack, before: value, ..., hash, ...
  115752. // On stack, after: ..., hash, ...
  115753. //
  115754. // Pops a value off the stack and assigns it to the current hash
  115755. assignToHash: function assignToHash(key) {
  115756. var value = this.popStack(),
  115757. context = undefined,
  115758. type = undefined,
  115759. id = undefined;
  115760. if (this.trackIds) {
  115761. id = this.popStack();
  115762. }
  115763. if (this.stringParams) {
  115764. type = this.popStack();
  115765. context = this.popStack();
  115766. }
  115767. var hash = this.hash;
  115768. if (context) {
  115769. hash.contexts[key] = context;
  115770. }
  115771. if (type) {
  115772. hash.types[key] = type;
  115773. }
  115774. if (id) {
  115775. hash.ids[key] = id;
  115776. }
  115777. hash.values[key] = value;
  115778. },
  115779. pushId: function pushId(type, name, child) {
  115780. if (type === 'BlockParam') {
  115781. this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : ''));
  115782. } else if (type === 'PathExpression') {
  115783. this.pushString(name);
  115784. } else if (type === 'SubExpression') {
  115785. this.pushStackLiteral('true');
  115786. } else {
  115787. this.pushStackLiteral('null');
  115788. }
  115789. },
  115790. // HELPERS
  115791. compiler: JavaScriptCompiler,
  115792. compileChildren: function compileChildren(environment, options) {
  115793. var children = environment.children,
  115794. child = undefined,
  115795. compiler = undefined;
  115796. for (var i = 0, l = children.length; i < l; i++) {
  115797. child = children[i];
  115798. compiler = new this.compiler(); // eslint-disable-line new-cap
  115799. var existing = this.matchExistingProgram(child);
  115800. if (existing == null) {
  115801. this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
  115802. var index = this.context.programs.length;
  115803. child.index = index;
  115804. child.name = 'program' + index;
  115805. this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
  115806. this.context.decorators[index] = compiler.decorators;
  115807. this.context.environments[index] = child;
  115808. this.useDepths = this.useDepths || compiler.useDepths;
  115809. this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
  115810. child.useDepths = this.useDepths;
  115811. child.useBlockParams = this.useBlockParams;
  115812. } else {
  115813. child.index = existing.index;
  115814. child.name = 'program' + existing.index;
  115815. this.useDepths = this.useDepths || existing.useDepths;
  115816. this.useBlockParams = this.useBlockParams || existing.useBlockParams;
  115817. }
  115818. }
  115819. },
  115820. matchExistingProgram: function matchExistingProgram(child) {
  115821. for (var i = 0, len = this.context.environments.length; i < len; i++) {
  115822. var environment = this.context.environments[i];
  115823. if (environment && environment.equals(child)) {
  115824. return environment;
  115825. }
  115826. }
  115827. },
  115828. programExpression: function programExpression(guid) {
  115829. var child = this.environment.children[guid],
  115830. programParams = [child.index, 'data', child.blockParams];
  115831. if (this.useBlockParams || this.useDepths) {
  115832. programParams.push('blockParams');
  115833. }
  115834. if (this.useDepths) {
  115835. programParams.push('depths');
  115836. }
  115837. return 'container.program(' + programParams.join(', ') + ')';
  115838. },
  115839. useRegister: function useRegister(name) {
  115840. if (!this.registers[name]) {
  115841. this.registers[name] = true;
  115842. this.registers.list.push(name);
  115843. }
  115844. },
  115845. push: function push(expr) {
  115846. if (!(expr instanceof Literal)) {
  115847. expr = this.source.wrap(expr);
  115848. }
  115849. this.inlineStack.push(expr);
  115850. return expr;
  115851. },
  115852. pushStackLiteral: function pushStackLiteral(item) {
  115853. this.push(new Literal(item));
  115854. },
  115855. pushSource: function pushSource(source) {
  115856. if (this.pendingContent) {
  115857. this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
  115858. this.pendingContent = undefined;
  115859. }
  115860. if (source) {
  115861. this.source.push(source);
  115862. }
  115863. },
  115864. replaceStack: function replaceStack(callback) {
  115865. var prefix = ['('],
  115866. stack = undefined,
  115867. createdStack = undefined,
  115868. usedLiteral = undefined;
  115869. /* istanbul ignore next */
  115870. if (!this.isInline()) {
  115871. throw new _exception2['default']('replaceStack on non-inline');
  115872. }
  115873. // We want to merge the inline statement into the replacement statement via ','
  115874. var top = this.popStack(true);
  115875. if (top instanceof Literal) {
  115876. // Literals do not need to be inlined
  115877. stack = [top.value];
  115878. prefix = ['(', stack];
  115879. usedLiteral = true;
  115880. } else {
  115881. // Get or create the current stack name for use by the inline
  115882. createdStack = true;
  115883. var _name = this.incrStack();
  115884. prefix = ['((', this.push(_name), ' = ', top, ')'];
  115885. stack = this.topStack();
  115886. }
  115887. var item = callback.call(this, stack);
  115888. if (!usedLiteral) {
  115889. this.popStack();
  115890. }
  115891. if (createdStack) {
  115892. this.stackSlot--;
  115893. }
  115894. this.push(prefix.concat(item, ')'));
  115895. },
  115896. incrStack: function incrStack() {
  115897. this.stackSlot++;
  115898. if (this.stackSlot > this.stackVars.length) {
  115899. this.stackVars.push('stack' + this.stackSlot);
  115900. }
  115901. return this.topStackName();
  115902. },
  115903. topStackName: function topStackName() {
  115904. return 'stack' + this.stackSlot;
  115905. },
  115906. flushInline: function flushInline() {
  115907. var inlineStack = this.inlineStack;
  115908. this.inlineStack = [];
  115909. for (var i = 0, len = inlineStack.length; i < len; i++) {
  115910. var entry = inlineStack[i];
  115911. /* istanbul ignore if */
  115912. if (entry instanceof Literal) {
  115913. this.compileStack.push(entry);
  115914. } else {
  115915. var stack = this.incrStack();
  115916. this.pushSource([stack, ' = ', entry, ';']);
  115917. this.compileStack.push(stack);
  115918. }
  115919. }
  115920. },
  115921. isInline: function isInline() {
  115922. return this.inlineStack.length;
  115923. },
  115924. popStack: function popStack(wrapped) {
  115925. var inline = this.isInline(),
  115926. item = (inline ? this.inlineStack : this.compileStack).pop();
  115927. if (!wrapped && item instanceof Literal) {
  115928. return item.value;
  115929. } else {
  115930. if (!inline) {
  115931. /* istanbul ignore next */
  115932. if (!this.stackSlot) {
  115933. throw new _exception2['default']('Invalid stack pop');
  115934. }
  115935. this.stackSlot--;
  115936. }
  115937. return item;
  115938. }
  115939. },
  115940. topStack: function topStack() {
  115941. var stack = this.isInline() ? this.inlineStack : this.compileStack,
  115942. item = stack[stack.length - 1];
  115943. /* istanbul ignore if */
  115944. if (item instanceof Literal) {
  115945. return item.value;
  115946. } else {
  115947. return item;
  115948. }
  115949. },
  115950. contextName: function contextName(context) {
  115951. if (this.useDepths && context) {
  115952. return 'depths[' + context + ']';
  115953. } else {
  115954. return 'depth' + context;
  115955. }
  115956. },
  115957. quotedString: function quotedString(str) {
  115958. return this.source.quotedString(str);
  115959. },
  115960. objectLiteral: function objectLiteral(obj) {
  115961. return this.source.objectLiteral(obj);
  115962. },
  115963. aliasable: function aliasable(name) {
  115964. var ret = this.aliases[name];
  115965. if (ret) {
  115966. ret.referenceCount++;
  115967. return ret;
  115968. }
  115969. ret = this.aliases[name] = this.source.wrap(name);
  115970. ret.aliasable = true;
  115971. ret.referenceCount = 1;
  115972. return ret;
  115973. },
  115974. setupHelper: function setupHelper(paramSize, name, blockHelper) {
  115975. var params = [],
  115976. paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
  115977. var foundHelper = this.nameLookup('helpers', name, 'helper'),
  115978. callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : (container.nullContext || {})');
  115979. return {
  115980. params: params,
  115981. paramsInit: paramsInit,
  115982. name: foundHelper,
  115983. callParams: [callContext].concat(params)
  115984. };
  115985. },
  115986. setupParams: function setupParams(helper, paramSize, params) {
  115987. var options = {},
  115988. contexts = [],
  115989. types = [],
  115990. ids = [],
  115991. objectArgs = !params,
  115992. param = undefined;
  115993. if (objectArgs) {
  115994. params = [];
  115995. }
  115996. options.name = this.quotedString(helper);
  115997. options.hash = this.popStack();
  115998. if (this.trackIds) {
  115999. options.hashIds = this.popStack();
  116000. }
  116001. if (this.stringParams) {
  116002. options.hashTypes = this.popStack();
  116003. options.hashContexts = this.popStack();
  116004. }
  116005. var inverse = this.popStack(),
  116006. program = this.popStack();
  116007. // Avoid setting fn and inverse if neither are set. This allows
  116008. // helpers to do a check for `if (options.fn)`
  116009. if (program || inverse) {
  116010. options.fn = program || 'container.noop';
  116011. options.inverse = inverse || 'container.noop';
  116012. }
  116013. // The parameters go on to the stack in order (making sure that they are evaluated in order)
  116014. // so we need to pop them off the stack in reverse order
  116015. var i = paramSize;
  116016. while (i--) {
  116017. param = this.popStack();
  116018. params[i] = param;
  116019. if (this.trackIds) {
  116020. ids[i] = this.popStack();
  116021. }
  116022. if (this.stringParams) {
  116023. types[i] = this.popStack();
  116024. contexts[i] = this.popStack();
  116025. }
  116026. }
  116027. if (objectArgs) {
  116028. options.args = this.source.generateArray(params);
  116029. }
  116030. if (this.trackIds) {
  116031. options.ids = this.source.generateArray(ids);
  116032. }
  116033. if (this.stringParams) {
  116034. options.types = this.source.generateArray(types);
  116035. options.contexts = this.source.generateArray(contexts);
  116036. }
  116037. if (this.options.data) {
  116038. options.data = 'data';
  116039. }
  116040. if (this.useBlockParams) {
  116041. options.blockParams = 'blockParams';
  116042. }
  116043. return options;
  116044. },
  116045. setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
  116046. var options = this.setupParams(helper, paramSize, params);
  116047. options = this.objectLiteral(options);
  116048. if (useRegister) {
  116049. this.useRegister('options');
  116050. params.push('options');
  116051. return ['options=', options];
  116052. } else if (params) {
  116053. params.push(options);
  116054. return '';
  116055. } else {
  116056. return options;
  116057. }
  116058. }
  116059. };
  116060. (function () {
  116061. 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(' ');
  116062. var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
  116063. for (var i = 0, l = reservedWords.length; i < l; i++) {
  116064. compilerWords[reservedWords[i]] = true;
  116065. }
  116066. })();
  116067. JavaScriptCompiler.isValidJavaScriptVariableName = function (name) {
  116068. return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
  116069. };
  116070. function strictLookup(requireTerminal, compiler, parts, type) {
  116071. var stack = compiler.popStack(),
  116072. i = 0,
  116073. len = parts.length;
  116074. if (requireTerminal) {
  116075. len--;
  116076. }
  116077. for (; i < len; i++) {
  116078. stack = compiler.nameLookup(stack, parts[i], type);
  116079. }
  116080. if (requireTerminal) {
  116081. return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')'];
  116082. } else {
  116083. return stack;
  116084. }
  116085. }
  116086. exports['default'] = JavaScriptCompiler;
  116087. module.exports = exports['default'];
  116088. /***/ }),
  116089. /* 43 */
  116090. /***/ (function(module, exports, __webpack_require__) {
  116091. /* global define */
  116092. 'use strict';
  116093. exports.__esModule = true;
  116094. var _utils = __webpack_require__(5);
  116095. var SourceNode = undefined;
  116096. try {
  116097. /* istanbul ignore next */
  116098. if (false) {
  116099. // We don't support this in AMD environments. For these environments, we asusme that
  116100. // they are running on the browser and thus have no need for the source-map library.
  116101. var SourceMap = require('source-map');
  116102. SourceNode = SourceMap.SourceNode;
  116103. }
  116104. } catch (err) {}
  116105. /* NOP */
  116106. /* istanbul ignore if: tested but not covered in istanbul due to dist build */
  116107. if (!SourceNode) {
  116108. SourceNode = function (line, column, srcFile, chunks) {
  116109. this.src = '';
  116110. if (chunks) {
  116111. this.add(chunks);
  116112. }
  116113. };
  116114. /* istanbul ignore next */
  116115. SourceNode.prototype = {
  116116. add: function add(chunks) {
  116117. if (_utils.isArray(chunks)) {
  116118. chunks = chunks.join('');
  116119. }
  116120. this.src += chunks;
  116121. },
  116122. prepend: function prepend(chunks) {
  116123. if (_utils.isArray(chunks)) {
  116124. chunks = chunks.join('');
  116125. }
  116126. this.src = chunks + this.src;
  116127. },
  116128. toStringWithSourceMap: function toStringWithSourceMap() {
  116129. return { code: this.toString() };
  116130. },
  116131. toString: function toString() {
  116132. return this.src;
  116133. }
  116134. };
  116135. }
  116136. function castChunk(chunk, codeGen, loc) {
  116137. if (_utils.isArray(chunk)) {
  116138. var ret = [];
  116139. for (var i = 0, len = chunk.length; i < len; i++) {
  116140. ret.push(codeGen.wrap(chunk[i], loc));
  116141. }
  116142. return ret;
  116143. } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
  116144. // Handle primitives that the SourceNode will throw up on
  116145. return chunk + '';
  116146. }
  116147. return chunk;
  116148. }
  116149. function CodeGen(srcFile) {
  116150. this.srcFile = srcFile;
  116151. this.source = [];
  116152. }
  116153. CodeGen.prototype = {
  116154. isEmpty: function isEmpty() {
  116155. return !this.source.length;
  116156. },
  116157. prepend: function prepend(source, loc) {
  116158. this.source.unshift(this.wrap(source, loc));
  116159. },
  116160. push: function push(source, loc) {
  116161. this.source.push(this.wrap(source, loc));
  116162. },
  116163. merge: function merge() {
  116164. var source = this.empty();
  116165. this.each(function (line) {
  116166. source.add([' ', line, '\n']);
  116167. });
  116168. return source;
  116169. },
  116170. each: function each(iter) {
  116171. for (var i = 0, len = this.source.length; i < len; i++) {
  116172. iter(this.source[i]);
  116173. }
  116174. },
  116175. empty: function empty() {
  116176. var loc = this.currentLocation || { start: {} };
  116177. return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
  116178. },
  116179. wrap: function wrap(chunk) {
  116180. var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1];
  116181. if (chunk instanceof SourceNode) {
  116182. return chunk;
  116183. }
  116184. chunk = castChunk(chunk, this, loc);
  116185. return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
  116186. },
  116187. functionCall: function functionCall(fn, type, params) {
  116188. params = this.generateList(params);
  116189. return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
  116190. },
  116191. quotedString: function quotedString(str) {
  116192. 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
  116193. .replace(/\u2029/g, '\\u2029') + '"';
  116194. },
  116195. objectLiteral: function objectLiteral(obj) {
  116196. var pairs = [];
  116197. for (var key in obj) {
  116198. if (obj.hasOwnProperty(key)) {
  116199. var value = castChunk(obj[key], this);
  116200. if (value !== 'undefined') {
  116201. pairs.push([this.quotedString(key), ':', value]);
  116202. }
  116203. }
  116204. }
  116205. var ret = this.generateList(pairs);
  116206. ret.prepend('{');
  116207. ret.add('}');
  116208. return ret;
  116209. },
  116210. generateList: function generateList(entries) {
  116211. var ret = this.empty();
  116212. for (var i = 0, len = entries.length; i < len; i++) {
  116213. if (i) {
  116214. ret.add(',');
  116215. }
  116216. ret.add(castChunk(entries[i], this));
  116217. }
  116218. return ret;
  116219. },
  116220. generateArray: function generateArray(entries) {
  116221. var ret = this.generateList(entries);
  116222. ret.prepend('[');
  116223. ret.add(']');
  116224. return ret;
  116225. }
  116226. };
  116227. exports['default'] = CodeGen;
  116228. module.exports = exports['default'];
  116229. /***/ })
  116230. /******/ ])
  116231. });
  116232. ;
  116233. /***/ }),
  116234. /* 16 */
  116235. /***/ (function(module, exports, __webpack_require__) {
  116236. "use strict";
  116237. Object.defineProperty(exports, "__esModule", { value: true });
  116238. var Handlebars = __webpack_require__(15);
  116239. var AbstractViewerNavbarButton = /** @class */ (function () {
  116240. function AbstractViewerNavbarButton() {
  116241. this.templateName = "navBar";
  116242. this.eventsToAttach = ['pointerdown'];
  116243. this._prepend = true;
  116244. }
  116245. AbstractViewerNavbarButton.prototype.interactionPredicate = function (event) {
  116246. var pointerDown = event.event;
  116247. if (pointerDown.button !== 0)
  116248. return false;
  116249. var element = event.event.target;
  116250. if (!element) {
  116251. return false;
  116252. }
  116253. var elementClasses = element.classList;
  116254. for (var i = 0; i < elementClasses.length; ++i) {
  116255. var className = elementClasses[i];
  116256. if (className.indexOf(this._buttonClass) !== -1) {
  116257. return true;
  116258. }
  116259. }
  116260. return false;
  116261. };
  116262. AbstractViewerNavbarButton.prototype.addHTMLTemplate = function (template) {
  116263. var element = this._generateHTMLElement(template);
  116264. var container = template.parent.querySelector("div.default-control");
  116265. if (container) {
  116266. if (this._prepend) {
  116267. container.insertBefore(element, container.firstChild);
  116268. }
  116269. else {
  116270. container.appendChild(element);
  116271. }
  116272. }
  116273. };
  116274. AbstractViewerNavbarButton.prototype._generateHTMLElement = function (template) {
  116275. var compiledTemplate = Handlebars.compile(this._htmlTemplate, { noEscape: (template.configuration.params && !!template.configuration.params.noEscape) });
  116276. var config = template.configuration.params || {};
  116277. var rawHtml = compiledTemplate(config);
  116278. var fragment;
  116279. try {
  116280. fragment = document.createRange().createContextualFragment(rawHtml);
  116281. }
  116282. catch (e) {
  116283. var test = document.createElement(this._buttonClass);
  116284. test.innerHTML = rawHtml;
  116285. fragment = test;
  116286. }
  116287. return fragment;
  116288. };
  116289. return AbstractViewerNavbarButton;
  116290. }());
  116291. exports.AbstractViewerNavbarButton = AbstractViewerNavbarButton;
  116292. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyVGVtcGxhdGVQbHVnaW4uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvdGVtcGxhdGluZy92aWV3ZXJUZW1wbGF0ZVBsdWdpbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVEQUF5RDtBQVl6RDtJQUFBO1FBRW9CLGlCQUFZLEdBQVcsUUFBUSxDQUFDO1FBQ2hDLG1CQUFjLEdBQWtCLENBQUMsYUFBYSxDQUFDLENBQUM7UUFDdEQsYUFBUSxHQUFZLElBQUksQ0FBQztJQW9EdkMsQ0FBQztJQWhERyx5REFBb0IsR0FBcEIsVUFBcUIsS0FBb0I7UUFDckMsSUFBSSxXQUFXLEdBQWlCLEtBQUssQ0FBQyxLQUFLLENBQUM7UUFDNUMsSUFBSSxXQUFXLENBQUMsTUFBTSxLQUFLLENBQUM7WUFBRSxPQUFPLEtBQUssQ0FBQztRQUMzQyxJQUFJLE9BQU8sR0FBaUIsS0FBSyxDQUFDLEtBQUssQ0FBQyxNQUFPLENBQUM7UUFFaEQsSUFBSSxDQUFDLE9BQU8sRUFBRTtZQUNWLE9BQU8sS0FBSyxDQUFDO1NBQ2hCO1FBRUQsSUFBSSxjQUFjLEdBQUcsT0FBTyxDQUFDLFNBQVMsQ0FBQztRQUV2QyxLQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEdBQUcsY0FBYyxDQU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UFRLENBQUMsYUFBYSxDQUFDLE1BQU0sSUFBSSxFQUFFLENBQUM7UUFDakQsSUFBSSxPQUFPLEdBQUcsZ0JBQWdCLENBQUMsTUFBTSxDQUFDLENBQUM7UUFDdkMsSUFBSSxRQUFvQyxDQUFDO1FBQ3pDLElBQUk7WUFDQSxRQUFRLEdBQUcsUUFBUSxDQUFDLFdBQVcsRUFBRSxDQUFDLHdCQUF3QixDQUFDLE9BQU8sQ0FBQyxDQUFDO1NBQ3ZFO1FBQUMsT0FBTyxDQUFDLEVBQUU7WUFDUixJQUFJLElBQUksR0FBRyxRQUFRLENBQUMsYUFBYSxDQUFDLElBQUksQ0FBQyxZQUFZLENBQUMsQ0FBQztZQUNyRCxJQUFJLENBQUMsU0FBUyxHQUFHLE9BQU8sQ0FBQztZQUN6QixRQUFRLEdBQUcsSUFBSSxDQUFDO1NBQ25CO1FBQ0QsT0FBTyxRQUFRLENBQUM7SUFDcEIsQ0FBQztJQUNMLGlDQUFDO0FBQUQsQ0FBQyxBQXhERCxJQXdEQztBQXhEcUIsZ0VBQTBCIn0=
  116293. /***/ }),
  116294. /* 17 */
  116295. /***/ (function(module, exports, __webpack_require__) {
  116296. module.exports = __webpack_require__(18);
  116297. /***/ }),
  116298. /* 18 */
  116299. /***/ (function(module, exports, __webpack_require__) {
  116300. "use strict";
  116301. function __export(m) {
  116302. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  116303. }
  116304. Object.defineProperty(exports, "__esModule", { value: true });
  116305. var mappers_1 = __webpack_require__(3);
  116306. exports.mapperManager = mappers_1.mapperManager;
  116307. var globals_1 = __webpack_require__(4);
  116308. exports.viewerGlobals = globals_1.viewerGlobals;
  116309. var viewerManager_1 = __webpack_require__(7);
  116310. exports.viewerManager = viewerManager_1.viewerManager;
  116311. var defaultViewer_1 = __webpack_require__(8);
  116312. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  116313. var viewer_1 = __webpack_require__(9);
  116314. exports.AbstractViewer = viewer_1.AbstractViewer;
  116315. var telemetryManager_1 = __webpack_require__(6);
  116316. exports.telemetryManager = telemetryManager_1.telemetryManager;
  116317. var modelLoader_1 = __webpack_require__(13);
  116318. exports.ModelLoader = modelLoader_1.ModelLoader;
  116319. var viewerModel_1 = __webpack_require__(5);
  116320. exports.ViewerModel = viewerModel_1.ViewerModel;
  116321. exports.ModelState = viewerModel_1.ModelState;
  116322. var viewerTemplatePlugin_1 = __webpack_require__(16);
  116323. exports.AbstractViewerNavbarButton = viewerTemplatePlugin_1.AbstractViewerNavbarButton;
  116324. /**
  116325. * BabylonJS Viewer
  116326. *
  116327. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  116328. */
  116329. var BABYLON = __webpack_require__(0);
  116330. exports.BABYLON = BABYLON;
  116331. // load needed modules.
  116332. __webpack_require__(14);
  116333. __webpack_require__(66);
  116334. var initializer_1 = __webpack_require__(67);
  116335. exports.InitTags = initializer_1.InitTags;
  116336. // promise polyfill, if needed!
  116337. BABYLON.PromisePolyfill.Apply();
  116338. initializer_1.initListeners();
  116339. //deprectaed, here for backwards compatibility
  116340. var disableInit = globals_1.viewerGlobals.disableInit;
  116341. exports.disableInit = disableInit;
  116342. /**
  116343. * Dispose all viewers currently registered
  116344. */
  116345. function disposeAll() {
  116346. viewerManager_1.viewerManager.dispose();
  116347. mappers_1.mapperManager.dispose();
  116348. telemetryManager_1.telemetryManager.dispose();
  116349. }
  116350. exports.disposeAll = disposeAll;
  116351. var Version = globals_1.viewerGlobals.version;
  116352. exports.Version = Version;
  116353. console.log("Babylon.js viewer (v" + Version + ")");
  116354. // export publicliy all configuration interfaces
  116355. __export(__webpack_require__(10));
  116356. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7QUFBQ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9CLENBQUM7QUFPK0ksZ0NBQVU7QUFMMUosSUFBTSxPQUFPLEdBQUcsdUJBQWEsQ0FBQyxPQUFPLENBQUM7QUFLcEIsMEJBQU87QUFIekIsT0FBTyxDQUFDLEdBQUcsQ0FBQyxzQkFBc0IsR0FBRyxPQUFPLEdBQUcsR0FBRyxDQUFDLENBQUM7QUFJcEQsZ0RBQWdEO0FBQ2hELHFDQUFnQyJ9
  116357. /***/ }),
  116358. /* 19 */
  116359. /***/ (function(module, exports) {
  116360. var g;
  116361. // This works in non-strict mode
  116362. g = (function() {
  116363. return this;
  116364. })();
  116365. try {
  116366. // This works if eval is allowed (see CSP)
  116367. g = g || Function("return this")() || (1,eval)("this");
  116368. } catch(e) {
  116369. // This works if the window reference is available
  116370. if(typeof window === "object")
  116371. g = window;
  116372. }
  116373. // g can still be undefined, but nothing to do about it...
  116374. // We return undefined, instead of nothing here, so it's
  116375. // easier to handle this case. if(!global) { ...}
  116376. module.exports = g;
  116377. /***/ }),
  116378. /* 20 */
  116379. /***/ (function(module, exports) {
  116380. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  116381. module.exports = CANNON;
  116382. /***/ }),
  116383. /* 21 */
  116384. /***/ (function(module, exports) {
  116385. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  116386. module.exports = OIMO;
  116387. /***/ }),
  116388. /* 22 */
  116389. /***/ (function(module, exports) {
  116390. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  116391. module.exports = earcut;
  116392. /***/ }),
  116393. /* 23 */
  116394. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  116395. "use strict";
  116396. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  116397. var isMergeableObject = function isMergeableObject(value) {
  116398. return isNonNullObject(value)
  116399. && !isSpecial(value)
  116400. };
  116401. function isNonNullObject(value) {
  116402. return !!value && typeof value === 'object'
  116403. }
  116404. function isSpecial(value) {
  116405. var stringValue = Object.prototype.toString.call(value);
  116406. return stringValue === '[object RegExp]'
  116407. || stringValue === '[object Date]'
  116408. || isReactElement(value)
  116409. }
  116410. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  116411. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  116412. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  116413. function isReactElement(value) {
  116414. return value.$$typeof === REACT_ELEMENT_TYPE
  116415. }
  116416. function emptyTarget(val) {
  116417. return Array.isArray(val) ? [] : {}
  116418. }
  116419. function cloneUnlessOtherwiseSpecified(value, options) {
  116420. return (options.clone !== false && options.isMergeableObject(value))
  116421. ? deepmerge(emptyTarget(value), value, options)
  116422. : value
  116423. }
  116424. function defaultArrayMerge(target, source, options) {
  116425. return target.concat(source).map(function(element) {
  116426. return cloneUnlessOtherwiseSpecified(element, options)
  116427. })
  116428. }
  116429. function mergeObject(target, source, options) {
  116430. var destination = {};
  116431. if (options.isMergeableObject(target)) {
  116432. Object.keys(target).forEach(function(key) {
  116433. destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
  116434. });
  116435. }
  116436. Object.keys(source).forEach(function(key) {
  116437. if (!options.isMergeableObject(source[key]) || !target[key]) {
  116438. destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
  116439. } else {
  116440. destination[key] = deepmerge(target[key], source[key], options);
  116441. }
  116442. });
  116443. return destination
  116444. }
  116445. function deepmerge(target, source, options) {
  116446. options = options || {};
  116447. options.arrayMerge = options.arrayMerge || defaultArrayMerge;
  116448. options.isMergeableObject = options.isMergeableObject || isMergeableObject;
  116449. var sourceIsArray = Array.isArray(source);
  116450. var targetIsArray = Array.isArray(target);
  116451. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  116452. if (!sourceAndTargetTypesMatch) {
  116453. return cloneUnlessOtherwiseSpecified(source, options)
  116454. } else if (sourceIsArray) {
  116455. return options.arrayMerge(target, source, options)
  116456. } else {
  116457. return mergeObject(target, source, options)
  116458. }
  116459. }
  116460. deepmerge.all = function deepmergeAll(array, options) {
  116461. if (!Array.isArray(array)) {
  116462. throw new Error('first argument should be an array')
  116463. }
  116464. return array.reduce(function(prev, next) {
  116465. return deepmerge(prev, next, options)
  116466. }, {})
  116467. };
  116468. var deepmerge_1 = deepmerge;
  116469. /* harmony default export */ __webpack_exports__["default"] = (deepmerge_1);
  116470. /***/ }),
  116471. /* 24 */
  116472. /***/ (function(module, exports, __webpack_require__) {
  116473. "use strict";
  116474. Object.defineProperty(exports, "__esModule", { value: true });
  116475. var babylonjs_1 = __webpack_require__(0);
  116476. var configuration_1 = __webpack_require__(10);
  116477. var viewerModel_1 = __webpack_require__(5);
  116478. var helper_1 = __webpack_require__(1);
  116479. var viewerLabs_1 = __webpack_require__(26);
  116480. var _1 = __webpack_require__(28);
  116481. var SceneManager = /** @class */ (function () {
  116482. function SceneManager(_engine, _configurationContainer, _observablesManager) {
  116483. var _this = this;
  116484. this._engine = _engine;
  116485. this._configurationContainer = _configurationContainer;
  116486. this._observablesManager = _observablesManager;
  116487. this._animationBlendingEnabled = true;
  116488. this._white = babylonjs_1.Color3.White();
  116489. this._forceShadowUpdate = false;
  116490. this._processShadows = true;
  116491. this._groundEnabled = true;
  116492. this._groundMirrorEnabled = true;
  116493. this._defaultRenderingPipelineEnabled = false;
  116494. this._globalConfiguration = {};
  116495. this._defaultRenderingPipelineShouldBuild = true;
  116496. // default from rendering pipeline
  116497. this._bloomEnabled = false;
  116498. // default from rendering pipeline
  116499. this._fxaaEnabled = false;
  116500. this._focusOnModel = function (model) {
  116501. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  116502. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  116503. var halfSizeVec = sizeVec.scale(0.5);
  116504. var center = boundingInfo.min.add(halfSizeVec);
  116505. _this.camera.setTarget(center);
  116506. _this.camera.alpha = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.alpha) || _this.camera.alpha;
  116507. _this.camera.beta = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.beta) || _this.camera.beta;
  116508. _this.camera.radius = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.radius) || _this.camera.radius;
  116509. var sceneDiagonalLenght = sizeVec.length();
  116510. if (isFinite(sceneDiagonalLenght))
  116511. _this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  116512. if (_this._configurationContainer.configuration)
  116513. _this._configureEnvironment(_this._configurationContainer.configuration.skybox, _this._configurationContainer.configuration.ground);
  116514. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  116515. // casting ais safe, due to the constraints tested before
  116516. (<ShadowLight>light).setDirectionToTarget(center);
  116517. });*/
  116518. };
  116519. this._cameraBehaviorMapping = {};
  116520. this.models = [];
  116521. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  116522. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  116523. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  116524. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  116525. this.onSceneInitObservable = new babylonjs_1.Observable();
  116526. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  116527. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  116528. this.onVRConfiguredObservable = new babylonjs_1.Observable();
  116529. //this._viewer.onEngineInitObservable.add(() => {
  116530. this._handleHardwareLimitations();
  116531. //});
  116532. this.onSceneInitObservable.add(function (scene) {
  116533. _this.scene.animationPropertiesOverride = _this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  116534. _this.labs = new viewerLabs_1.ViewerLabs(scene);
  116535. var updateShadows = function () {
  116536. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  116537. var light = _a[_i];
  116538. var generator = light.getShadowGenerator();
  116539. if (generator) {
  116540. // Processing shadows if animates
  116541. var shadowMap = generator.getShadowMap();
  116542. if (shadowMap) {
  116543. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  116544. }
  116545. }
  116546. }
  116547. };
  116548. scene.registerBeforeRender(function () {
  116549. if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  116550. // make sure all models are loaded
  116551. updateShadows();
  116552. _this._forceShadowUpdate = false;
  116553. }
  116554. else if (!(_this.models.every(function (model) {
  116555. if (!model.shadowsRenderedAfterLoad) {
  116556. model.shadowsRenderedAfterLoad = true;
  116557. return false;
  116558. }
  116559. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  116560. }))) {
  116561. updateShadows();
  116562. }
  116563. });
  116564. return _this._observablesManager && _this._observablesManager.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  116565. });
  116566. if (this._observablesManager) {
  116567. this._observablesManager.onModelLoadedObservable.add(function (model) {
  116568. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  116569. var light = _a[_i];
  116570. var generator = light.getShadowGenerator();
  116571. if (generator) {
  116572. // Processing shadows if animates
  116573. var shadowMap = generator.getShadowMap();
  116574. if (shadowMap) {
  116575. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  116576. }
  116577. }
  116578. }
  116579. _this._focusOnModel(model);
  116580. });
  116581. this._observablesManager.onModelAddedObservable.add(function (model) {
  116582. _this.models.push(model);
  116583. });
  116584. this._observablesManager.onModelRemovedObservable.add(function (model) {
  116585. _this.models.splice(_this.models.indexOf(model), 1);
  116586. });
  116587. }
  116588. }
  116589. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  116590. get: function () {
  116591. return this._defaultRenderingPipeline;
  116592. },
  116593. enumerable: true,
  116594. configurable: true
  116595. });
  116596. Object.defineProperty(SceneManager.prototype, "vrHelper", {
  116597. get: function () {
  116598. return this._vrHelper;
  116599. },
  116600. enumerable: true,
  116601. configurable: true
  116602. });
  116603. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  116604. /**
  116605. * Returns a boolean representing HDR support
  116606. */
  116607. get: function () {
  116608. return this._hdrSupport;
  116609. },
  116610. enumerable: true,
  116611. configurable: true
  116612. });
  116613. Object.defineProperty(SceneManager.prototype, "mainColor", {
  116614. /**
  116615. * Return the main color defined in the configuration.
  116616. */
  116617. get: function () {
  116618. return this._configurationContainer.mainColor;
  116619. },
  116620. enumerable: true,
  116621. configurable: true
  116622. });
  116623. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  116624. get: function () {
  116625. return this._configurationContainer.reflectionColor;
  116626. },
  116627. enumerable: true,
  116628. configurable: true
  116629. });
  116630. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  116631. get: function () {
  116632. return this.scene && this.scene.animationPropertiesOverride.enableBlending;
  116633. },
  116634. set: function (value) {
  116635. this.scene.animationPropertiesOverride.enableBlending = value;
  116636. },
  116637. enumerable: true,
  116638. configurable: true
  116639. });
  116640. Object.defineProperty(SceneManager.prototype, "observablesManager", {
  116641. get: function () {
  116642. return this._observablesManager;
  116643. },
  116644. enumerable: true,
  116645. configurable: true
  116646. });
  116647. Object.defineProperty(SceneManager.prototype, "processShadows", {
  116648. /**
  116649. * The flag defining whether shadows are rendered constantly or once.
  116650. */
  116651. get: function () {
  116652. return this._processShadows;
  116653. },
  116654. /**
  116655. * Should shadows be rendered every frame, or only once and stop.
  116656. * This can be used to optimize a scene.
  116657. *
  116658. * Not that the shadows will NOT disapear but will remain in place.
  116659. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  116660. */
  116661. set: function (process) {
  116662. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  116663. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  116664. var light = _a[_i];
  116665. var generator = light.getShadowGenerator();
  116666. if (generator) {
  116667. var shadowMap = generator.getShadowMap();
  116668. if (shadowMap) {
  116669. shadowMap.refreshRate = refreshType;
  116670. }
  116671. }
  116672. }
  116673. this._processShadows = process;
  116674. },
  116675. enumerable: true,
  116676. configurable: true
  116677. });
  116678. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  116679. get: function () {
  116680. return this._groundEnabled;
  116681. },
  116682. set: function (newValue) {
  116683. if (newValue === this._groundEnabled)
  116684. return;
  116685. this._groundEnabled = newValue;
  116686. if (this.environmentHelper && this.environmentHelper.ground) {
  116687. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  116688. }
  116689. },
  116690. enumerable: true,
  116691. configurable: true
  116692. });
  116693. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  116694. /**
  116695. * gets wether the reflection is disabled.
  116696. */
  116697. get: function () {
  116698. return this._groundMirrorEnabled;
  116699. },
  116700. /**
  116701. * sets wether the reflection is disabled.
  116702. */
  116703. set: function (value) {
  116704. if (this._groundMirrorEnabled === value) {
  116705. return;
  116706. }
  116707. this._groundMirrorEnabled = value;
  116708. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  116709. if (!value) {
  116710. this.environmentHelper.groundMaterial.reflectionTexture = null;
  116711. }
  116712. else {
  116713. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  116714. }
  116715. }
  116716. },
  116717. enumerable: true,
  116718. configurable: true
  116719. });
  116720. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  116721. get: function () {
  116722. return this._defaultRenderingPipelineEnabled;
  116723. },
  116724. set: function (value) {
  116725. if (value === this._defaultRenderingPipelineEnabled) {
  116726. return;
  116727. }
  116728. this._defaultRenderingPipelineEnabled = value;
  116729. this._rebuildPostprocesses();
  116730. if (this._defaultRenderingPipeline) {
  116731. this._defaultRenderingPipelineShouldBuild = false;
  116732. this._defaultRenderingPipeline.prepare();
  116733. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  116734. }
  116735. },
  116736. enumerable: true,
  116737. configurable: true
  116738. });
  116739. /**
  116740. * Sets the engine flags to unlock all babylon features.
  116741. * Can also be configured using the scene.flags configuration object
  116742. */
  116743. SceneManager.prototype.unlockBabylonFeatures = function () {
  116744. this.scene.shadowsEnabled = true;
  116745. this.scene.particlesEnabled = true;
  116746. this.scene.postProcessesEnabled = true;
  116747. this.scene.collisionsEnabled = true;
  116748. this.scene.lightsEnabled = true;
  116749. this.scene.texturesEnabled = true;
  116750. this.scene.lensFlaresEnabled = true;
  116751. this.scene.proceduralTexturesEnabled = true;
  116752. this.scene.renderTargetsEnabled = true;
  116753. this.scene.spritesEnabled = true;
  116754. this.scene.skeletonsEnabled = true;
  116755. this.scene.audioEnabled = true;
  116756. };
  116757. /**
  116758. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  116759. */
  116760. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  116761. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  116762. // if the scen exists, dispose it.
  116763. if (this.scene) {
  116764. this.scene.dispose();
  116765. }
  116766. // create a new scene
  116767. this.scene = new babylonjs_1.Scene(this._engine);
  116768. this._configurationContainer.scene = this.scene;
  116769. // set a default PBR material
  116770. if (!sceneConfiguration.defaultMaterial) {
  116771. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  116772. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  116773. defaultMaterial.microSurface = 0.6;
  116774. if (this.scene.defaultMaterial) {
  116775. this.scene.defaultMaterial.dispose();
  116776. }
  116777. this.scene.defaultMaterial = defaultMaterial;
  116778. }
  116779. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  116780. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  116781. /*if (sceneConfiguration.glow) {
  116782. let options: Partial<IGlowLayerOptions> = {
  116783. mainTextureFixedSize: 512
  116784. };
  116785. if (typeof sceneConfiguration.glow === 'object') {
  116786. options = sceneConfiguration.glow
  116787. }
  116788. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  116789. }*/
  116790. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  116791. };
  116792. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  116793. if (clearModels === void 0) { clearModels = true; }
  116794. if (clearLights === void 0) { clearLights = false; }
  116795. if (clearModels) {
  116796. this.models.forEach(function (m) { return m.dispose(); });
  116797. this.models.length = 0;
  116798. }
  116799. if (clearLights) {
  116800. this.scene.lights.forEach(function (l) { return l.dispose(); });
  116801. }
  116802. };
  116803. /**
  116804. * This will update the scene's configuration, including camera, lights, environment.
  116805. * @param newConfiguration the delta that should be configured. This includes only the changes
  116806. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  116807. */
  116808. SceneManager.prototype.updateConfiguration = function (newConfiguration) {
  116809. var _this = this;
  116810. if (this._configurationContainer) {
  116811. this._globalConfiguration = this._configurationContainer.configuration;
  116812. }
  116813. else {
  116814. this._globalConfiguration = newConfiguration;
  116815. }
  116816. if (newConfiguration.lab) {
  116817. if (newConfiguration.lab.assetsRootURL) {
  116818. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  116819. }
  116820. }
  116821. // update scene configuration
  116822. if (newConfiguration.scene) {
  116823. this._configureScene(newConfiguration.scene);
  116824. }
  116825. // optimizer
  116826. if (newConfiguration.optimizer !== undefined) {
  116827. this._configureOptimizer(newConfiguration.optimizer);
  116828. }
  116829. // configure model
  116830. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  116831. this._configureModel(newConfiguration.model);
  116832. }*/
  116833. // lights
  116834. this._configureLights(newConfiguration.lights);
  116835. // environment
  116836. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  116837. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  116838. }
  116839. // camera
  116840. this._configureCamera(newConfiguration.camera);
  116841. if (newConfiguration.vr !== undefined) {
  116842. this._configureVR(newConfiguration.vr);
  116843. }
  116844. if (newConfiguration.lab) {
  116845. if (newConfiguration.lab.environmentMap) {
  116846. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  116847. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  116848. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  116849. });
  116850. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  116851. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  116852. }
  116853. }
  116854. // rendering piplines
  116855. if (newConfiguration.lab.defaultRenderingPipelines) {
  116856. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  116857. if (typeof pipelineConfig === 'boolean') {
  116858. this.defaultRenderingPipelineEnabled = pipelineConfig;
  116859. }
  116860. else {
  116861. this.defaultRenderingPipelineEnabled = true;
  116862. }
  116863. }
  116864. if (this.environmentHelper && newConfiguration.lab.environmentMainColor) {
  116865. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  116866. this.environmentHelper.setMainColor(mainColor);
  116867. }
  116868. if (newConfiguration.lab.globalLightRotation !== undefined) {
  116869. // rotate all lights that are shadow lights
  116870. this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) {
  116871. // casting and '!' are safe, due to the constraints tested before
  116872. _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation);
  116873. });
  116874. this._forceShadowUpdate = true;
  116875. }
  116876. }
  116877. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  116878. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  116879. }
  116880. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  116881. this._defaultRenderingPipelineShouldBuild = false;
  116882. this._defaultRenderingPipeline.prepare();
  116883. }
  116884. };
  116885. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  116886. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._globalConfiguration)) {
  116887. if (this._defaultRenderingPipeline) {
  116888. this._defaultRenderingPipeline.dispose();
  116889. this._defaultRenderingPipeline = null;
  116890. this.scene.autoClearDepthAndStencil = true;
  116891. this.scene.autoClear = true;
  116892. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  116893. }
  116894. return;
  116895. }
  116896. var pipelineConfig = configuration || (this._globalConfiguration.lab && this._globalConfiguration.lab.defaultRenderingPipelines);
  116897. if (pipelineConfig) {
  116898. if (!this._defaultRenderingPipeline) {
  116899. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  116900. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  116901. }
  116902. this.scene.autoClear = false;
  116903. this.scene.autoClearDepthAndStencil = false;
  116904. this._defaultRenderingPipelineShouldBuild = true;
  116905. var bloomEnabled = this._bloomEnabled;
  116906. if (typeof pipelineConfig !== 'boolean') {
  116907. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  116908. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  116909. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  116910. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  116911. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  116912. }
  116913. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  116914. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  116915. }
  116916. };
  116917. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  116918. get: function () {
  116919. return this._bloomEnabled;
  116920. },
  116921. set: function (value) {
  116922. if (this._bloomEnabled === value) {
  116923. return;
  116924. }
  116925. this._bloomEnabled = value;
  116926. this._rebuildPostprocesses();
  116927. if (this._defaultRenderingPipeline) {
  116928. this._defaultRenderingPipelineShouldBuild = false;
  116929. this._defaultRenderingPipeline.prepare();
  116930. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  116931. }
  116932. },
  116933. enumerable: true,
  116934. configurable: true
  116935. });
  116936. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  116937. get: function () {
  116938. return this._fxaaEnabled;
  116939. },
  116940. set: function (value) {
  116941. if (this._fxaaEnabled === value) {
  116942. return;
  116943. }
  116944. this._fxaaEnabled = value;
  116945. this._rebuildPostprocesses();
  116946. if (this._defaultRenderingPipeline) {
  116947. this._defaultRenderingPipelineShouldBuild = false;
  116948. this._defaultRenderingPipeline.prepare();
  116949. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  116950. }
  116951. },
  116952. enumerable: true,
  116953. configurable: true
  116954. });
  116955. /**
  116956. * internally configure the scene using the provided configuration.
  116957. * The scene will not be recreated, but just updated.
  116958. * @param sceneConfig the (new) scene configuration
  116959. */
  116960. SceneManager.prototype._configureScene = function (sceneConfig) {
  116961. // sanity check!
  116962. if (!this.scene) {
  116963. return;
  116964. }
  116965. var cc = sceneConfig.clearColor;
  116966. var oldcc = this.scene.clearColor;
  116967. if (cc) {
  116968. if (cc.r !== undefined) {
  116969. oldcc.r = cc.r;
  116970. }
  116971. if (cc.g !== undefined) {
  116972. oldcc.g = cc.g;
  116973. }
  116974. if (cc.b !== undefined) {
  116975. oldcc.b = cc.b;
  116976. }
  116977. if (cc.a !== undefined) {
  116978. oldcc.a = cc.a;
  116979. }
  116980. }
  116981. // image processing configuration - optional.
  116982. if (sceneConfig.imageProcessingConfiguration) {
  116983. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  116984. }
  116985. //animation properties override
  116986. if (sceneConfig.animationPropertiesOverride) {
  116987. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  116988. }
  116989. if (sceneConfig.environmentTexture) {
  116990. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  116991. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  116992. this.scene.environmentTexture.dispose();
  116993. }
  116994. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  116995. this.scene.environmentTexture = environmentTexture;
  116996. }
  116997. }
  116998. if (sceneConfig.debug === true) {
  116999. this.scene.debugLayer.show();
  117000. }
  117001. else if (sceneConfig.debug === false) {
  117002. if (this.scene.debugLayer.isVisible()) {
  117003. this.scene.debugLayer.hide();
  117004. }
  117005. }
  117006. if (sceneConfig.disableHdr) {
  117007. this._handleHardwareLimitations(false);
  117008. }
  117009. else {
  117010. this._handleHardwareLimitations(true);
  117011. }
  117012. if (sceneConfig.renderInBackground !== undefined) {
  117013. this._engine.renderEvenInBackground = !!sceneConfig.renderInBackground;
  117014. }
  117015. var canvas = this._engine.getRenderingCanvas();
  117016. if (canvas) {
  117017. if (this.camera && sceneConfig.disableCameraControl) {
  117018. this.camera.detachControl(canvas);
  117019. }
  117020. else if (this.camera && sceneConfig.disableCameraControl === false) {
  117021. this.camera.attachControl(canvas);
  117022. }
  117023. }
  117024. // process mainColor changes:
  117025. if (sceneConfig.mainColor) {
  117026. this._configurationContainer.mainColor = this.mainColor || babylonjs_1.Color3.White();
  117027. var mc = sceneConfig.mainColor;
  117028. if (mc.r !== undefined) {
  117029. this.mainColor.r = mc.r;
  117030. }
  117031. if (mc.g !== undefined) {
  117032. this.mainColor.g = mc.g;
  117033. }
  117034. if (mc.b !== undefined) {
  117035. this.mainColor.b = mc.b;
  117036. }
  117037. this.reflectionColor.copyFrom(this.mainColor);
  117038. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._globalConfiguration) || 0;
  117039. // reflection color
  117040. this.reflectionColor.toLinearSpaceToRef(this.reflectionColor);
  117041. this.reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this.reflectionColor);
  117042. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this.reflectionColor, environmentTint);
  117043. this.reflectionColor.copyFrom(tmpColor3);
  117044. //update the environment, if exists
  117045. if (this.environmentHelper) {
  117046. if (this.environmentHelper.groundMaterial) {
  117047. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  117048. }
  117049. if (this.environmentHelper.skyboxMaterial) {
  117050. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  117051. }
  117052. }
  117053. }
  117054. if (sceneConfig.defaultMaterial) {
  117055. var conf = sceneConfig.defaultMaterial;
  117056. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  117057. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  117058. this.scene.defaultMaterial.dispose();
  117059. if (conf.materialType === 'standard') {
  117060. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  117061. }
  117062. else {
  117063. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  117064. }
  117065. }
  117066. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  117067. }
  117068. if (sceneConfig.flags) {
  117069. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  117070. }
  117071. this.onSceneConfiguredObservable.notifyObservers({
  117072. sceneManager: this,
  117073. object: this.scene,
  117074. newConfiguration: sceneConfig
  117075. });
  117076. };
  117077. /**
  117078. * Configure the scene optimizer.
  117079. * The existing scene optimizer will be disposed and a new one will be created.
  117080. * @param optimizerConfig the (new) optimizer configuration
  117081. */
  117082. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  117083. var _this = this;
  117084. if (typeof optimizerConfig === 'boolean') {
  117085. if (this.sceneOptimizer) {
  117086. this.sceneOptimizer.stop();
  117087. this.sceneOptimizer.dispose();
  117088. delete this.sceneOptimizer;
  117089. }
  117090. if (optimizerConfig) {
  117091. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  117092. this.sceneOptimizer.start();
  117093. }
  117094. }
  117095. else {
  117096. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  117097. // check for degradation
  117098. if (optimizerConfig.degradation) {
  117099. switch (optimizerConfig.degradation) {
  117100. case "low":
  117101. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  117102. break;
  117103. case "moderate":
  117104. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  117105. break;
  117106. case "hight":
  117107. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  117108. break;
  117109. }
  117110. }
  117111. if (this.sceneOptimizer) {
  117112. this.sceneOptimizer.stop();
  117113. this.sceneOptimizer.dispose();
  117114. }
  117115. if (optimizerConfig.custom) {
  117116. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  117117. if (customOptimizer_1) {
  117118. optimizerOptions.addCustomOptimization(function () {
  117119. return customOptimizer_1(_this);
  117120. }, function () {
  117121. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  117122. });
  117123. }
  117124. }
  117125. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  117126. this.sceneOptimizer.start();
  117127. }
  117128. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  117129. sceneManager: this,
  117130. object: this.sceneOptimizer,
  117131. newConfiguration: optimizerConfig
  117132. });
  117133. };
  117134. /**
  117135. * configure all models using the configuration.
  117136. * @param modelConfiguration the configuration to use to reconfigure the models
  117137. */
  117138. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  117139. this.models.forEach(model => {
  117140. model.updateConfiguration(modelConfiguration);
  117141. });
  117142. this.onModelsConfiguredObservable.notifyObservers({
  117143. sceneManager: this,
  117144. object: this.models,
  117145. newConfiguration: modelConfiguration
  117146. });
  117147. }*/
  117148. SceneManager.prototype._configureVR = function (vrConfig) {
  117149. var _this = this;
  117150. if (vrConfig.disabled) {
  117151. if (this._vrHelper) {
  117152. if (this._vrHelper.isInVRMode) {
  117153. this._vrHelper.exitVR();
  117154. }
  117155. this._vrHelper.dispose();
  117156. this._vrHelper = undefined;
  117157. }
  117158. return;
  117159. }
  117160. var vrOptions = vrConfig.vrOptions || {
  117161. useCustomVRButton: true,
  117162. createDeviceOrientationCamera: false,
  117163. trackPosition: true
  117164. };
  117165. this._vrHelper = this.scene.createDefaultVRExperience(vrOptions);
  117166. if (!vrConfig.disableInteractions) {
  117167. this._vrHelper.enableInteractions();
  117168. }
  117169. if (!vrConfig.disableTeleportation) {
  117170. var floorMeshName = vrConfig.overrideFloorMeshName || "BackgroundPlane";
  117171. this._vrHelper.enableTeleportation({
  117172. floorMeshName: floorMeshName
  117173. });
  117174. }
  117175. var rotationOffset;
  117176. this._vrHelper.onControllerMeshLoadedObservable.add(function (controller) {
  117177. controller.onTriggerStateChangedObservable.add(function (data) {
  117178. if (controller.mesh && controller.mesh.rotationQuaternion) {
  117179. if (data.pressed) {
  117180. if (!rotationOffset) {
  117181. _this.models[0].rootMesh.rotationQuaternion = _this.models[0].rootMesh.rotationQuaternion || new babylonjs_1.Quaternion();
  117182. rotationOffset = controller.mesh.rotationQuaternion.conjugate().multiply(_this.models[0].rootMesh.rotationQuaternion);
  117183. }
  117184. }
  117185. else {
  117186. rotationOffset = null;
  117187. }
  117188. }
  117189. });
  117190. _this.scene.registerBeforeRender(function () {
  117191. if (_this.models[0]) {
  117192. if (rotationOffset && controller.mesh && controller.mesh.rotationQuaternion) {
  117193. _this.models[0].rootMesh.rotationQuaternion.copyFrom(controller.mesh.rotationQuaternion).multiplyInPlace(rotationOffset);
  117194. }
  117195. else {
  117196. _this.models[0].rootMesh.rotationQuaternion = null;
  117197. }
  117198. }
  117199. });
  117200. });
  117201. this.onVRConfiguredObservable.notifyObservers({
  117202. sceneManager: this,
  117203. object: this._vrHelper,
  117204. newConfiguration: vrConfig
  117205. });
  117206. };
  117207. /**
  117208. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  117209. * @param cameraConfig the new camera configuration
  117210. * @param model optionally use the model to configure the camera.
  117211. */
  117212. SceneManager.prototype._configureCamera = function (cameraConfig) {
  117213. var _this = this;
  117214. if (cameraConfig === void 0) { cameraConfig = {}; }
  117215. if (!this.scene.activeCamera) {
  117216. var attachControl = true;
  117217. if (this._globalConfiguration.scene && this._globalConfiguration.scene.disableCameraControl) {
  117218. attachControl = false;
  117219. }
  117220. this.scene.createDefaultCamera(true, true, attachControl);
  117221. this.camera = this.scene.activeCamera;
  117222. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  117223. }
  117224. if (!this.camera) {
  117225. this.camera = this.scene.activeCamera;
  117226. }
  117227. if (cameraConfig.position) {
  117228. var newPosition = this.camera.position.clone();
  117229. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  117230. this.camera.setPosition(newPosition);
  117231. }
  117232. if (cameraConfig.target) {
  117233. var newTarget = this.camera.target.clone();
  117234. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  117235. this.camera.setTarget(newTarget);
  117236. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  117237. this._focusOnModel(this.models[0]);
  117238. }*/
  117239. if (cameraConfig.rotation) {
  117240. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  117241. }
  117242. if (cameraConfig.behaviors) {
  117243. for (var name_1 in cameraConfig.behaviors) {
  117244. if (cameraConfig.behaviors[name_1] !== undefined) {
  117245. this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]);
  117246. }
  117247. }
  117248. }
  117249. ;
  117250. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  117251. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  117252. });
  117253. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  117254. var sceneDiagonalLength = sceneDiagonal.length();
  117255. if (isFinite(sceneDiagonalLength)) {
  117256. this.camera.upperRadiusLimit = sceneDiagonalLength * 4;
  117257. }
  117258. // sanity check!
  117259. if (this.scene.imageProcessingConfiguration) {
  117260. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  117261. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  117262. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._globalConfiguration);
  117263. }
  117264. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  117265. this.onCameraConfiguredObservable.notifyObservers({
  117266. sceneManager: this,
  117267. object: this.camera,
  117268. newConfiguration: cameraConfig
  117269. });
  117270. };
  117271. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  117272. var _this = this;
  117273. if (!skyboxConifguration && !groundConfiguration) {
  117274. if (this.environmentHelper) {
  117275. this.environmentHelper.dispose();
  117276. this.environmentHelper = undefined;
  117277. }
  117278. ;
  117279. }
  117280. else {
  117281. var options = {
  117282. createGround: !!groundConfiguration && this._groundEnabled,
  117283. createSkybox: !!skyboxConifguration,
  117284. setupImageProcessing: false,
  117285. };
  117286. // will that cause problems with model ground configuration?
  117287. /*if (model) {
  117288. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  117289. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  117290. const halfSizeVec = sizeVec.scale(0.5);
  117291. const center = boundingInfo.min.add(halfSizeVec);
  117292. options.groundYBias = -center.y;
  117293. }*/
  117294. if (groundConfiguration) {
  117295. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  117296. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  117297. if (groundSize) {
  117298. options.groundSize = groundSize;
  117299. }
  117300. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  117301. if (groundConfig_1.shadowLevel !== undefined) {
  117302. options.groundShadowLevel = groundConfig_1.shadowLevel;
  117303. }
  117304. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  117305. if (groundConfig_1.texture) {
  117306. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  117307. }
  117308. if (groundConfig_1.color) {
  117309. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  117310. }
  117311. if (groundConfig_1.opacity !== undefined) {
  117312. options.groundOpacity = groundConfig_1.opacity;
  117313. }
  117314. if (groundConfig_1.mirror) {
  117315. options.enableGroundMirror = true;
  117316. // to prevent undefines
  117317. if (typeof groundConfig_1.mirror === "object") {
  117318. if (groundConfig_1.mirror.amount !== undefined)
  117319. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  117320. if (groundConfig_1.mirror.sizeRatio !== undefined)
  117321. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  117322. if (groundConfig_1.mirror.blurKernel !== undefined)
  117323. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  117324. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  117325. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  117326. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  117327. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  117328. if (this._defaultPipelineTextureType !== undefined)
  117329. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  117330. }
  117331. }
  117332. }
  117333. var postInitSkyboxMaterial = false;
  117334. if (skyboxConifguration) {
  117335. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  117336. if (conf.material && conf.material.imageProcessingConfiguration) {
  117337. options.setupImageProcessing = false; // will be configured later manually.
  117338. }
  117339. var skyboxSize = conf.scale;
  117340. if (skyboxSize) {
  117341. options.skyboxSize = skyboxSize;
  117342. }
  117343. options.sizeAuto = !options.skyboxSize;
  117344. if (conf.color) {
  117345. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  117346. }
  117347. if (conf.cubeTexture && conf.cubeTexture.url) {
  117348. if (typeof conf.cubeTexture.url === "string") {
  117349. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  117350. }
  117351. else {
  117352. // init later!
  117353. postInitSkyboxMaterial = true;
  117354. }
  117355. }
  117356. if (conf.material) {
  117357. postInitSkyboxMaterial = true;
  117358. }
  117359. }
  117360. options.setupImageProcessing = false; // TMP
  117361. if (!this.environmentHelper) {
  117362. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  117363. }
  117364. else {
  117365. // unlikely, but there might be a new scene! we need to dispose.
  117366. // get the scene used by the envHelper
  117367. var scene = this.environmentHelper.rootMesh.getScene();
  117368. // is it a different scene? Oh no!
  117369. if (scene !== this.scene) {
  117370. this.environmentHelper.dispose();
  117371. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  117372. }
  117373. else {
  117374. // recreate the ground
  117375. if (this.environmentHelper.ground) {
  117376. this.environmentHelper.ground.dispose();
  117377. }
  117378. // recreate the skybox
  117379. if (this.environmentHelper.skybox) {
  117380. this.environmentHelper.skybox.dispose();
  117381. }
  117382. this.environmentHelper.updateOptions(options);
  117383. // update doesn't change the size of the skybox and ground, so we have to recreate!
  117384. //this.environmentHelper.dispose();
  117385. //this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  117386. }
  117387. }
  117388. if (this.environmentHelper.rootMesh && this._globalConfiguration.scene && this._globalConfiguration.scene.environmentRotationY !== undefined) {
  117389. this.environmentHelper.rootMesh.rotation.y = this._globalConfiguration.scene.environmentRotationY;
  117390. }
  117391. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  117392. if (this.environmentHelper.groundMaterial && groundConfig) {
  117393. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  117394. if (groundConfig.material) {
  117395. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  117396. }
  117397. if (this.environmentHelper.groundMirror) {
  117398. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  117399. // TODO user camera exposure value to set the mirror clear color
  117400. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  117401. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  117402. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  117403. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  117404. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  117405. this.environmentHelper.groundMirror.clearColor.a = 1;
  117406. if (!this.groundMirrorEnabled) {
  117407. this.environmentHelper.groundMaterial.reflectionTexture = null;
  117408. }
  117409. }
  117410. }
  117411. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  117412. if (skyboxMaterial) {
  117413. skyboxMaterial._perceptualColor = this.mainColor;
  117414. if (postInitSkyboxMaterial) {
  117415. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  117416. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  117417. }
  117418. }
  117419. }
  117420. }
  117421. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  117422. _this._updateGroundMirrorRenderList(model);
  117423. });
  117424. this.onEnvironmentConfiguredObservable.notifyObservers({
  117425. sceneManager: this,
  117426. object: this.environmentHelper,
  117427. newConfiguration: {
  117428. skybox: skyboxConifguration,
  117429. ground: groundConfiguration
  117430. }
  117431. });
  117432. };
  117433. /**
  117434. * configure the lights.
  117435. *
  117436. * @param lightsConfiguration the (new) light(s) configuration
  117437. * @param model optionally use the model to configure the camera.
  117438. */
  117439. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  117440. var _this = this;
  117441. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  117442. // sanity check!
  117443. var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; });
  117444. if (!lightKeys.length) {
  117445. if (!this.scene.lights.length)
  117446. this.scene.createDefaultLight(true);
  117447. }
  117448. else {
  117449. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  117450. // compare to the global (!) configuration object and dispose unneeded:
  117451. var lightsToConfigure_1 = Object.keys(this._globalConfiguration.lights || []);
  117452. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  117453. lightsAvailable_1.forEach(function (lName) {
  117454. if (lightsToConfigure_1.indexOf(lName) === -1) {
  117455. _this.scene.getLightByName(lName).dispose();
  117456. }
  117457. });
  117458. }
  117459. lightKeys.forEach(function (name, idx) {
  117460. var lightConfig = { type: 0 };
  117461. if (typeof lightsConfiguration[name] === 'object') {
  117462. lightConfig = lightsConfiguration[name];
  117463. }
  117464. if (typeof lightsConfiguration[name] === 'number') {
  117465. lightConfig.type = lightsConfiguration[name];
  117466. }
  117467. lightConfig.name = name;
  117468. var light;
  117469. // light is not already available
  117470. if (lightsAvailable_1.indexOf(name) === -1) {
  117471. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  117472. if (!constructor)
  117473. return;
  117474. light = constructor();
  117475. }
  117476. else {
  117477. // available? get it from the scene
  117478. light = _this.scene.getLightByName(name);
  117479. if (typeof lightsConfiguration[name] === 'boolean') {
  117480. lightConfig.type = light.getTypeID();
  117481. }
  117482. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  117483. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  117484. light.dispose();
  117485. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  117486. if (!constructor)
  117487. return;
  117488. light = constructor();
  117489. }
  117490. }
  117491. // if config set the light to false, dispose it.
  117492. if (lightsConfiguration[name] === false) {
  117493. light.dispose();
  117494. return;
  117495. }
  117496. //enabled
  117497. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  117498. light.setEnabled(enabled);
  117499. helper_1.extendClassWithConfig(light, lightConfig);
  117500. //position. Some lights don't support shadows
  117501. if (light instanceof babylonjs_1.ShadowLight) {
  117502. // set default values
  117503. light.shadowMinZ = light.shadowMinZ || 0.2;
  117504. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  117505. if (lightConfig.target) {
  117506. if (light.setDirectionToTarget) {
  117507. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  117508. light.setDirectionToTarget(target);
  117509. }
  117510. }
  117511. else if (lightConfig.direction) {
  117512. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  117513. light.direction = direction;
  117514. }
  117515. var isShadowEnabled = false;
  117516. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  117517. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  117518. isShadowEnabled = true;
  117519. }
  117520. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  117521. var spotLight = light;
  117522. if (lightConfig.spotAngle !== undefined) {
  117523. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  117524. }
  117525. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  117526. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  117527. }
  117528. isShadowEnabled = true;
  117529. }
  117530. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  117531. if (lightConfig.shadowFieldOfView) {
  117532. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  117533. }
  117534. isShadowEnabled = true;
  117535. }
  117536. var shadowGenerator_1 = light.getShadowGenerator();
  117537. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  117538. var bufferSize = lightConfig.shadowBufferSize || 256;
  117539. if (!shadowGenerator_1) {
  117540. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  117541. }
  117542. var blurKernel = _this.getBlurKernel(light, bufferSize);
  117543. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  117544. shadowGenerator_1.blurKernel = blurKernel;
  117545. //override defaults
  117546. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  117547. // add the focues meshes to the shadow list
  117548. _this._observablesManager && _this._observablesManager.onModelLoadedObservable.add(function (model) {
  117549. _this._updateShadowRenderList(shadowGenerator_1, model);
  117550. });
  117551. //if (model) {
  117552. _this._updateShadowRenderList(shadowGenerator_1);
  117553. //}
  117554. }
  117555. else if (shadowGenerator_1) {
  117556. shadowGenerator_1.dispose();
  117557. }
  117558. }
  117559. });
  117560. // render priority
  117561. var globalLightsConfiguration_1 = this._globalConfiguration.lights || {};
  117562. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  117563. var configuration = globalLightsConfiguration_1[name];
  117564. var light = _this.scene.getLightByName(name);
  117565. // sanity check
  117566. if (!light)
  117567. return;
  117568. light.renderPriority = -idx;
  117569. });
  117570. }
  117571. this.onLightsConfiguredObservable.notifyObservers({
  117572. sceneManager: this,
  117573. object: this.scene.lights,
  117574. newConfiguration: lightsConfiguration
  117575. });
  117576. };
  117577. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  117578. var focusMeshes = model ? model.meshes : this.scene.meshes;
  117579. // add the focues meshes to the shadow list
  117580. var shadownMap = shadowGenerator.getShadowMap();
  117581. if (!shadownMap)
  117582. return;
  117583. if (resetList && shadownMap.renderList) {
  117584. shadownMap.renderList.length = 0;
  117585. }
  117586. else {
  117587. shadownMap.renderList = shadownMap.renderList || [];
  117588. }
  117589. for (var index = 0; index < focusMeshes.length; index++) {
  117590. var mesh = focusMeshes[index];
  117591. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  117592. shadownMap.renderList.push(mesh);
  117593. }
  117594. }
  117595. if (!this._shadowGroundPlane) {
  117596. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  117597. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  117598. shadowGroundPlane.useVertexColors = false;
  117599. //material isn't ever used in rendering, just used to set back face culling
  117600. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  117601. shadowGroundPlane.material.backFaceCulling = false;
  117602. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  117603. shadowGroundPlane.freezeWorldMatrix();
  117604. this._shadowGroundPlane = shadowGroundPlane;
  117605. this.scene.removeMesh(shadowGroundPlane);
  117606. }
  117607. }
  117608. else {
  117609. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  117610. this._shadowGroundPlane.dispose();
  117611. this._shadowGroundPlane = null;
  117612. }
  117613. }
  117614. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  117615. shadownMap.renderList.push(this._shadowGroundPlane);
  117616. }
  117617. };
  117618. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  117619. if (this.environmentHelper && this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  117620. var focusMeshes = model ? model.meshes : this.scene.meshes;
  117621. var renderList = this.environmentHelper.groundMirror.renderList;
  117622. if (resetList) {
  117623. renderList.length = 0;
  117624. }
  117625. for (var index = 0; index < focusMeshes.length; index++) {
  117626. var mesh = focusMeshes[index];
  117627. if (renderList.indexOf(mesh) === -1) {
  117628. renderList.push(mesh);
  117629. }
  117630. }
  117631. }
  117632. };
  117633. /**
  117634. * Gets the shadow map blur kernel according to the light configuration.
  117635. * @param light The light used to generate the shadows
  117636. * @param bufferSize The size of the shadow map
  117637. * @return the kernel blur size
  117638. */
  117639. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  117640. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  117641. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  117642. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  117643. }
  117644. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  117645. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  117646. }
  117647. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  117648. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  117649. }
  117650. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  117651. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  117652. return blurKernel;
  117653. };
  117654. /**
  117655. * Alters render settings to reduce features based on hardware feature limitations
  117656. * @param enableHDR Allows the viewer to run in HDR mode.
  117657. */
  117658. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  117659. if (enableHDR === void 0) { enableHDR = true; }
  117660. //flip rendering settings switches based on hardware support
  117661. var maxVaryingRows = this._engine.getCaps().maxVaryingVectors;
  117662. var maxFragmentSamplers = this._engine.getCaps().maxTexturesImageUnits;
  117663. //shadows are disabled if there's not enough varyings for a single shadow
  117664. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  117665. this._maxShadows = 0;
  117666. }
  117667. else {
  117668. this._maxShadows = 3;
  117669. }
  117670. //can we render to any >= 16-bit targets (required for HDR)
  117671. var caps = this._engine.getCaps();
  117672. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  117673. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  117674. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  117675. if (linearHalfFloatTargets) {
  117676. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  117677. this._shadowGeneratorBias = 0.002;
  117678. }
  117679. else if (linearFloatTargets) {
  117680. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  117681. this._shadowGeneratorBias = 0.001;
  117682. }
  117683. else {
  117684. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  117685. this._shadowGeneratorBias = 0.001;
  117686. }
  117687. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  117688. };
  117689. /**
  117690. * Dispoe the entire viewer including the scene and the engine
  117691. */
  117692. SceneManager.prototype.dispose = function () {
  117693. // this.onCameraConfiguredObservable.clear();
  117694. this.onEnvironmentConfiguredObservable.clear();
  117695. this.onLightsConfiguredObservable.clear();
  117696. this.onModelsConfiguredObservable.clear();
  117697. this.onSceneConfiguredObservable.clear();
  117698. this.onSceneInitObservable.clear();
  117699. this.onSceneOptimizerConfiguredObservable.clear();
  117700. this.onVRConfiguredObservable.clear();
  117701. if (this.sceneOptimizer) {
  117702. this.sceneOptimizer.stop();
  117703. this.sceneOptimizer.dispose();
  117704. }
  117705. if (this.environmentHelper) {
  117706. this.environmentHelper.dispose();
  117707. }
  117708. this.models.forEach(function (model) {
  117709. model.dispose();
  117710. });
  117711. if (this._defaultRenderingPipeline) {
  117712. this._defaultRenderingPipeline.dispose();
  117713. }
  117714. this.models.length = 0;
  117715. if (this.scene) {
  117716. this.scene.dispose();
  117717. }
  117718. };
  117719. SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) {
  117720. var behavior;
  117721. var type;
  117722. if (typeof behaviorConfig === 'object') {
  117723. type = behaviorConfig.type;
  117724. }
  117725. else if (typeof behaviorConfig === 'number') {
  117726. type = behaviorConfig;
  117727. }
  117728. else {
  117729. type = this._cameraBehaviorMapping[name];
  117730. }
  117731. if (type === undefined)
  117732. return;
  117733. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  117734. var enabled = true;
  117735. if (typeof behaviorConfig === 'boolean') {
  117736. enabled = behaviorConfig;
  117737. }
  117738. // constructing behavior
  117739. switch (type) {
  117740. case 0 /* AUTOROTATION */:
  117741. this.camera.useAutoRotationBehavior = enabled;
  117742. behavior = this.camera.autoRotationBehavior;
  117743. break;
  117744. case 1 /* BOUNCING */:
  117745. this.camera.useBouncingBehavior = enabled;
  117746. behavior = this.camera.bouncingBehavior;
  117747. break;
  117748. case 2 /* FRAMING */:
  117749. this.camera.useFramingBehavior = enabled;
  117750. behavior = this.camera.framingBehavior;
  117751. break;
  117752. default:
  117753. behavior = null;
  117754. break;
  117755. }
  117756. if (behavior) {
  117757. this._cameraBehaviorMapping[name] = type;
  117758. if (typeof behaviorConfig === "object") {
  117759. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  117760. }
  117761. }
  117762. // post attach configuration. Some functionalities require the attached camera.
  117763. switch (type) {
  117764. case 0 /* AUTOROTATION */:
  117765. break;
  117766. case 1 /* BOUNCING */:
  117767. break;
  117768. case 2 /* FRAMING */:
  117769. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  117770. if (config.zoomOnBoundingInfo) {
  117771. behavior.zoomOnMeshHierarchy(model.rootMesh);
  117772. }
  117773. });
  117774. break;
  117775. }
  117776. };
  117777. return SceneManager;
  117778. }());
  117779. exports.SceneManager = SceneManager;
  117780. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NlbmVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL3NjZW5lTWFuYWdlci50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QUFJLE9BQU8sY0FBYyxLQUFLLFFBQVEsRUFBRTtnQkFDcEMsOEJBQXFCLENBQUMsUUFBUSxFQUFFLGNBQWMsQ0FBQyxDQUFDO2FBQ25EO1NBQ0o7UUFFRCwrRUFBK0U7UUFDL0UsUUFBUSxJQUFJLEVBQUU7WUFDVjtnQkFDSSxNQUFNO1lBQ1Y7Z0JBQ0ksTUFBTTtZQUNWO2dCQUNJLElBQUksQ0FBQyxtQkFBbUIsSUFBSSxJQUFJLENBQUMsbUJBQW1CLENBQUMsdUJBQXVCLENBQUMsR0FBRyxDQUFDLFVBQUMsS0FBSztvQkFDbkYsSUFBSSxNQUFNLENBQUMsa0JBQWtCLEVBQUU7d0JBQ1QsUUFBUyxDQUFDLG1CQUFtQixDQUFDLEtBQUssQ0FBQyxRQUFRLENBQUMsQ0FBQztxQkFDbkU7Z0JBQ0wsQ0FBQyxDQUFDLENBQUM7Z0JBQ0gsTUFBTTtTQUNiO0lBQ0wsQ0FBQztJQUNMLG1CQUFDO0FBQUQsQ0FBQyxBQTE4Q0QsSUEwOENDO0FBMThDWSxvQ0FBWSJ9
  117781. /***/ }),
  117782. /* 25 */
  117783. /***/ (function(module, exports, __webpack_require__) {
  117784. "use strict";
  117785. Object.defineProperty(exports, "__esModule", { value: true });
  117786. /**
  117787. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  117788. * native GroupAnimation class.
  117789. */
  117790. var GroupModelAnimation = /** @class */ (function () {
  117791. /**
  117792. * Create a new GroupModelAnimation object using an AnimationGroup object
  117793. * @param _animationGroup The aniamtion group to base the class on
  117794. */
  117795. function GroupModelAnimation(_animationGroup) {
  117796. var _this = this;
  117797. this._animationGroup = _animationGroup;
  117798. this._state = 0 /* INIT */;
  117799. this._playMode = 1 /* LOOP */;
  117800. this._animationGroup.onAnimationEndObservable.add(function () {
  117801. _this.stop();
  117802. _this._state = 4 /* ENDED */;
  117803. });
  117804. }
  117805. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  117806. /**
  117807. * Get the animation's name
  117808. */
  117809. get: function () {
  117810. return this._animationGroup.name;
  117811. },
  117812. enumerable: true,
  117813. configurable: true
  117814. });
  117815. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  117816. /**
  117817. * Get the current animation's state
  117818. */
  117819. get: function () {
  117820. return this._state;
  117821. },
  117822. enumerable: true,
  117823. configurable: true
  117824. });
  117825. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  117826. /**
  117827. * Gets the speed ratio to use for all animations
  117828. */
  117829. get: function () {
  117830. return this._animationGroup.speedRatio;
  117831. },
  117832. /**
  117833. * Sets the speed ratio to use for all animations
  117834. */
  117835. set: function (value) {
  117836. this._animationGroup.speedRatio = value;
  117837. },
  117838. enumerable: true,
  117839. configurable: true
  117840. });
  117841. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  117842. /**
  117843. * Get the max numbers of frame available in the animation group
  117844. *
  117845. * In correlation to an arry, this would be ".length"
  117846. */
  117847. get: function () {
  117848. return this._animationGroup.to - this._animationGroup.from;
  117849. },
  117850. enumerable: true,
  117851. configurable: true
  117852. });
  117853. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  117854. /**
  117855. * Get the current frame playing right now.
  117856. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  117857. *
  117858. * In correlation to an array, this would be the current index
  117859. */
  117860. get: function () {
  117861. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  117862. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  117863. }
  117864. else {
  117865. return 0;
  117866. }
  117867. },
  117868. enumerable: true,
  117869. configurable: true
  117870. });
  117871. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  117872. /**
  117873. * Get the FPS value of this animation
  117874. */
  117875. get: function () {
  117876. // get the first currentFrame found
  117877. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  117878. var animatable = this._animationGroup.animatables[i];
  117879. var animations = animatable.getAnimations();
  117880. if (!animations || !animations.length) {
  117881. continue;
  117882. }
  117883. for (var idx = 0; idx < animations.length; ++idx) {
  117884. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  117885. return animations[idx].animation.framePerSecond;
  117886. }
  117887. }
  117888. }
  117889. return 0;
  117890. },
  117891. enumerable: true,
  117892. configurable: true
  117893. });
  117894. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  117895. /**
  117896. * What is the animation'S play mode (looping or played once)
  117897. */
  117898. get: function () {
  117899. return this._playMode;
  117900. },
  117901. /**
  117902. * Set the play mode.
  117903. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  117904. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  117905. */
  117906. set: function (value) {
  117907. if (value === this._playMode) {
  117908. return;
  117909. }
  117910. this._playMode = value;
  117911. if (this.state === 1 /* PLAYING */) {
  117912. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  117913. }
  117914. else {
  117915. this._animationGroup.reset();
  117916. this._state = 0 /* INIT */;
  117917. }
  117918. },
  117919. enumerable: true,
  117920. configurable: true
  117921. });
  117922. /**
  117923. * Reset the animation group
  117924. */
  117925. GroupModelAnimation.prototype.reset = function () {
  117926. this._animationGroup.reset();
  117927. };
  117928. /**
  117929. * Restart the animation group
  117930. */
  117931. GroupModelAnimation.prototype.restart = function () {
  117932. if (this.state === 2 /* PAUSED */)
  117933. this._animationGroup.restart();
  117934. else
  117935. this.start();
  117936. };
  117937. /**
  117938. *
  117939. * @param frameNumber Go to a specific frame in the animation
  117940. */
  117941. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  117942. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  117943. };
  117944. /**
  117945. * Start playing the animation.
  117946. */
  117947. GroupModelAnimation.prototype.start = function () {
  117948. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  117949. if (this._animationGroup.isStarted) {
  117950. this._state = 1 /* PLAYING */;
  117951. }
  117952. };
  117953. /**
  117954. * Pause the animation
  117955. */
  117956. GroupModelAnimation.prototype.pause = function () {
  117957. this._animationGroup.pause();
  117958. this._state = 2 /* PAUSED */;
  117959. };
  117960. /**
  117961. * Stop the animation.
  117962. * This will fail silently if the animation group is already stopped.
  117963. */
  117964. GroupModelAnimation.prototype.stop = function () {
  117965. this._animationGroup.stop();
  117966. if (!this._animationGroup.isStarted) {
  117967. this._state = 3 /* STOPPED */;
  117968. }
  117969. };
  117970. /**
  117971. * Dispose this animation object.
  117972. */
  117973. GroupModelAnimation.prototype.dispose = function () {
  117974. this._animationGroup.dispose();
  117975. };
  117976. return GroupModelAnimation;
  117977. }());
  117978. exports.GroupModelAnimation = GroupModelAnimation;
  117979. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxBbmltYXRpb24uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvbW9kZWxBbmltYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUF3SUE7OztHQUdHO0FBQ0g7SUFLSTs7O09BR0c7SUFDSCw2QkFBb0IsZUFBK0I7UUFBbkQsaUJBUUM7UUFSbUIsb0JBQWUsR0FBZixlQUFlLENBQWdCO1FBQy9DLElBQUksQ0FBQyxNQUFNLGVBQXNCLENBQUM7UUFDbEMsSUFBSSxDQUFDLFNBQVMsZUFBeUIsQ0FBQztRQUV4QyxJQUFJLENBQUMsZUFBZSxDQUFDLHdCQUF3QixDQUFDLEdBQUcsQ0FBQztZQUM5QyxLQUFJLENBQUMsSUFBSSxFQUFFLENBQUM7WUFDWixLQUFJLENBQUMsTUFBTSxnQkFBdUIsQ0FBQztRQUN2QyxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFLRCxzQkFBVyxxQ0FBSTtRQUhmOztXQUVHO2FBQ0g7WUFDSSxPQUFPLElBQUksQ0FB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NLGtCQUF5QixDQUFDO1NBQ3hDO0lBQ0wsQ0FBQztJQUVEOztPQUVHO0lBQ0gsbUNBQUssR0FBTDtRQUNJLElBQUksQ0FBQyxlQUFlLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDN0IsSUFBSSxDQUFDLE1BQU0saUJBQXdCLENBQUM7SUFDeEMsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGtDQUFJLEdBQVg7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQzVCLElBQUksQ0FBQyxJQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsRUFBRTtZQUNqQyxJQUFJLENBQUMsTUFBTSxrQkFBeUIsQ0FBQztTQUN4QztJQUNMLENBQUM7SUFFRDs7T0FFRztJQUNJLHFDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ25DLENBQUM7SUFDTCwwQkFBQztBQUFELENBQUMsQUFqTEQsSUFpTEM7QUFqTFksa0RBQW1CIn0=
  117980. /***/ }),
  117981. /* 26 */
  117982. /***/ (function(module, exports, __webpack_require__) {
  117983. "use strict";
  117984. Object.defineProperty(exports, "__esModule", { value: true });
  117985. var environmentSerializer_1 = __webpack_require__(27);
  117986. var babylonjs_1 = __webpack_require__(0);
  117987. var texture_1 = __webpack_require__(12);
  117988. /**
  117989. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  117990. * The APIs in all labs-related classes and configuration might change.
  117991. * Once stable, lab features will be moved to the publis API and configuration object.
  117992. */
  117993. var ViewerLabs = /** @class */ (function () {
  117994. function ViewerLabs(_scene) {
  117995. this._scene = _scene;
  117996. this.environment = {
  117997. //irradiance
  117998. irradiancePolynomialCoefficients: {
  117999. x: new babylonjs_1.Vector3(0, 0, 0),
  118000. y: new babylonjs_1.Vector3(0, 0, 0),
  118001. z: new babylonjs_1.Vector3(0, 0, 0),
  118002. xx: new babylonjs_1.Vector3(0, 0, 0),
  118003. yy: new babylonjs_1.Vector3(0, 0, 0),
  118004. zz: new babylonjs_1.Vector3(0, 0, 0),
  118005. yz: new babylonjs_1.Vector3(0, 0, 0),
  118006. zx: new babylonjs_1.Vector3(0, 0, 0),
  118007. xy: new babylonjs_1.Vector3(0, 0, 0)
  118008. },
  118009. textureIntensityScale: 1.0
  118010. };
  118011. }
  118012. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  118013. var _this = this;
  118014. //@! todo: should loadEnvironment cancel any currently loading environments?
  118015. if (data instanceof ArrayBuffer) {
  118016. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  118017. if (onSuccess)
  118018. onSuccess(this.environment);
  118019. }
  118020. else if (typeof data === 'string') {
  118021. var url = this.getAssetUrl(data);
  118022. this._scene._loadFile(url, function (arrayBuffer) {
  118023. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  118024. if (onSuccess)
  118025. onSuccess(_this.environment);
  118026. }, function (progressEvent) { if (onProgress)
  118027. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  118028. if (onError) {
  118029. onError(e);
  118030. }
  118031. });
  118032. }
  118033. else {
  118034. //data assumed to be PBREnvironment object
  118035. this.environment = data;
  118036. if (onSuccess)
  118037. onSuccess(data);
  118038. }
  118039. };
  118040. /**
  118041. * Applies an `EnvironmentMapConfiguration` to the scene
  118042. * @param environmentMapConfiguration Environment map configuration to apply
  118043. */
  118044. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  118045. if (!this.environment)
  118046. return;
  118047. //set orientation
  118048. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0);
  118049. // Add env texture to the scene.
  118050. if (this.environment.specularTexture) {
  118051. // IE crashes when disposing the old texture and setting a new one
  118052. if (!this._scene.environmentTexture) {
  118053. this._scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._scene, this.environment.specularTexture, false, true);
  118054. }
  118055. if (this._scene.environmentTexture) {
  118056. this._scene.environmentTexture.level = this.environment.textureIntensityScale;
  118057. this._scene.environmentTexture.invertZ = true;
  118058. this._scene.environmentTexture.lodLevelInAlpha = true;
  118059. var poly = this._scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial();
  118060. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  118061. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  118062. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  118063. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  118064. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  118065. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  118066. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  118067. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  118068. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  118069. this._scene.environmentTexture.sphericalPolynomial = poly;
  118070. //set orientation
  118071. babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._scene.environmentTexture.getReflectionTextureMatrix());
  118072. }
  118073. }
  118074. };
  118075. /**
  118076. * Get an environment asset url by using the configuration if the path is not absolute.
  118077. * @param url Asset url
  118078. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  118079. */
  118080. ViewerLabs.prototype.getAssetUrl = function (url) {
  118081. var returnUrl = url;
  118082. if (url && url.toLowerCase().indexOf("//") === -1) {
  118083. if (!this.assetsRootURL) {
  118084. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  118085. return url;
  118086. }
  118087. returnUrl = this.assetsRootURL + returnUrl;
  118088. }
  118089. return returnUrl;
  118090. };
  118091. ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) {
  118092. if (point === void 0) { point = babylonjs_1.Vector3.Zero(); }
  118093. if (axis === void 0) { axis = babylonjs_1.Axis.Y; }
  118094. if (target === void 0) { target = babylonjs_1.Vector3.Zero(); }
  118095. axis.normalize();
  118096. point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]);
  118097. 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]);
  118098. babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]);
  118099. babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]);
  118100. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]);
  118101. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]);
  118102. babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]);
  118103. shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]);
  118104. shadowLight.setDirectionToTarget(target);
  118105. };
  118106. return ViewerLabs;
  118107. }());
  118108. exports.ViewerLabs = ViewerLabs;
  118109. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTGFicy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3ZpZXdlckxhYnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBa0Y7QUFFbEYsdUNBQW1IO0FBQ25ILHFDQUF5QztBQUV6Qzs7OztHQUlHO0FBQ0g7SUFFSSxvQkFBb0IsTUFBYTtRQUFiLFdBQU0sR0FBTixNQUFNLENBQU87UUFHMUIsZ0JBQVcsR0FBbUI7WUFDakMsWUFBWTt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***/ }),
  118111. /* 27 */
  118112. /***/ (function(module, exports, __webpack_require__) {
  118113. "use strict";
  118114. Object.defineProperty(exports, "__esModule", { value: true });
  118115. var babylonjs_1 = __webpack_require__(0);
  118116. var texture_1 = __webpack_require__(12);
  118117. /**
  118118. * A static class proving methods to aid parsing Spectre environment files
  118119. */
  118120. var EnvironmentDeserializer = /** @class */ (function () {
  118121. function EnvironmentDeserializer() {
  118122. }
  118123. /**
  118124. * Parses an arraybuffer into a new PBREnvironment object
  118125. * @param arrayBuffer The arraybuffer of the Spectre environment file
  118126. * @return a PBREnvironment object
  118127. */
  118128. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  118129. var environment = {
  118130. //irradiance
  118131. irradiancePolynomialCoefficients: {
  118132. x: new babylonjs_1.Vector3(0, 0, 0),
  118133. y: new babylonjs_1.Vector3(0, 0, 0),
  118134. z: new babylonjs_1.Vector3(0, 0, 0),
  118135. xx: new babylonjs_1.Vector3(0, 0, 0),
  118136. yy: new babylonjs_1.Vector3(0, 0, 0),
  118137. zz: new babylonjs_1.Vector3(0, 0, 0),
  118138. yz: new babylonjs_1.Vector3(0, 0, 0),
  118139. zx: new babylonjs_1.Vector3(0, 0, 0),
  118140. xy: new babylonjs_1.Vector3(0, 0, 0)
  118141. },
  118142. //specular
  118143. textureIntensityScale: 1.0,
  118144. };
  118145. //read .env
  118146. var littleEndian = false;
  118147. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  118148. var dataView = new DataView(arrayBuffer);
  118149. var pos = 0;
  118150. for (var i = 0; i < magicBytes.length; i++) {
  118151. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  118152. babylonjs_1.Tools.Error('Not a Spectre environment map');
  118153. }
  118154. }
  118155. var version = dataView.getUint16(pos, littleEndian);
  118156. pos += 2;
  118157. if (version !== 1) {
  118158. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  118159. }
  118160. //read json descriptor - collect characters up to null terminator
  118161. var descriptorString = '';
  118162. var charCode = 0x00;
  118163. while ((charCode = dataView.getUint8(pos++))) {
  118164. descriptorString += String.fromCharCode(charCode);
  118165. }
  118166. var descriptor = JSON.parse(descriptorString);
  118167. var payloadPos = pos;
  118168. //irradiance
  118169. switch (descriptor.irradiance.type) {
  118170. case 'irradiance_sh_coefficients_9':
  118171. //irradiance
  118172. var harmonics = descriptor.irradiance;
  118173. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  118174. //harmonics now represent radiance
  118175. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  118176. break;
  118177. default:
  118178. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  118179. }
  118180. //specular
  118181. switch (descriptor.specular.type) {
  118182. case 'cubemap_faces':
  118183. var specularDescriptor = descriptor.specular;
  118184. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  118185. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  118186. var mipmaps = specularDescriptor.mipmaps;
  118187. var imageType = specularDescriptor.imageType;
  118188. for (var l = 0; l < mipmaps.length; l++) {
  118189. var faceRanges = mipmaps[l];
  118190. specularTexture.source[l] = [];
  118191. for (var i = 0; i < 6; i++) {
  118192. var range = faceRanges[i];
  118193. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  118194. switch (imageType) {
  118195. case 'png':
  118196. //construct image element from bytes
  118197. var image = new Image();
  118198. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  118199. image.src = src;
  118200. specularTexture.source[l][i] = image;
  118201. break;
  118202. default:
  118203. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  118204. }
  118205. }
  118206. }
  118207. break;
  118208. default:
  118209. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  118210. }
  118211. return environment;
  118212. };
  118213. /**
  118214. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  118215. * L = (1/pi) * E * rho
  118216. *
  118217. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  118218. * @param harmonics Spherical harmonic coefficients (9)
  118219. */
  118220. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  118221. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  118222. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  118223. // (The pixel shader must apply albedo after texture fetches, etc).
  118224. };
  118225. /**
  118226. * Convert spherical harmonics to spherical polynomial coefficients
  118227. * @param harmonics Spherical harmonic coefficients (9)
  118228. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  118229. */
  118230. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  118231. var rPi = 1 / Math.PI;
  118232. //x
  118233. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  118234. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  118235. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  118236. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  118237. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  118238. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  118239. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  118240. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  118241. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  118242. //xx
  118243. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  118244. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  118245. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  118246. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  118247. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  118248. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  118249. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  118250. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  118251. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  118252. //yz
  118253. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  118254. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  118255. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  118256. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  118257. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  118258. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  118259. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  118260. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  118261. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  118262. };
  118263. /**
  118264. * Multiplies harmonic coefficients in place
  118265. * @param harmonics Spherical harmonic coefficients (9)
  118266. * @param scaleFactor Value to multiply by
  118267. */
  118268. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  118269. harmonics.l00[0] *= scaleFactor;
  118270. harmonics.l00[1] *= scaleFactor;
  118271. harmonics.l00[2] *= scaleFactor;
  118272. harmonics.l1_1[0] *= scaleFactor;
  118273. harmonics.l1_1[1] *= scaleFactor;
  118274. harmonics.l1_1[2] *= scaleFactor;
  118275. harmonics.l10[0] *= scaleFactor;
  118276. harmonics.l10[1] *= scaleFactor;
  118277. harmonics.l10[2] *= scaleFactor;
  118278. harmonics.l11[0] *= scaleFactor;
  118279. harmonics.l11[1] *= scaleFactor;
  118280. harmonics.l11[2] *= scaleFactor;
  118281. harmonics.l2_2[0] *= scaleFactor;
  118282. harmonics.l2_2[1] *= scaleFactor;
  118283. harmonics.l2_2[2] *= scaleFactor;
  118284. harmonics.l2_1[0] *= scaleFactor;
  118285. harmonics.l2_1[1] *= scaleFactor;
  118286. harmonics.l2_1[2] *= scaleFactor;
  118287. harmonics.l20[0] *= scaleFactor;
  118288. harmonics.l20[1] *= scaleFactor;
  118289. harmonics.l20[2] *= scaleFactor;
  118290. harmonics.l21[0] *= scaleFactor;
  118291. harmonics.l21[1] *= scaleFactor;
  118292. harmonics.l21[2] *= scaleFactor;
  118293. harmonics.l22[0] *= scaleFactor;
  118294. harmonics.l22[1] *= scaleFactor;
  118295. harmonics.l22[2] *= scaleFactor;
  118296. };
  118297. return EnvironmentDeserializer;
  118298. }());
  118299. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  118300. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRTZXJpYWxpemVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2xhYnMvZW52aXJvbm1lbnRTZXJpYWxpemVyLnRzIl0sIm5hbWVzIj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QUFTLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNqQyxTQUFTLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNqQyxTQUFTLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNqQyxTQUFTLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNqQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztJQUNwQyxDQUFDO0lBQ0wsOEJBQUM7QUFBRCxDQUFDLEFBck5ELElBcU5DO0FBck5ZLDBEQUF1QiJ9
  118301. /***/ }),
  118302. /* 28 */
  118303. /***/ (function(module, exports, __webpack_require__) {
  118304. "use strict";
  118305. Object.defineProperty(exports, "__esModule", { value: true });
  118306. var extended_1 = __webpack_require__(29);
  118307. var cache = {};
  118308. /**
  118309. *
  118310. * @param name the name of the custom optimizer configuration
  118311. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  118312. */
  118313. function getCustomOptimizerByName(name, upgrade) {
  118314. if (!cache[name]) {
  118315. switch (name) {
  118316. case 'extended':
  118317. if (upgrade) {
  118318. return extended_1.extendedUpgrade;
  118319. }
  118320. else {
  118321. return extended_1.extendedDegrade;
  118322. }
  118323. }
  118324. }
  118325. return cache[name];
  118326. }
  118327. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  118328. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4RDtBQUc5RCxJQUFNLEtBQUssR0FBK0QsRUFBRSxDQUFDO0FBRTdFOzs7O0dBSUc7QUFDSCxrQ0FBeUMsSUFBWSxFQUFFLE9BQWlCO0lBQ3BFLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEVBQUU7UUFDZCxRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssVUFBVTtnQkFDWCxJQUFJLE9BQU8sRUFBRTtvQkFDVCxPQUFPLDBCQUFlLENBQUM7aUJBQzFCO3FCQUNJO29CQUNELE9BQU8sMEJBQWUsQ0FBQztpQkFDMUI7U0FDUjtLQUNKO0lBRUQsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQWRELDREQWNDIn0=
  118329. /***/ }),
  118330. /* 29 */
  118331. /***/ (function(module, exports, __webpack_require__) {
  118332. "use strict";
  118333. Object.defineProperty(exports, "__esModule", { value: true });
  118334. var babylonjs_1 = __webpack_require__(0);
  118335. /**
  118336. * A custom upgrade-oriented function configuration for the scene optimizer.
  118337. *
  118338. * @param viewer the viewer to optimize
  118339. */
  118340. function extendedUpgrade(sceneManager) {
  118341. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  118342. // if (!this.Scene.BackgroundHelper) {
  118343. // this.Scene.EngineScene.autoClear = false;
  118344. // this.Scene.BackgroundHelper = true;
  118345. // Would require a dedicated clear color;
  118346. // return false;
  118347. // }
  118348. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > 1) {
  118349. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, 1);
  118350. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  118351. return false;
  118352. }
  118353. if (!sceneManager.scene.postProcessesEnabled) {
  118354. sceneManager.scene.postProcessesEnabled = true;
  118355. return false;
  118356. }
  118357. if (!sceneManager.groundEnabled) {
  118358. sceneManager.groundEnabled = true;
  118359. return false;
  118360. }
  118361. if (defaultPipeline && !sceneManager.fxaaEnabled) {
  118362. sceneManager.fxaaEnabled = true;
  118363. return false;
  118364. }
  118365. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  118366. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > hardwareScalingLevel) {
  118367. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  118368. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  118369. return false;
  118370. }
  118371. if (!sceneManager.processShadows) {
  118372. sceneManager.processShadows = true;
  118373. return false;
  118374. }
  118375. if (defaultPipeline && !sceneManager.bloomEnabled) {
  118376. sceneManager.bloomEnabled = true;
  118377. return false;
  118378. }
  118379. if (!sceneManager.groundMirrorEnabled) {
  118380. sceneManager.groundMirrorEnabled = true;
  118381. return false;
  118382. }
  118383. return true;
  118384. }
  118385. exports.extendedUpgrade = extendedUpgrade;
  118386. /**
  118387. * A custom degrade-oriented function configuration for the scene optimizer.
  118388. *
  118389. * @param viewer the viewer to optimize
  118390. */
  118391. function extendedDegrade(sceneManager) {
  118392. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  118393. if (sceneManager.groundMirrorEnabled) {
  118394. sceneManager.groundMirrorEnabled = false;
  118395. return false;
  118396. }
  118397. if (defaultPipeline && sceneManager.bloomEnabled) {
  118398. sceneManager.bloomEnabled = false;
  118399. return false;
  118400. }
  118401. if (sceneManager.processShadows) {
  118402. sceneManager.processShadows = false;
  118403. return false;
  118404. }
  118405. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1) {
  118406. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1);
  118407. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  118408. return false;
  118409. }
  118410. if (defaultPipeline && sceneManager.fxaaEnabled) {
  118411. sceneManager.fxaaEnabled = false;
  118412. return false;
  118413. }
  118414. if (sceneManager.groundEnabled) {
  118415. sceneManager.groundEnabled = false;
  118416. return false;
  118417. }
  118418. if (sceneManager.scene.postProcessesEnabled) {
  118419. sceneManager.scene.postProcessesEnabled = false;
  118420. return false;
  118421. }
  118422. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1.25) {
  118423. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1.25);
  118424. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  118425. return false;
  118426. }
  118427. // if (this.Scene.BackgroundHelper) {
  118428. // this.Scene.EngineScene.autoClear = true;
  118429. // this.Scene.BackgroundHelper = false;
  118430. // Would require a dedicated clear color;
  118431. // return false;
  118432. // }
  118433. return true;
  118434. }
  118435. exports.extendedDegrade = extendedDegrade;
  118436. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6W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UMsV0FBVyxHQUFHLEtBQUssQ0FBQztRQUNqQyxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLGFBQWEsRUFBRTtRQUM1QixZQUFZLENBQUMsYUFBYSxHQUFHLEtBQUssQ0FBQztRQUNuQyxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLEtBQUssQ0FBQyxvQkFBb0IsRUFBRTtRQUN6QyxZQUFZLENBQUMsS0FBSyxDQUFDLG9CQUFvQixHQUFHLEtBQUssQ0FBQztRQUNoRCxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLEtBQUssQ0FBQyxTQUFTLEVBQUUsQ0FBQyx1QkFBdUIsRUFBRSxHQUFHLElBQUksRUFBRTtRQUNqRSxJQUFJLE9BQU8sR0FBRyxrQkFBTSxDQUFDLEtBQUssQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixFQUFFLEdBQUcsSUFBSSxFQUFFLENBQUMsRUFBRSxJQUFJLENBQUMsQ0FBQztRQUNyRyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQ2hFLE9BQU8sS0FBSyxDQUFDO0tBQ2hCO0lBQ0QscUNBQXFDO0lBQ3JDLDRDQUE0QztJQUM1Qyx1Q0FBdUM7SUFDdkMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osT0FBTyxJQUFJLENBQUM7QUFDaEIsQ0FBQztBQTVDRCwwQ0E0Q0MifQ==
  118437. /***/ }),
  118438. /* 30 */
  118439. /***/ (function(module, exports, __webpack_require__) {
  118440. "use strict";
  118441. Object.defineProperty(exports, "__esModule", { value: true });
  118442. var mappers_1 = __webpack_require__(3);
  118443. var types_1 = __webpack_require__(31);
  118444. var configurationCompatibility_1 = __webpack_require__(55);
  118445. var _1 = __webpack_require__(1);
  118446. var babylonjs_1 = __webpack_require__(0);
  118447. /**
  118448. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  118449. * parse the object and return a conform ViewerConfiguration.
  118450. * It is a private member of the scene.
  118451. */
  118452. var ConfigurationLoader = /** @class */ (function () {
  118453. function ConfigurationLoader(_enableCache) {
  118454. if (_enableCache === void 0) { _enableCache = false; }
  118455. this._enableCache = _enableCache;
  118456. this._configurationCache = {};
  118457. this._loadRequests = [];
  118458. }
  118459. /**
  118460. * load a configuration object that is defined in the initial configuration provided.
  118461. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  118462. *
  118463. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  118464. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  118465. * @returns A promise that delivers the extended viewer configuration, when done.
  118466. */
  118467. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  118468. var _this = this;
  118469. if (initConfig === void 0) { initConfig = {}; }
  118470. var loadedConfig = _1.deepmerge({}, initConfig);
  118471. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  118472. if (loadedConfig.configuration) {
  118473. var mapperType_1 = "json";
  118474. return Promise.resolve().then(function () {
  118475. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  118476. // a file to load
  118477. var url = '';
  118478. if (typeof loadedConfig.configuration === "string") {
  118479. url = loadedConfig.configuration;
  118480. }
  118481. // if configuration is an object
  118482. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  118483. url = loadedConfig.configuration.url;
  118484. var type = loadedConfig.configuration.mapper;
  118485. // empty string?
  118486. if (!type) {
  118487. // load mapper type from filename / url
  118488. type = loadedConfig.configuration.url.split('.').pop();
  118489. }
  118490. mapperType_1 = type || mapperType_1;
  118491. }
  118492. return _this._loadFile(url);
  118493. }
  118494. else {
  118495. if (typeof loadedConfig.configuration === "object") {
  118496. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  118497. return loadedConfig.configuration.payload || {};
  118498. }
  118499. return {};
  118500. }
  118501. }).then(function (data) {
  118502. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  118503. var parsed = _1.deepmerge(mapper.map(data), loadedConfig);
  118504. var merged = _1.deepmerge(extendedConfiguration, parsed);
  118505. configurationCompatibility_1.processConfigurationCompatibility(merged);
  118506. if (callback)
  118507. callback(merged);
  118508. return merged;
  118509. });
  118510. }
  118511. else {
  118512. loadedConfig = _1.deepmerge(extendedConfiguration, loadedConfig);
  118513. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  118514. if (callback)
  118515. callback(loadedConfig);
  118516. return Promise.resolve(loadedConfig);
  118517. }
  118518. };
  118519. /**
  118520. * Dispose the configuration loader. This will cancel file requests, if active.
  118521. */
  118522. ConfigurationLoader.prototype.dispose = function () {
  118523. this._loadRequests.forEach(function (request) {
  118524. request.abort();
  118525. });
  118526. this._loadRequests.length = 0;
  118527. };
  118528. ConfigurationLoader.prototype._loadFile = function (url) {
  118529. var _this = this;
  118530. var cacheReference = this._configurationCache;
  118531. if (this._enableCache && cacheReference[url]) {
  118532. return Promise.resolve(cacheReference[url]);
  118533. }
  118534. return new Promise(function (resolve, reject) {
  118535. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  118536. var idx = _this._loadRequests.indexOf(fileRequest);
  118537. if (idx !== -1)
  118538. _this._loadRequests.splice(idx, 1);
  118539. if (_this._enableCache)
  118540. cacheReference[url] = result;
  118541. resolve(result);
  118542. }, undefined, undefined, false, function (request, error) {
  118543. var idx = _this._loadRequests.indexOf(fileRequest);
  118544. if (idx !== -1)
  118545. _this._loadRequests.splice(idx, 1);
  118546. reject(error);
  118547. });
  118548. _this._loadRequests.push(fileRequest);
  118549. });
  118550. };
  118551. return ConfigurationLoader;
  118552. }());
  118553. exports.ConfigurationLoader = ConfigurationLoader;
  118554. //# sourceMappingURL=data:application/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kFDdEMsTUFBTSxDQUFDLEtBQUssQ0FBQyxDQUFDO1lBQ2xCLENBQUMsQ0FBQyxDQUFDO1lBQ0gsS0FBSSxDQUFDLGFBQWEsQ0FBQyxJQUFJLENBQUMsV0FBVyxDQUFDLENBQUM7UUFDekMsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUwsMEJBQUM7QUFBRCxDQUFDLEFBMUdELElBMEdDO0FBMUdZLGtEQUFtQiJ9
  118555. /***/ }),
  118556. /* 31 */
  118557. /***/ (function(module, exports, __webpack_require__) {
  118558. "use strict";
  118559. Object.defineProperty(exports, "__esModule", { value: true });
  118560. var minimal_1 = __webpack_require__(32);
  118561. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  118562. var default_1 = __webpack_require__(51);
  118563. exports.defaultConfiguration = default_1.defaultConfiguration;
  118564. var extended_1 = __webpack_require__(52);
  118565. var shadowLight_1 = __webpack_require__(53);
  118566. var environmentMap_1 = __webpack_require__(54);
  118567. var _1 = __webpack_require__(1);
  118568. /**
  118569. * Get the configuration type you need to use as the base for your viewer.
  118570. * The types can either be a single string, or comma separated types that will extend each other. for example:
  118571. *
  118572. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  118573. *
  118574. * @param types a comma-separated string of the type(s) or configuration to load.
  118575. */
  118576. var getConfigurationType = function (types) {
  118577. var config = {};
  118578. var typesSeparated = types.split(",");
  118579. typesSeparated.forEach(function (type) {
  118580. switch (type.trim()) {
  118581. case 'environmentMap':
  118582. config = _1.deepmerge(config, environmentMap_1.environmentMapConfiguration);
  118583. break;
  118584. case 'shadowDirectionalLight':
  118585. config = _1.deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  118586. break;
  118587. case 'shadowSpotLight':
  118588. config = _1.deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  118589. break;
  118590. case 'extended':
  118591. config = _1.deepmerge(config, extended_1.extendedConfiguration);
  118592. break;
  118593. case 'minimal':
  118594. config = _1.deepmerge(config, minimal_1.minimalConfiguration);
  118595. break;
  118596. case 'none':
  118597. break;
  118598. case 'default':
  118599. default:
  118600. config = _1.deepmerge(config, default_1.defaultConfiguration);
  118601. break;
  118602. }
  118603. if (config.extends) {
  118604. config = _1.deepmerge(config, getConfigurationType(config.extends));
  118605. }
  118606. });
  118607. return config;
  118608. };
  118609. exports.getConfigurationType = getConfigurationType;
  118610. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHFDQUFpRDtBQW9ESSwrQkFwRDVDLDhCQUFvQixDQW9ENEM7QUFuRHpFLHFDQUFpRDtBQW1EbEIsK0JBbkR0Qiw4QkFBb0IsQ0FtRHNCO0FBbERuRCx1Q0FBbUQ7QUFFbkQsNkNBQW1HO0FBQ25HLG1EQUErRDtBQUMvRCxrQ0FBMEM7QUFFMUM7Ozs7Ozs7R0FPRztBQUNILElBQUksb0JBQW9CLEdBQUcsVUFBVSxLQUFhO0lBQzlDLElBQUksTUFBTSxHQUF3QixFQUFFLENBQUM7SUFDckMsSUFBSSxjQUFjLEdBQUcsS0FBSyxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN0QyxjQUFjLENBQUMsT0FBTyxDQUFDLFVBQUEsSUFBSTtRQUN2QixRQUFRLElBQUksQ0FBQyxJQUFJLEVBQUUsRUFBRTtZQUNqQixLQUFLLGdCQUFnQjtnQkFDakIsTUFBTSxHQUFHLFlBQVMsQ0FBQyxNQUFNLEVBQUUsNENBQTJCLENBQUMsQ0FBQztnQkFDeEQsTUFBTTtZQUNWLEtBQUssd0JBQXdCO2dCQUN6QixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxpREFBbUMsQ0FBQyxDQUFDO2dCQUNoRSxNQUFNO1lBQ1YsS0FBSyxpQkFBaUI7Z0JBQ2xCLE1BQU0sR0FBRyxZQUFTLENBQUMsTUFBTSxFQUFFLDJDQUE2QixDQUFDLENBQUM7Z0JBQzFELE1BQU07WUFDVixLQUFLLFVBQVU7Z0JBQ1gsTUFBTSxHQUFHLFlBQVMsQ0FBQyxNQUFNLEVBQUUsZ0NBQXFCLENBQUMsQ0FBQztnQkFDbEQsTUFBTTtZQUNWLEtBQUssU0FBUztnQkFDVixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSw4QkFBb0IsQ0FBQyxDQUFDO2dCQUNqRCxNQUFNO1lBQ1YsS0FBSyxNQUFNO2dCQUNQLE1BQU07WUFDVixLQUFLLFNBQVMsQ0FBQztZQUNmO2dCQUNJLE1BQU0sR0FBRyxZQUFTLENBQUMsTUFBTSxFQUFFLDhCQUFvQixDQUFDLENBQUM7Z0JBQ2pELE1BQU07U0FDYjtRQUVELElBQUksTUFBTSxDQUFDLE9BQU8sRUFBRTtZQUNoQixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxvQkFBb0IsQ0FBQyxNQUFNLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQztTQUNwRTtJQUNMLENBQUMsQ0FBQyxDQUFDO0lBQ0gsT0FBTyxNQUFNLENBQUM7QUFFbEIsQ0FBQyxDQUFBO0FBRVEsb0RBQW9CIn0=
  118611. /***/ }),
  118612. /* 32 */
  118613. /***/ (function(module, exports, __webpack_require__) {
  118614. "use strict";
  118615. Object.defineProperty(exports, "__esModule", { value: true });
  118616. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  118617. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  118618. /**
  118619. * The minimal configuration needed to make the viewer work.
  118620. * Some functionalities might not work correctly (like fill-screen)
  118621. */
  118622. exports.minimalConfiguration = {
  118623. version: "0.1",
  118624. templates: {
  118625. main: {
  118626. html: babylonjs_viewer_assets_1.defaultTemplate
  118627. },
  118628. fillContainer: {
  118629. html: babylonjs_viewer_assets_1.fillContainer,
  118630. params: {
  118631. disable: false
  118632. }
  118633. },
  118634. loadingScreen: {
  118635. html: babylonjs_viewer_assets_1.loadingScreen,
  118636. params: {
  118637. backgroundColor: "#000000",
  118638. loadingImage: babylonjs_viewer_assets_2.loading
  118639. }
  118640. },
  118641. viewer: {
  118642. html: babylonjs_viewer_assets_1.defaultViewer,
  118643. },
  118644. overlay: {
  118645. html: babylonjs_viewer_assets_1.overlay,
  118646. params: {
  118647. closeImage: babylonjs_viewer_assets_2.close,
  118648. closeText: 'Close'
  118649. }
  118650. },
  118651. error: {
  118652. html: babylonjs_viewer_assets_1.error
  118653. }
  118654. },
  118655. engine: {
  118656. antialiasing: true
  118657. }
  118658. };
  118659. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWluaW1hbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL21pbmltYWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBdUg7QUFDdkgsbUVBQXlEO0FBRXpEOzs7R0FHRztBQUNRLFFBQUEsb0JBQW9CLEdBQXdCO0lBQ25ELE9BQU8sRUFBRSxLQUFLO0lBQ2QsU0FBUyxFQUFFO1FBQ1AsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLHlDQUFlO1NBQ3hCO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixPQUFPLEVBQUUsS0FBSzthQUNqQjtTQUNKO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixlQUFlLEVBQUUsU0FBUztnQkFDMUIsWUFBWSxFQUFFLGlDQUFPO2FBQ3hCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsdUNBQWE7U0FDdEI7UUFDRCxPQUFPLEVBQUU7WUFDTCxJQUFJLEVBQUUsaUNBQU87WUFDYixNQUFNLEVBQUU7Z0JBQ0osVUFBVSxFQUFFLCtCQUFLO2dCQUNqQixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7S0FFSjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0NBQ0osQ0FBQSJ9
  118660. /***/ }),
  118661. /* 33 */
  118662. /***/ (function(module, exports, __webpack_require__) {
  118663. "use strict";
  118664. Object.defineProperty(exports, "__esModule", { value: true });
  118665. exports.babylonFont = __webpack_require__(34);
  118666. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9udC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9hc3NldHMvZm9udC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFhLFFBQUEsV0FBVyxHQUFHLE9BQU8sQ0FBQywyQkFBMkIsQ0FBQyxDQUFDIn0=
  118667. /***/ }),
  118668. /* 34 */
  118669. /***/ (function(module, exports) {
  118670. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABTkAA8AAAAAJEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEgAAABgSlp+MVZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAACIAAAA3oTfhSJjdnQgAAAEMAAAACAAAAAqCdkJr2ZwZ20AAARQAAAA8AAAAVn8nuaOZ2FzcAAABUAAAAAMAAAADAAIABtnbHlmAAAFTAAACPgAAAzOOMLcQmhlYW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fc5curD3a5ITOgf552HFCR74ui9jbGP5vbefsKTFNQGZojh11LpnN6qIMOu9Px3WtNwOYSZuLI3/dW4D8ba4pSGrKXNNb+azZE4emSlJftF/brFpc0ZtVkSVG23Wz40HNnN7kf57R9qtW+M7M2bs3RPkq4/xgvCOqdNvb+RdZ0AR35z/h1P9ay0PfZPoqH7oH79Gr0Wb0fvRu9DasVw4xFWB/B/QeUd2KNsrg++CbkFE3d0DTQLyYjfgbYLuFq3jaY2BmAIP/fgzlDFgAACkqAcgAeNrbwKDNsImRk0mbcRMXiNzO1ZobaqvKwKG9nTs12EFPBsTiifCw0JAEsXidzbXlhUEsPh0VGREeEItfTkKYjwPEEuDj4WRnAbEEwQDEEtowoSDAAMhi2M4IN5oJbjQz3GgWuNGscKPZ5CShRrPDjeaAG80JN3qTMCO79gYGBdfaTAkXAMQBKBoAAAA="
  118671. /***/ }),
  118672. /* 35 */
  118673. /***/ (function(module, exports, __webpack_require__) {
  118674. "use strict";
  118675. Object.defineProperty(exports, "__esModule", { value: true });
  118676. exports.babylonLogo = __webpack_require__(36);
  118677. exports.close = __webpack_require__(37);
  118678. exports.fullscreen = __webpack_require__(38);
  118679. exports.helpCircle = __webpack_require__(39);
  118680. exports.loading = __webpack_require__(40);
  118681. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW1nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy9pbWcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLFdBQVcsR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUNuRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsNEJBQTRCLENBQUMsQ0FBQztBQUM5QyxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsaUNBQWlDLENBQUMsQ0FBQztBQUN4RCxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsa0NBQWtDLENBQUMsQ0FBQztBQUN6RCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsOEJBQThCLENBQUMsQ0FBQyJ9
  118682. /***/ }),
  118683. /* 36 */
  118684. /***/ (function(module, exports) {
  118685. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB7MAAAgHCAYAAABZmyd0AAAACXBIWXMAAC4jAAAuIwF4pT92AAAgAElEQVR42uzd7XEb6Zm24Wtc+5/IgO0IyDcCtiMQNwLBEYgTgaAIhhOBpQhMRSAwghEjWCoCixHw/fE0DIKiKAIE+vM4qlDi1I531/fYRDdOPHf/dn9/HwAAAAAmb5bkNMnSKAAAgD74HyMAAAAAmJwqJVyfJqmbP4+a/9m3JIskH40JAADo0m9OZgMAAACM2ukTr6MX/OtEbQAAoFNiNgAAAMB41FkH6yrJ2R7+d4raAABAJ8RsAAAAgOFZPd+6znpl+MmB/2+K2gAAQKvEbAAAAIB+q/LjmvDjDv//EbUBAIBWiNkAAAAA/bFaD746df3S51t3QdQGAAAOSswGAAAA6Mbj09ZnA/33IWoDAAAHIWYDAAAAHF6dzXB9MsJ/j6I2AACwV2I2AAAAwP7MsrkivOvnW3dB1AYAAPZCzAYAAADYTZV1sK6bvz42lv8StQEAgFcRswEAAAB+bRWtq6xPXR8Zy4uI2gAAwE7EbAAAAIBNddbh+jTJmZHshagNAABsRcwGAAAApmr1fOuHrxNjOThRGwAAeBExGwAAAJiCVbiusw7Xnm/dLVEbAAB4lpgNAAAAjE2VdbCu4/nWfSdqAwAATxKzAQAAgCF7vCbc862HS9QGAAA2iNkAAADAUNRZR+sqwvVYidoAAEASMRsAAADon4fPt66an0+MZXJEbQAAmDgxGwAAAOhSlR9XhR8bCw+I2gAAMFFiNgAAANCW1Xrw1anr0yRHxsILidoAADAxYjYAAABwCHU2T117vjX7ImoDAMBEiNkAAADAa9XZXBPu+da0QdQGAICRE7MBAACAl5plc0W451vTB6I2AACMlJgNAAAA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AOCZlNkAAPTNLMnlwJ9hk1JgNz5OAAAAAHgeZTYAAH00T/JhYL/mXcp7v+dJ1j5CAAAAAHgZZTYAAH21SvJ2AL/O+xX2Msmtjw0AAAAA2qHMBgCgryYpC+fXPfy1WWEDAAAAQMeU2QAA9Nk0ZaF90pNfzzb7d2FbYQMAAABAh5TZAAD03SzJ5ZF/DYuUAnvl4wAAAACAw1BmAwAwBE2S8wP/f1phAwAAAMARKbMBABiKdZLTA/z/WGEDAAAAQA8oswEAGIpJkpt08/7sbUqBPY8VNgAAAAD0gjIbAIAhmSb51uL/3lVKib0ULQAAAAD0izIbAIChmSW5fMHff7/CblKW3gAAAABADymzAQAYoibJ+RP/HitsAAAAABgQZTYAAEO1TnL6i79ml/27sG9EBgAAAADDocwGAGCo3qQU2icP/HfX2Z8SBwAAAAAGSJkNAMCQnSX5evefrbABAAAAoCLKbAAAhu5dkkmssAEAAACgKv8F3qtfY+YVvDIAAAAASUVORK5CYII="
  118686. /***/ }),
  118687. /* 37 */
  118688. /***/ (function(module, exports) {
  118689. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  118690. /***/ }),
  118691. /* 38 */
  118692. /***/ (function(module, exports) {
  118693. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  118694. /***/ }),
  118695. /* 39 */
  118696. /***/ (function(module, exports) {
  118697. 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=="
  118698. /***/ }),
  118699. /* 40 */
  118700. /***/ (function(module, exports) {
  118701. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTK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5t94G6VV6khQs3h7zSUMnAs6q7S87xRoiiBH/2UYF+YMjra8ifR40IjeLc30vmeAlxXoAn7AV6L9r9K0oOcELVnhUD51k5w1mForNtjB8YjV4WeWOZ4yG52gryhF0K30uPraYciNZT076gXFPnSWfVanxvYK/WpElHxMs3IpXlWOgi4sQ8L1IBp4laFc0/iO/WZKR84c9EJE8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  118702. /***/ }),
  118703. /* 41 */
  118704. /***/ (function(module, exports, __webpack_require__) {
  118705. "use strict";
  118706. Object.defineProperty(exports, "__esModule", { value: true });
  118707. exports.defaultTemplate = __webpack_require__(42);
  118708. exports.defaultViewer = __webpack_require__(43);
  118709. exports.error = __webpack_require__(44);
  118710. exports.fillContainer = __webpack_require__(45);
  118711. exports.help = __webpack_require__(46);
  118712. exports.loadingScreen = __webpack_require__(47);
  118713. exports.navbar = __webpack_require__(48);
  118714. exports.overlay = __webpack_require__(49);
  118715. exports.share = __webpack_require__(50);
  118716. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy90ZW1wbGF0ZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLGVBQWUsR0FBRyxPQUFPLENBQUMscURBQXFELENBQUMsQ0FBQztBQUNqRixRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUM3RCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLElBQUksR0FBRyxPQUFPLENBQUMsMENBQTBDLENBQUMsQ0FBQztBQUMzRCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLE1BQU0sR0FBRyxPQUFPLENBQUMsNENBQTRDLENBQUMsQ0FBQztBQUMvRCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsNkNBQTZDLENBQUMsQ0FBQztBQUNqRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQyJ9
  118717. /***/ }),
  118718. /* 42 */
  118719. /***/ (function(module, exports) {
  118720. 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>";
  118721. /***/ }),
  118722. /* 43 */
  118723. /***/ (function(module, exports) {
  118724. 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>";
  118725. /***/ }),
  118726. /* 44 */
  118727. /***/ (function(module, exports) {
  118728. module.exports = "Error loading the model";
  118729. /***/ }),
  118730. /* 45 */
  118731. /***/ (function(module, exports) {
  118732. 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>";
  118733. /***/ }),
  118734. /* 46 */
  118735. /***/ (function(module, exports) {
  118736. module.exports = "HELP";
  118737. /***/ }),
  118738. /* 47 */
  118739. /***/ (function(module, exports) {
  118740. 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}}>";
  118741. /***/ }),
  118742. /* 48 */
  118743. /***/ (function(module, exports) {
  118744. 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>";
  118745. /***/ }),
  118746. /* 49 */
  118747. /***/ (function(module, exports) {
  118748. 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>";
  118749. /***/ }),
  118750. /* 50 */
  118751. /***/ (function(module, exports) {
  118752. module.exports = "SHARE";
  118753. /***/ }),
  118754. /* 51 */
  118755. /***/ (function(module, exports, __webpack_require__) {
  118756. "use strict";
  118757. Object.defineProperty(exports, "__esModule", { value: true });
  118758. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  118759. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  118760. var images = __webpack_require__(2);
  118761. /**
  118762. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  118763. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  118764. */
  118765. exports.defaultConfiguration = {
  118766. version: "3.2.0-alpha4",
  118767. templates: {
  118768. main: {
  118769. html: babylonjs_viewer_assets_1.defaultTemplate,
  118770. params: {
  118771. babylonFont: babylonjs_viewer_assets_2.babylonFont,
  118772. noEscape: true
  118773. }
  118774. },
  118775. fillContainer: {
  118776. html: babylonjs_viewer_assets_1.fillContainer,
  118777. params: {
  118778. disable: false
  118779. }
  118780. },
  118781. loadingScreen: {
  118782. html: babylonjs_viewer_assets_1.loadingScreen,
  118783. params: {
  118784. backgroundColor: "#000000",
  118785. loadingImage: images.loading
  118786. }
  118787. },
  118788. viewer: {
  118789. html: babylonjs_viewer_assets_1.defaultViewer,
  118790. params: {
  118791. enableDragAndDrop: false
  118792. }
  118793. },
  118794. navBar: {
  118795. html: babylonjs_viewer_assets_1.navbar,
  118796. params: {
  118797. speedList: {
  118798. "0.5x": "0.5",
  118799. "1.0x": "1.0",
  118800. "1.5x": "1.5",
  118801. "2.0x": "2.0",
  118802. },
  118803. logoImage: images.babylonLogo,
  118804. logoText: 'BabylonJS',
  118805. logoLink: 'https://babylonjs.com',
  118806. hideHelp: true,
  118807. hideHd: true,
  118808. hideVr: true,
  118809. disableOnFullscreen: false,
  118810. text: {
  118811. hdButton: "Toggle HD",
  118812. fullscreenButton: "Fullscreen",
  118813. helpButton: "Help",
  118814. vrButton: "Toggle VR"
  118815. }
  118816. },
  118817. events: {
  118818. pointerdown: {
  118819. '.navbar-control': true,
  118820. '.help-button': true
  118821. },
  118822. input: {
  118823. '.progress-wrapper': true
  118824. },
  118825. pointerup: {
  118826. '.progress-wrapper': true
  118827. }
  118828. }
  118829. },
  118830. overlay: {
  118831. html: babylonjs_viewer_assets_1.overlay,
  118832. params: {
  118833. closeImage: images.close,
  118834. closeText: 'Close'
  118835. }
  118836. },
  118837. help: {
  118838. html: babylonjs_viewer_assets_1.help
  118839. },
  118840. share: {
  118841. html: babylonjs_viewer_assets_1.share
  118842. },
  118843. error: {
  118844. html: babylonjs_viewer_assets_1.error
  118845. }
  118846. },
  118847. camera: {
  118848. behaviors: {
  118849. autoRotate: {
  118850. type: 0
  118851. },
  118852. framing: {
  118853. type: 2,
  118854. zoomOnBoundingInfo: true,
  118855. zoomStopsAnimation: false
  118856. },
  118857. bouncing: {
  118858. type: 1
  118859. }
  118860. }
  118861. },
  118862. skybox: {},
  118863. ground: {
  118864. receiveShadows: true
  118865. },
  118866. engine: {
  118867. antialiasing: true
  118868. },
  118869. scene: {}
  118870. };
  118871. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL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VBQUUsS0FBSzthQUM1QjtZQUNELFFBQVEsRUFBRTtnQkFDTixJQUFJLEVBQUUsQ0FBQzthQUNWO1NBQ0o7S0FDSjtJQUNELE1BQU0sRUFBRSxFQUNQO0lBQ0QsTUFBTSxFQUFFO1FBQ0osY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxNQUFNLEVBQUU7UUFDSixZQUFZLEVBQUUsSUFBSTtLQUNyQjtJQUNELEtBQUssRUFBRSxFQUNOO0NBQ0osQ0FBQSJ9
  118872. /***/ }),
  118873. /* 52 */
  118874. /***/ (function(module, exports, __webpack_require__) {
  118875. "use strict";
  118876. Object.defineProperty(exports, "__esModule", { value: true });
  118877. var babylonjs_1 = __webpack_require__(0);
  118878. /**
  118879. * The viewer's "extended" configuration.
  118880. * This configuration defines specific obejcts and parameters that we think make any model look good.
  118881. */
  118882. exports.extendedConfiguration = {
  118883. version: "3.2.0",
  118884. extends: "default",
  118885. camera: {
  118886. exposure: 3.034578,
  118887. fov: 0.7853981633974483,
  118888. contrast: 1.6,
  118889. toneMappingEnabled: true,
  118890. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  118891. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  118892. behaviors: {
  118893. framing: {
  118894. type: 2,
  118895. mode: 0,
  118896. positionScale: 0.5,
  118897. defaultElevation: 0.2617993877991494,
  118898. elevationReturnWaitTime: 3000,
  118899. elevationReturnTime: 2000,
  118900. framingTime: 500,
  118901. zoomStopsAnimation: false,
  118902. radiusScale: 0.866
  118903. },
  118904. autoRotate: {
  118905. type: 0,
  118906. idleRotationWaitTime: 4000,
  118907. idleRotationSpeed: 0.17453292519943295,
  118908. idleRotationSpinupTime: 2500,
  118909. zoomStopsAnimation: false
  118910. },
  118911. bouncing: {
  118912. type: 1,
  118913. lowerRadiusTransitionRange: 0.05,
  118914. upperRadiusTransitionRange: -0.2
  118915. }
  118916. },
  118917. upperRadiusLimit: 5,
  118918. lowerRadiusLimit: 0.5,
  118919. frameOnModelLoad: true,
  118920. framingElevation: 0.2617993877991494,
  118921. framingRotation: 1.5707963267948966,
  118922. radius: 2,
  118923. alpha: 1.5708,
  118924. beta: Math.PI * 0.5 - 0.2618,
  118925. wheelPrecision: 300,
  118926. minZ: 0.1,
  118927. maxZ: 50,
  118928. fovMode: 0,
  118929. pinchPrecision: 1500,
  118930. panningSensibility: 3000
  118931. },
  118932. lights: {
  118933. light0: {
  118934. type: 0,
  118935. frustumEdgeFalloff: 0,
  118936. intensity: 7,
  118937. intensityMode: 0,
  118938. radius: 0.6,
  118939. range: 0.6,
  118940. spotAngle: 60,
  118941. diffuse: {
  118942. r: 1,
  118943. g: 1,
  118944. b: 1
  118945. },
  118946. position: {
  118947. x: -2,
  118948. y: 2.5,
  118949. z: 2
  118950. },
  118951. target: {
  118952. x: 0,
  118953. y: 0,
  118954. z: 0
  118955. },
  118956. enabled: true,
  118957. shadowEnabled: true,
  118958. shadowBufferSize: 512,
  118959. shadowMinZ: 1,
  118960. shadowMaxZ: 10,
  118961. shadowFieldOfView: 60,
  118962. shadowFrustumSize: 2,
  118963. shadowConfig: {
  118964. useBlurCloseExponentialShadowMap: true,
  118965. useKernelBlur: true,
  118966. blurScale: 1.0,
  118967. bias: 0.001,
  118968. depthScale: 50 * (10 - 1),
  118969. frustumEdgeFalloff: 0
  118970. }
  118971. },
  118972. light1: {
  118973. type: 0,
  118974. frustumEdgeFalloff: 0,
  118975. intensity: 7,
  118976. intensityMode: 0,
  118977. radius: 0.4,
  118978. range: 0.4,
  118979. spotAngle: 57,
  118980. diffuse: {
  118981. r: 1,
  118982. g: 1,
  118983. b: 1
  118984. },
  118985. position: {
  118986. x: 4,
  118987. y: 3,
  118988. z: -0.5
  118989. },
  118990. target: {
  118991. x: 0,
  118992. y: 0,
  118993. z: 0
  118994. },
  118995. enabled: true,
  118996. shadowEnabled: false,
  118997. shadowBufferSize: 512,
  118998. shadowMinZ: 0.2,
  118999. shadowMaxZ: 10,
  119000. shadowFieldOfView: 28,
  119001. shadowFrustumSize: 2
  119002. },
  119003. light2: {
  119004. type: 0,
  119005. frustumEdgeFalloff: 0,
  119006. intensity: 1,
  119007. intensityMode: 0,
  119008. radius: 0.5,
  119009. range: 0.5,
  119010. spotAngle: 42.85,
  119011. diffuse: {
  119012. r: 0.8,
  119013. g: 0.8,
  119014. b: 0.8
  119015. },
  119016. position: {
  119017. x: -1,
  119018. y: 3,
  119019. z: -3
  119020. },
  119021. target: {
  119022. x: 0,
  119023. y: 0,
  119024. z: 0
  119025. },
  119026. enabled: true,
  119027. shadowEnabled: false,
  119028. shadowBufferSize: 512,
  119029. shadowMinZ: 0.2,
  119030. shadowMaxZ: 10,
  119031. shadowFieldOfView: 45,
  119032. shadowFrustumSize: 2
  119033. }
  119034. },
  119035. ground: {
  119036. shadowLevel: 0.9,
  119037. texture: "Ground_2.0-1024.png",
  119038. material: {
  119039. primaryColorHighlightLevel: 0.035,
  119040. primaryColorShadowLevel: 0,
  119041. enableNoise: true,
  119042. useRGBColor: false,
  119043. maxSimultaneousLights: 1,
  119044. diffuseTexture: {
  119045. gammaSpace: true
  119046. }
  119047. },
  119048. opacity: 1,
  119049. mirror: false,
  119050. receiveShadows: true,
  119051. size: 5
  119052. },
  119053. skybox: {
  119054. scale: 11,
  119055. cubeTexture: {
  119056. url: "Skybox_2.0-256.dds"
  119057. },
  119058. material: {
  119059. primaryColorHighlightLevel: 0.03,
  119060. primaryColorShadowLevel: 0.03,
  119061. enableNoise: true,
  119062. useRGBColor: false,
  119063. reflectionTexture: {
  119064. gammaSpace: true
  119065. }
  119066. }
  119067. },
  119068. engine: {
  119069. renderInBackground: true
  119070. },
  119071. scene: {
  119072. flags: {
  119073. shadowsEnabled: true,
  119074. particlesEnabled: false,
  119075. collisionsEnabled: false,
  119076. lightsEnabled: true,
  119077. texturesEnabled: true,
  119078. lensFlaresEnabled: false,
  119079. proceduralTexturesEnabled: false,
  119080. renderTargetsEnabled: true,
  119081. spritesEnabled: false,
  119082. skeletonsEnabled: true,
  119083. audioEnabled: false,
  119084. },
  119085. defaultMaterial: {
  119086. materialType: 'pbr',
  119087. reflectivityColor: {
  119088. r: 0.1,
  119089. g: 0.1,
  119090. b: 0.1
  119091. },
  119092. microSurface: 0.6
  119093. },
  119094. clearColor: {
  119095. r: 0.9,
  119096. g: 0.9,
  119097. b: 0.9,
  119098. a: 1.0
  119099. },
  119100. imageProcessingConfiguration: {
  119101. vignetteCentreX: 0,
  119102. vignetteCentreY: 0,
  119103. vignetteColor: {
  119104. r: 0.086,
  119105. g: 0.184,
  119106. b: 0.259,
  119107. a: 1
  119108. },
  119109. vignetteWeight: 0.855,
  119110. vignetteStretch: 0.5,
  119111. vignetteBlendMode: 0,
  119112. vignetteCameraFov: 0.7853981633974483,
  119113. isEnabled: true,
  119114. colorCurves: {
  119115. shadowsHue: 0,
  119116. shadowsDensity: 0,
  119117. shadowsSaturation: 0,
  119118. shadowsExposure: 0,
  119119. midtonesHue: 0,
  119120. midtonesDensity: 0,
  119121. midtonesExposure: 0,
  119122. midtonesSaturation: 0,
  119123. highlightsHue: 0,
  119124. highlightsDensity: 0,
  119125. highlightsExposure: 0,
  119126. highlightsSaturation: 0
  119127. }
  119128. },
  119129. mainColor: {
  119130. r: 0.8823529411764706,
  119131. g: 0.8823529411764706,
  119132. b: 0.8823529411764706
  119133. }
  119134. },
  119135. loaderPlugins: {
  119136. extendedMaterial: true,
  119137. applyMaterialConfig: true,
  119138. msftLod: true,
  119139. telemetry: true
  119140. },
  119141. model: {
  119142. rotationOffsetAxis: {
  119143. x: 0,
  119144. y: -1,
  119145. z: 0
  119146. },
  119147. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  119148. material: {
  119149. directEnabled: true,
  119150. directIntensity: 0.884,
  119151. emissiveIntensity: 1.04,
  119152. environmentIntensity: 0.6
  119153. },
  119154. entryAnimation: {
  119155. scaling: {
  119156. x: 0,
  119157. y: 0,
  119158. z: 0
  119159. },
  119160. time: 0.5,
  119161. easingFunction: 4,
  119162. easingMode: 1
  119163. },
  119164. exitAnimation: {
  119165. scaling: {
  119166. x: 0,
  119167. y: 0,
  119168. z: 0
  119169. },
  119170. time: 0.5,
  119171. easingFunction: 4,
  119172. easingMode: 1
  119173. },
  119174. normalize: true,
  119175. castShadow: true,
  119176. receiveShadows: true
  119177. },
  119178. lab: {
  119179. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  119180. environmentMap: {
  119181. texture: "EnvMap_2.0-256.env",
  119182. rotationY: 3,
  119183. tintLevel: 0.4
  119184. },
  119185. defaultRenderingPipelines: {
  119186. bloomEnabled: true,
  119187. bloomThreshold: 1.0,
  119188. fxaaEnabled: true,
  119189. bloomWeight: 0.05
  119190. }
  119191. }
  119192. };
  119193. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVDQUFrQztBQUVsQzs7O0dBR0c7QUFDUSxRQUFBLHFCQUFxQixHQUF3QjtJQUNwRCxPQUFPLEVBQUUsT0FBTztJQUNoQixPQUFPLEVBQUUsU0FBUztJQUNsQixNQUFNLEVBQUU7UUFDSixRQUFRLEVBQUUsUUFBUTtRQUNsQixHQUFHLEVBQUUsa0JBQWtCO1FBQ3ZCLFFBQVEsRUFBRSxHQUFHO1FBQ2Isa0JBQWtCLEVBQUUsSUFBSTtRQUN4QixjQUFjLEVBQUUsa0JBQWtCLEdBQUcsSUFBSSxDQUFDLEVBQUUsR0FBRyxDQUFDO1FBQ2hELGNBQWMsRUFBRSxDQUFDLGtCQUFrQixHQUFHLElBQUksQ0FBQyxFQUFFLEdBQUcsQ0FBQztRQUNqRCxTQUFTLEVBQUU7WUFDUCxPQUFPLEVBQUU7Z0JBQ0wsSU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BRSxHQUFHO1lBQ25CLFdBQVcsRUFBRSxJQUFJO1lBQ2pCLFdBQVcsRUFBRSxJQUFJO1NBQ3BCO0tBQ0o7Q0FDSixDQUFBIn0=
  119194. /***/ }),
  119195. /* 53 */
  119196. /***/ (function(module, exports, __webpack_require__) {
  119197. "use strict";
  119198. Object.defineProperty(exports, "__esModule", { value: true });
  119199. /**
  119200. * Defines a default directional shadow light for normalized objects (!)
  119201. */
  119202. exports.shadowDirectionalLightConfiguration = {
  119203. model: {
  119204. receiveShadows: true,
  119205. castShadow: true
  119206. },
  119207. ground: {
  119208. receiveShadows: true
  119209. },
  119210. lights: {
  119211. shadowDirectionalLight: {
  119212. type: 1,
  119213. shadowEnabled: true,
  119214. target: { x: 0, y: 0, z: 0.5 },
  119215. position: { x: 1.49, y: 2.39, z: -1.33 },
  119216. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  119217. intensity: 4.887,
  119218. intensityMode: 0,
  119219. shadowBufferSize: 1024,
  119220. shadowFrustumSize: 6.0,
  119221. shadowFieldOfView: 50.977,
  119222. shadowMinZ: 0.1,
  119223. shadowMaxZ: 10.0,
  119224. shadowConfig: {
  119225. blurKernel: 32,
  119226. useBlurCloseExponentialShadowMap: true
  119227. }
  119228. }
  119229. }
  119230. };
  119231. /**
  119232. * Defines a default shadow-enabled spot light for normalized objects.
  119233. */
  119234. exports.shadowSpotlLightConfiguration = {
  119235. model: {
  119236. receiveShadows: true,
  119237. castShadow: true
  119238. },
  119239. ground: {
  119240. receiveShadows: true
  119241. },
  119242. lights: {
  119243. shadowSpotLight: {
  119244. type: 2,
  119245. intensity: 2,
  119246. shadowEnabled: true,
  119247. target: { x: 0, y: 0, z: 0.5 },
  119248. position: { x: 0, y: 3.5, z: 3.7 },
  119249. angle: 1,
  119250. shadowOrthoScale: 0.5,
  119251. shadowBufferSize: 1024,
  119252. shadowMinZ: 0.1,
  119253. shadowMaxZ: 50.0,
  119254. shadowConfig: {
  119255. frustumEdgeFalloff: 0.5,
  119256. blurKernel: 32,
  119257. useBlurExponentialShadowMap: true
  119258. }
  119259. }
  119260. }
  119261. };
  119262. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hhZG93TGlnaHQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9zaGFkb3dMaWdodC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSxtQ0FBbUMsR0FBd0I7SUFDcEUsS0FBSyxFQUFFO1FBQ0gsY0FBYyxFQUFFLElBQUk7UUFDcEIsVUFBVSxFQUFFLElBQUk7S0FDbkI7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLHNCQUFzQixFQUFFO1lBQ3BCLElBQUksRUFBRSxDQUFDO1lBQ1AsYUFBYSxFQUFFLElBQUk7WUFDbkIsTUFBTSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDOUIsUUFBUSxFQUFFLEVBQUUsQ0FBQyxFQUFFLElBQUksRUFBRSxDQUFDLEVBQUUsSUFBSSxFQUFFLENBQUMsRUFBRSxDQUFDLElBQUksRUFBRTtZQUN4QyxPQUFPLEVBQUUsRUFBRSxDQUFDLEVBQUUsS0FBSyxFQUFFLENBQUMsRUFBRSxLQUFLLEVBQUUsQ0FBQyxFQUFFLEtBQUssRUFBRTtZQUN6QyxTQUFTLEVBQUUsS0FBSztZQUNoQixhQUFhLEVBQUUsQ0FBQztZQUNoQixnQkFBZ0IsRUFBRSxJQUFJO1lBQ3RCLGlCQUFpQixFQUFFLEdBQUc7WUFDdEIsaUJBQWlCLEVBQUUsTUFBTTtZQUN6QixVQUFVL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object.defineProperty(exports, "__esModule", { value: true });
  119268. /**
  119269. * Lab-oriented default .env support
  119270. */
  119271. exports.environmentMapConfiguration = {
  119272. lab: {
  119273. assetsRootURL: '/assets/environment/',
  119274. environmentMap: {
  119275. texture: 'EnvMap_2.0-256.env',
  119276. rotationY: 0,
  119277. tintLevel: 0.4
  119278. }
  119279. }
  119280. };
  119281. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRNYXAuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9lbnZpcm9ubWVudE1hcC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSwyQkFBMkIsR0FBd0I7SUFDNUQsR0FBRyxFQUFFO1FBQ0QsYUFBYSxFQUFFLHNCQUFzQjtRQUNyQyxjQUFjLEVBQUU7WUFDWixPQUFPLEVBQUUsb0JBQW9CO1lBQzdCLFNBQVMsRUFBRSxDQUFDO1lBQ1osU0FBUyxFQUFFLEdBQUc7U0FDakI7S0FDSjtDQUNKLENBQUEifQ==
  119282. /***/ }),
  119283. /* 55 */
  119284. /***/ (function(module, exports, __webpack_require__) {
  119285. "use strict";
  119286. Object.defineProperty(exports, "__esModule", { value: true });
  119287. var configuration_1 = __webpack_require__(11);
  119288. /**
  119289. * This function will make sure the configuration file is taking deprecated fields into account
  119290. * and is setting them to the correct keys and values.
  119291. *
  119292. * @param configuration The configuration to process. Mutable!
  119293. */
  119294. function processConfigurationCompatibility(configuration) {
  119295. if (configuration.camera) {
  119296. // camera contrast -> image processing contrast
  119297. if (configuration.camera.contrast !== undefined) {
  119298. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  119299. }
  119300. // camera exposure -> image processing exposure
  119301. if (configuration.camera.exposure !== undefined) {
  119302. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  119303. }
  119304. }
  119305. if (configuration.scene) {
  119306. //glow
  119307. if (configuration.scene.glow) {
  119308. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  119309. var enabledProcessing = configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  119310. if (enabledProcessing !== false) {
  119311. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  119312. }
  119313. }
  119314. }
  119315. }
  119316. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  119317. function setKeyInObject(object, keys, value, shouldOverwrite) {
  119318. var keySplit = keys.split(".");
  119319. if (keySplit.length === 0)
  119320. return;
  119321. var lastKey = keySplit.pop();
  119322. if (!lastKey)
  119323. return;
  119324. var curObj = object;
  119325. keySplit.forEach(function (key) {
  119326. curObj[key] = curObj[key] || {};
  119327. curObj = curObj[key];
  119328. });
  119329. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  119330. return;
  119331. curObj[lastKey] = value;
  119332. }
  119333. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbXBhdGliaWxpdHkuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9jb25maWd1cmF0aW9uQ29tcGF0aWJpbGl0eS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLGlEQUEwRTtBQUMxRTs7Ozs7R0FLRztBQUNILDJDQUFrRCxhQUFrQztJQUloRixJQUFJLGFBQWEsQ0FBQyxNQUFNLEVBQUU7UUFDdEIsK0NBQStDO1FBQy9DLElBQUksYUFBYSxDQUFDLE1BQU0sQ0FBQyxRQUFRLEtBQUssU0FBUyxFQUFFO1lBQzdDLGNBQWMsQ0FBQyxhQUFhLEVBQUUsNkNBQTZDLEVBQUUsYUFBYSxDQUFDL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QUc7UUFDaEIsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsSUFBSSxFQUFFLENBQUM7UUFDaEMsTUFBTSxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN6QixDQUFDLENBQUMsQ0FBQztJQUNILElBQUksTUFBTSxDQUFDLE9BQU8sQ0FBQyxLQUFLLFNBQVMsSUFBSSxDQUFDLGVBQWU7UUFBRSxPQUFPO0lBQzlELE1BQU0sQ0FBQyxPQUFPLENBQUMsR0FBRyxLQUFLLENBQUM7QUFDNUIsQ0FBQyJ9
  119334. /***/ }),
  119335. /* 56 */
  119336. /***/ (function(module, exports, __webpack_require__) {
  119337. "use strict";
  119338. Object.defineProperty(exports, "__esModule", { value: true });
  119339. var telemetryLoaderPlugin_1 = __webpack_require__(57);
  119340. exports.TelemetryLoaderPlugin = telemetryLoaderPlugin_1.TelemetryLoaderPlugin;
  119341. var msftLodLoaderPlugin_1 = __webpack_require__(58);
  119342. exports.MSFTLodLoaderPlugin = msftLodLoaderPlugin_1.MSFTLodLoaderPlugin;
  119343. var applyMaterialConfig_1 = __webpack_require__(59);
  119344. exports.ApplyMaterialConfigPlugin = applyMaterialConfig_1.ApplyMaterialConfigPlugin;
  119345. var extendedMaterialLoaderPlugin_1 = __webpack_require__(60);
  119346. exports.ExtendedMaterialLoaderPlugin = extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin;
  119347. var babylonjs_1 = __webpack_require__(0);
  119348. var pluginCache = {};
  119349. /**
  119350. * Get a loader plugin according to its name.
  119351. * The plugin will be cached and will be reused if called for again.
  119352. *
  119353. * @param name the name of the plugin
  119354. */
  119355. function getLoaderPluginByName(name) {
  119356. if (!pluginCache[name]) {
  119357. switch (name) {
  119358. case 'telemetry':
  119359. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  119360. break;
  119361. case 'msftLod':
  119362. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  119363. break;
  119364. case 'applyMaterialConfig':
  119365. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  119366. break;
  119367. case 'extendedMaterial':
  119368. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  119369. break;
  119370. }
  119371. }
  119372. return pluginCache[name];
  119373. }
  119374. exports.getLoaderPluginByName = getLoaderPluginByName;
  119375. /**
  119376. *
  119377. */
  119378. function addLoaderPlugin(name, plugin) {
  119379. if (pluginCache[name]) {
  119380. babylonjs_1.Tools.Warn("Overwriting plugin with the same name - " + name);
  119381. }
  119382. pluginCache[name] = plugin;
  119383. }
  119384. exports.addLoaderPlugin = addLoaderPlugin;
  119385. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvbG9hZGVyL3BsdWdpbnMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBZ0U7QUFTdkQsZ0NBVEEsNkNBQXFCLENBU0E7QUFQOUIsNkRBQTREO0FBT2IsOEJBUHRDLHlDQUFtQixDQU9zQztBQU5sRSw2REFBa0U7QUFNRSxvQ0FOM0QsK0NBQXlCLENBTTJEO0FBTDdGLCtFQUE4RTtBQUtpQix1Q0FMdEYsMkRBQTRCLENBS3NGO0FBSjNILHVDQUFrQztBQUVsQyxJQUFNLFdBQVcsR0FBcUMsRUFBRSxDQUFDO0FBSXpEOzs7OztHQUtHO0FBQ0gsK0JBQXNDLElBQVk7SUFDOUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLENBQUMsRUFBRTtRQUNwQixRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssV0FBVztnQkFDWixXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSw2Q0FBcUIsRUFBRSxDQUFDO2dCQUNoRCxNQUFNO1lBQ1YsS0FBSyxTQUFTO2dCQUNWLFdBQVcsQ0FBQyxJQUFJLENBQUMsR0FBRyxJQUFJLHlDQUFtQixFQUFFLENBQUM7Z0JBQzlDLE1BQU07WUFDVixLQUFLLHFCQUFxQjtnQkFDdEIsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLElBQUksK0NBQXlCLEVBQUUsQ0FBQztnQkFDcEQsTUFBTTtZQUNWLEtBQUssa0JBQWtCO2dCQUNuQixXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSwyREFBNEIsRUFBRSxDQUFDO2dCQUN2RCxNQUFNO1NBQ2I7S0FDSjtJQUVELE9BQU8sV0FBVyxDQUFDLElBQUksQ0FBQyxDQUFDO0FBQzdCLENBQUM7QUFuQkQsc0RBbUJDO0FBRUQ7O0dBRUc7QUFDSCx5QkFBZ0MsSUFBWSxFQUFFLE1BQXFCO0lBQy9ELElBQUksV0FBVyxDQUFDLElBQUksQ0FBQyxFQUFFO1FBQ25CLGlCQUFLLENBQUMsSUFBSSxDQUFDLDBDQUEwQyxHQUFHLElBQUksQ0FBQyxDQUFDO0tBQ2pFO0lBQ0QsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLE1BQU0sQ0FBQztBQUMvQixDQUFDO0FBTEQsMENBS0MifQ==
  119386. /***/ }),
  119387. /* 57 */
  119388. /***/ (function(module, exports, __webpack_require__) {
  119389. "use strict";
  119390. Object.defineProperty(exports, "__esModule", { value: true });
  119391. var telemetryManager_1 = __webpack_require__(6);
  119392. var babylonjs_1 = __webpack_require__(0);
  119393. var TelemetryLoaderPlugin = /** @class */ (function () {
  119394. function TelemetryLoaderPlugin() {
  119395. }
  119396. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  119397. this._model = model;
  119398. this._loadStart = babylonjs_1.Tools.Now;
  119399. };
  119400. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  119401. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewerId(), {
  119402. model: model,
  119403. loadTime: babylonjs_1.Tools.Now - this._loadStart
  119404. });
  119405. telemetryManager_1.telemetryManager.flushWebGLErrors(model.rootMesh.getEngine(), model.getViewerId());
  119406. };
  119407. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  119408. this._loadEnd = babylonjs_1.Tools.Now;
  119409. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewerId(), {
  119410. model: this._model,
  119411. loadTime: this._loadEnd - this._loadStart
  119412. });
  119413. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  119414. };
  119415. TelemetryLoaderPlugin.prototype.onComplete = function () {
  119416. this._loadEnd = babylonjs_1.Tools.Now;
  119417. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewerId(), {
  119418. model: this._model,
  119419. loadTime: this._loadEnd - this._loadStart
  119420. });
  119421. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  119422. };
  119423. return TelemetryLoaderPlugin;
  119424. }());
  119425. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  119426. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TG9hZGVyUGx1Z2luLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vc3JjL2xvYWRlci9wbHVnaW5zL3RlbGVtZXRyeUxvYWRlclBsdWdpbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLG9FQUFtRTtBQUVuRSx1Q0FBK0U7QUFHL0U7SUFBQTtJQXVDQSxDQUFDO0lBaENVLHNDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO1FBQ3BCLElBQUks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QUMxQixtQ0FBZ0IsQ0FBQyxTQUFTLENBQUMsZUFBZSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLEVBQUU7WUFDbkUsS0FBSyxFQUFFLElBQUksQ0FBQyxNQUFNO1lBQ2xCLFFBQVEsRUFBRSxJQUFJLENBQUMsUUFBUSxHQUFHLElBQUksQ0FBQyxVQUFVO1NBQzVDLENBQUMsQ0FBQztRQUVILG1DQUFnQixDQUFDLGdCQUFnQixDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLFNBQVMsRUFBRSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLENBQUMsQ0FBQztJQUNuRyxDQUFDO0lBQ0wsNEJBQUM7QUFBRCxDQUFDLEFBdkNELElBdUNDO0FBdkNZLHNEQUFxQiJ9
  119427. /***/ }),
  119428. /* 58 */
  119429. /***/ (function(module, exports, __webpack_require__) {
  119430. "use strict";
  119431. Object.defineProperty(exports, "__esModule", { value: true });
  119432. /**
  119433. * A loder plugin to use MSFT_lod extension correctly (glTF)
  119434. */
  119435. var MSFTLodLoaderPlugin = /** @class */ (function () {
  119436. function MSFTLodLoaderPlugin() {
  119437. }
  119438. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  119439. this._model = model;
  119440. };
  119441. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  119442. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  119443. var MSFT_lod = extension;
  119444. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  119445. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  119446. }
  119447. };
  119448. return MSFTLodLoaderPlugin;
  119449. }());
  119450. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  119451. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXNmdExvZExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9tc2Z0TG9kTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBTUE7O0dBRUc7QUFDSDtJQUFBO0lBZUEsQ0FBQztJQVhVLG9DQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSwrQ0FBaUIsR0FBeEIsVUFBeUIsU0FBK0I7UUFDcEQsSUFBSSxTQUFTLENBQUMsSUFBSSxLQUFLLFVBQVUsSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxtQkFBbUIsRUFBRTtZQUNoRixJQUFNLFFBQVEsR0FBRyxTQUFzQyxDQUFDO1lBQ3hELFFBQVEsQ0FBQyxPQUFPLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsYUFBYSxDQUFDLG1CQUFtQixDQUFDLGtCQUFrQixDQUFDO1lBQ3RGLFFBQVEsQ0FBQyxhQUFhLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxhQUFhLENBQUMsbUJBQW1CLENBQUMsYUFBYSxJQUFJLE1BQU0sQ0FBQyxTQUFTLENBQUM7U0FDNUc7SUFDTCxDQUFDO0lBQ0wsMEJBQUM7QUFBRCxDQUFDLEFBZkQsSUFlQztBQWZZLGtEQUFtQiJ9
  119452. /***/ }),
  119453. /* 59 */
  119454. /***/ (function(module, exports, __webpack_require__) {
  119455. "use strict";
  119456. Object.defineProperty(exports, "__esModule", { value: true });
  119457. /**
  119458. * Force-apply material configuration right after a material was loaded.
  119459. */
  119460. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  119461. function ApplyMaterialConfigPlugin() {
  119462. }
  119463. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  119464. this._model = model;
  119465. };
  119466. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  119467. this._model && this._model._applyModelMaterialConfiguration(material);
  119468. };
  119469. return ApplyMaterialConfigPlugin;
  119470. }());
  119471. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  119472. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwbHlNYXRlcmlhbENvbmZpZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9hcHBseU1hdGVyaWFsQ29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBV0EsQ0FBQztJQVBVLDBDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSxvREFBZ0IsR0FBdkIsVUFBd0IsUUFBa0I7UUFDdEMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGdDQUFnQyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQzFFLENBQUM7SUFDTCxnQ0FBQztBQUFELENBQUMsQUFYRCxJQVdDO0FBWFksOERBQXlCIn0=
  119473. /***/ }),
  119474. /* 60 */
  119475. /***/ (function(module, exports, __webpack_require__) {
  119476. "use strict";
  119477. Object.defineProperty(exports, "__esModule", { value: true });
  119478. var babylonjs_1 = __webpack_require__(0);
  119479. /**
  119480. * A (PBR) material will be extended using this function.
  119481. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  119482. */
  119483. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  119484. function ExtendedMaterialLoaderPlugin() {
  119485. }
  119486. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  119487. var material = baseMaterial;
  119488. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  119489. };
  119490. return ExtendedMaterialLoaderPlugin;
  119491. }());
  119492. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  119493. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWRNYXRlcmlhbExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9leHRlbmRlZE1hdGVyaWFsTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQTBEO0FBSTFEOzs7R0FHRztBQUNIO0lBQUE7SUFNQSxDQUFDO0lBSlUsdURBQWdCLEdBQXZCLFVBQXdCLFlBQXNCO1FBQzFDLElBQUksUUFBUSxHQUFHLFlBQTJCLENBQUM7UUFDM0MsUUFBUSxDQUFDLFNBQVMsR0FBRyxrQkFBTSxDQUFDLDhCQUE4QixDQUFDO0lBQy9ELENBQUM7SUFDTCxtQ0FBQztBQUFELENBQUMsQUFORCxJQU1DO0FBTlksb0VBQTRCIn0=
  119494. /***/ }),
  119495. /* 61 */
  119496. /***/ (function(module, exports, __webpack_require__) {
  119497. "use strict";
  119498. Object.defineProperty(exports, "__esModule", { value: true });
  119499. var babylonjs_1 = __webpack_require__(0);
  119500. var ObservablesManager = /** @class */ (function () {
  119501. function ObservablesManager() {
  119502. this.onSceneInitObservable = new babylonjs_1.Observable();
  119503. this.onEngineInitObservable = new babylonjs_1.Observable();
  119504. this.onModelLoadedObservable = new babylonjs_1.Observable();
  119505. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  119506. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  119507. this.onModelAddedObservable = new babylonjs_1.Observable();
  119508. this.onModelRemovedObservable = new babylonjs_1.Observable();
  119509. this.onViewerInitDoneObservable = new babylonjs_1.Observable();
  119510. this.onViewerInitStartedObservable = new babylonjs_1.Observable();
  119511. this.onLoaderInitObservable = new babylonjs_1.Observable();
  119512. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  119513. }
  119514. ObservablesManager.prototype.dispose = function () {
  119515. this.onSceneInitObservable.clear();
  119516. this.onEngineInitObservable.clear();
  119517. this.onModelLoadedObservable.clear();
  119518. this.onModelLoadProgressObservable.clear();
  119519. this.onModelLoadErrorObservable.clear();
  119520. this.onModelAddedObservable.clear();
  119521. this.onModelRemovedObservable.clear();
  119522. this.onViewerInitDoneObservable.clear();
  119523. this.onLoaderInitObservable.clear();
  119524. this.onFrameRenderedObservable.clear();
  119525. };
  119526. return ObservablesManager;
  119527. }());
  119528. exports.ObservablesManager = ObservablesManager;
  119529. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJsZXNNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL29ic2VydmFibGVzTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE2SDtBQUk3SDtJQW9ESTtRQUNJLElBQUksQ0FBQyxxQkFBcUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUM5QyxJQUFJLENBQUMsc0JBQXNCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7UUFDL0MsSUFBSSxDQUFDLHVCQUF1QixHQUFHLElBQUksc0JBQVUsRUFBRSxDQUFDO1FBQ2hELElBQUksQ0FBQyw2QkFBNkIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUN0RCxJQUFJLENB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Q0FBQztJQUVMLHlCQUFDO0FBQUQsQ0FBQyxBQS9FRCxJQStFQztBQS9FWSxnREFBa0IifQ==
  119530. /***/ }),
  119531. /* 62 */
  119532. /***/ (function(module, exports, __webpack_require__) {
  119533. "use strict";
  119534. Object.defineProperty(exports, "__esModule", { value: true });
  119535. var babylonjs_1 = __webpack_require__(0);
  119536. var ConfigurationContainer = /** @class */ (function () {
  119537. function ConfigurationContainer() {
  119538. this.mainColor = babylonjs_1.Color3.White();
  119539. this.reflectionColor = babylonjs_1.Color3.White();
  119540. }
  119541. return ConfigurationContainer;
  119542. }());
  119543. exports.ConfigurationContainer = ConfigurationContainer;
  119544. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbnRhaW5lci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb25Db250YWluZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSx1Q0FBMEM7QUFFMUM7SUFBQTtRQU1XLGNBQVMsR0FBVyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ25DLG9CQUFlLEdBQVcsa0JBQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUVwRCxDQUFDO0lBQUQsNkJBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHdEQUFzQiJ9
  119545. /***/ }),
  119546. /* 63 */
  119547. /***/ (function(module, exports, __webpack_require__) {
  119548. "use strict";
  119549. Object.defineProperty(exports, "__esModule", { value: true });
  119550. var babylonjs_1 = __webpack_require__(0);
  119551. var helper_1 = __webpack_require__(1);
  119552. var Handlebars = __webpack_require__(15);
  119553. var eventManager_1 = __webpack_require__(64);
  119554. var _1 = __webpack_require__(1);
  119555. /**
  119556. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  119557. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  119558. */
  119559. var TemplateManager = /** @class */ (function () {
  119560. function TemplateManager(containerElement) {
  119561. this.containerElement = containerElement;
  119562. this.templates = {};
  119563. this.onTemplateInit = new babylonjs_1.Observable();
  119564. this.onTemplateLoaded = new babylonjs_1.Observable();
  119565. this.onTemplateStateChange = new babylonjs_1.Observable();
  119566. this.onAllLoaded = new babylonjs_1.Observable();
  119567. this.onEventTriggered = new babylonjs_1.Observable();
  119568. this.eventManager = new eventManager_1.EventManager(this);
  119569. }
  119570. /**
  119571. * Initialize the template(s) for the viewer. Called bay the Viewer class
  119572. * @param templates the templates to be used to initialize the main template
  119573. */
  119574. TemplateManager.prototype.initTemplate = function (templates) {
  119575. var _this = this;
  119576. var internalInit = function (dependencyMap, name, parentTemplate) {
  119577. //init template
  119578. var template = _this.templates[name];
  119579. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  119580. return internalInit(dependencyMap[childName], childName, template);
  119581. });
  119582. // register the observers
  119583. //template.onLoaded.add(() => {
  119584. var addToParent = function () {
  119585. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  119586. template.appendTo(containingElement);
  119587. _this._checkLoadedState();
  119588. };
  119589. if (parentTemplate && !parentTemplate.parent) {
  119590. parentTemplate.onAppended.add(function () {
  119591. addToParent();
  119592. });
  119593. }
  119594. else {
  119595. addToParent();
  119596. }
  119597. //});
  119598. return template;
  119599. };
  119600. //build the html tree
  119601. return this._buildHTMLTree(templates).then(function (htmlTree) {
  119602. if (_this.templates['main']) {
  119603. internalInit(htmlTree, 'main');
  119604. }
  119605. else {
  119606. _this._checkLoadedState();
  119607. }
  119608. return;
  119609. });
  119610. };
  119611. /**
  119612. *
  119613. * This function will create a simple map with child-dependencies of the template html tree.
  119614. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  119615. * It is expected that the main template will be called main!
  119616. *
  119617. * @param templates
  119618. */
  119619. TemplateManager.prototype._buildHTMLTree = function (templates) {
  119620. var _this = this;
  119621. var promises = Object.keys(templates).map(function (name) {
  119622. // if the template was overridden
  119623. if (!templates[name])
  119624. return Promise.resolve(false);
  119625. // else - we have a template, let's do our job!
  119626. var template = new Template(name, templates[name]);
  119627. template.onLoaded.add(function () {
  119628. _this.onTemplateLoaded.notifyObservers(template);
  119629. });
  119630. template.onStateChange.add(function () {
  119631. _this.onTemplateStateChange.notifyObservers(template);
  119632. });
  119633. _this.onTemplateInit.notifyObservers(template);
  119634. // make sure the global onEventTriggered is called as well
  119635. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  119636. _this.templates[name] = template;
  119637. return template.initPromise;
  119638. });
  119639. return Promise.all(promises).then(function () {
  119640. var templateStructure = {};
  119641. // now iterate through all templates and check for children:
  119642. var buildTree = function (parentObject, name) {
  119643. _this.templates[name].isInHtmlTree = true;
  119644. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  119645. childNodes.forEach(function (element) {
  119646. parentObject[element] = {};
  119647. buildTree(parentObject[element], element);
  119648. });
  119649. };
  119650. if (_this.templates['main']) {
  119651. buildTree(templateStructure, "main");
  119652. }
  119653. return templateStructure;
  119654. });
  119655. };
  119656. /**
  119657. * Get the canvas in the template tree.
  119658. * There must be one and only one canvas inthe template.
  119659. */
  119660. TemplateManager.prototype.getCanvas = function () {
  119661. return this.containerElement.querySelector('canvas');
  119662. };
  119663. /**
  119664. * Get a specific template from the template tree
  119665. * @param name the name of the template to load
  119666. */
  119667. TemplateManager.prototype.getTemplate = function (name) {
  119668. return this.templates[name];
  119669. };
  119670. TemplateManager.prototype._checkLoadedState = function () {
  119671. var _this = this;
  119672. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  119673. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  119674. });
  119675. if (done) {
  119676. this.onAllLoaded.notifyObservers(this);
  119677. }
  119678. };
  119679. /**
  119680. * Dispose the template manager
  119681. */
  119682. TemplateManager.prototype.dispose = function () {
  119683. var _this = this;
  119684. // dispose all templates
  119685. Object.keys(this.templates).forEach(function (template) {
  119686. _this.templates[template].dispose();
  119687. });
  119688. this.templates = {};
  119689. this.eventManager.dispose();
  119690. this.onTemplateInit.clear();
  119691. this.onAllLoaded.clear();
  119692. this.onEventTriggered.clear();
  119693. this.onTemplateLoaded.clear();
  119694. this.onTemplateStateChange.clear();
  119695. };
  119696. return TemplateManager;
  119697. }());
  119698. exports.TemplateManager = TemplateManager;
  119699. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  119700. Handlebars.registerHelper('eachInMap', function (map, block) {
  119701. var out = '';
  119702. Object.keys(map).map(function (prop) {
  119703. var data = map[prop];
  119704. if (typeof data === 'object') {
  119705. data.id = data.id || prop;
  119706. out += block.fn(data);
  119707. }
  119708. else {
  119709. out += block.fn({ id: prop, value: data });
  119710. }
  119711. });
  119712. return out;
  119713. });
  119714. Handlebars.registerHelper('add', function (a, b) {
  119715. var out = a + b;
  119716. return out;
  119717. });
  119718. Handlebars.registerHelper('eq', function (a, b) {
  119719. var out = (a == b);
  119720. return out;
  119721. });
  119722. Handlebars.registerHelper('or', function (a, b) {
  119723. var out = a || b;
  119724. return out;
  119725. });
  119726. Handlebars.registerHelper('not', function (a) {
  119727. var out = !a;
  119728. return out;
  119729. });
  119730. Handlebars.registerHelper('count', function (map) {
  119731. return map.length;
  119732. });
  119733. Handlebars.registerHelper('gt', function (a, b) {
  119734. var out = a > b;
  119735. return out;
  119736. });
  119737. /**
  119738. * This class represents a single template in the viewer's template tree.
  119739. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  119740. * A template is injected using the template manager in the correct position.
  119741. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  119742. *
  119743. * For further information please refer to the documentation page, https://doc.babylonjs.com
  119744. */
  119745. var Template = /** @class */ (function () {
  119746. function Template(name, _configuration) {
  119747. var _this = this;
  119748. this.name = name;
  119749. this._configuration = _configuration;
  119750. this.onLoaded = new babylonjs_1.Observable();
  119751. this.onAppended = new babylonjs_1.Observable();
  119752. this.onStateChange = new babylonjs_1.Observable();
  119753. this.onEventTriggered = new babylonjs_1.Observable();
  119754. this.onParamsUpdated = new babylonjs_1.Observable();
  119755. this.onHTMLRendered = new babylonjs_1.Observable();
  119756. this.loadRequests = [];
  119757. this.isLoaded = false;
  119758. this.isShown = false;
  119759. this.isInHtmlTree = false;
  119760. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  119761. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  119762. if (htmlTemplate) {
  119763. _this._htmlTemplate = htmlTemplate;
  119764. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && !!_this._configuration.params.noEscape) });
  119765. var config = _this._configuration.params || {};
  119766. _this._rawHtml = compiledTemplate(config);
  119767. try {
  119768. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  119769. }
  119770. catch (e) {
  119771. var test = document.createElement(_this.name);
  119772. test.innerHTML = _this._rawHtml;
  119773. _this._fragment = test;
  119774. }
  119775. _this.isLoaded = true;
  119776. _this.isShown = true;
  119777. _this.onLoaded.notifyObservers(_this);
  119778. }
  119779. return _this;
  119780. });
  119781. }
  119782. /**
  119783. * Some templates have parameters (like background color for example).
  119784. * The parameters are provided to Handlebars which in turn generates the template.
  119785. * This function will update the template with the new parameters
  119786. *
  119787. * Note that when updating parameters the events will be registered again (after being cleared).
  119788. *
  119789. * @param params the new template parameters
  119790. */
  119791. Template.prototype.updateParams = function (params, append) {
  119792. if (append === void 0) { append = true; }
  119793. if (append) {
  119794. this._configuration.params = _1.deepmerge(this._configuration.params, params);
  119795. }
  119796. else {
  119797. this._configuration.params = params;
  119798. }
  119799. // update the template
  119800. if (this.isLoaded) {
  119801. // this.dispose();
  119802. }
  119803. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  119804. var config = this._configuration.params || {};
  119805. this._rawHtml = compiledTemplate(config);
  119806. try {
  119807. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  119808. }
  119809. catch (e) {
  119810. var test = document.createElement(this.name);
  119811. test.innerHTML = this._rawHtml;
  119812. this._fragment = test;
  119813. }
  119814. if (this.parent) {
  119815. this.appendTo(this.parent, true);
  119816. }
  119817. };
  119818. Template.prototype.redraw = function () {
  119819. this.updateParams({});
  119820. };
  119821. Object.defineProperty(Template.prototype, "configuration", {
  119822. /**
  119823. * Get the template'S configuration
  119824. */
  119825. get: function () {
  119826. return this._configuration;
  119827. },
  119828. enumerable: true,
  119829. configurable: true
  119830. });
  119831. /**
  119832. * A template can be a parent element for other templates or HTML elements.
  119833. * This function will deliver all child HTML elements of this template.
  119834. */
  119835. Template.prototype.getChildElements = function () {
  119836. var childrenArray = [];
  119837. //Edge and IE don't support frage,ent.children
  119838. var children = this._fragment && this._fragment.children;
  119839. if (!this._fragment) {
  119840. var fragment = this.parent.querySelector(this.name);
  119841. if (fragment) {
  119842. children = fragment.querySelectorAll('*');
  119843. }
  119844. }
  119845. if (!children) {
  119846. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  119847. children = this._fragment.querySelectorAll('*');
  119848. }
  119849. for (var i = 0; i < children.length; ++i) {
  119850. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  119851. }
  119852. return childrenArray;
  119853. };
  119854. /**
  119855. * Appending the template to a parent HTML element.
  119856. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  119857. * @param parent the parent to which the template is added
  119858. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  119859. */
  119860. Template.prototype.appendTo = function (parent, forceRemove) {
  119861. var _this = this;
  119862. if (this.parent) {
  119863. if (forceRemove && this._addedFragment) {
  119864. /*let fragement = this.parent.querySelector(this.name)
  119865. if (fragement)
  119866. this.parent.removeChild(fragement);*/
  119867. this.parent.innerHTML = '';
  119868. }
  119869. else {
  119870. return;
  119871. }
  119872. }
  119873. this.parent = parent;
  119874. if (this._configuration.id) {
  119875. this.parent.id = this._configuration.id;
  119876. }
  119877. if (this._fragment) {
  119878. this.parent.appendChild(this._fragment);
  119879. this._addedFragment = this._fragment;
  119880. }
  119881. else {
  119882. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  119883. }
  119884. this.onHTMLRendered.notifyObservers(this);
  119885. // appended only one frame after.
  119886. setTimeout(function () {
  119887. _this._registerEvents();
  119888. _this.onAppended.notifyObservers(_this);
  119889. });
  119890. };
  119891. /**
  119892. * Show the template using the provided visibilityFunction, or natively using display: flex.
  119893. * The provided function returns a promise that should be fullfilled when the element is shown.
  119894. * Since it is a promise async operations are more than possible.
  119895. * See the default viewer for an opacity example.
  119896. * @param visibilityFunction The function to execute to show the template.
  119897. */
  119898. Template.prototype.show = function (visibilityFunction) {
  119899. var _this = this;
  119900. if (this._isHiding)
  119901. return Promise.resolve(this);
  119902. return Promise.resolve().then(function () {
  119903. _this._isShowing = true;
  119904. if (visibilityFunction) {
  119905. return visibilityFunction(_this);
  119906. }
  119907. else {
  119908. // flex? box? should this be configurable easier than the visibilityFunction?
  119909. _this.parent.style.display = 'flex';
  119910. // support old browsers with no flex:
  119911. if (_this.parent.style.display !== 'flex') {
  119912. _this.parent.style.display = '';
  119913. }
  119914. return _this;
  119915. }
  119916. }).then(function () {
  119917. _this.isShown = true;
  119918. _this._isShowing = false;
  119919. _this.onStateChange.notifyObservers(_this);
  119920. return _this;
  119921. });
  119922. };
  119923. /**
  119924. * Hide the template using the provided visibilityFunction, or natively using display: none.
  119925. * The provided function returns a promise that should be fullfilled when the element is hidden.
  119926. * Since it is a promise async operations are more than possible.
  119927. * See the default viewer for an opacity example.
  119928. * @param visibilityFunction The function to execute to show the template.
  119929. */
  119930. Template.prototype.hide = function (visibilityFunction) {
  119931. var _this = this;
  119932. if (this._isShowing)
  119933. return Promise.resolve(this);
  119934. return Promise.resolve().then(function () {
  119935. _this._isHiding = true;
  119936. if (visibilityFunction) {
  119937. return visibilityFunction(_this);
  119938. }
  119939. else {
  119940. // flex? box? should this be configurable easier than the visibilityFunction?
  119941. _this.parent.style.display = 'none';
  119942. return _this;
  119943. }
  119944. }).then(function () {
  119945. _this.isShown = false;
  119946. _this._isHiding = false;
  119947. _this.onStateChange.notifyObservers(_this);
  119948. return _this;
  119949. });
  119950. };
  119951. /**
  119952. * Dispose this template
  119953. */
  119954. Template.prototype.dispose = function () {
  119955. this.onAppended.clear();
  119956. this.onEventTriggered.clear();
  119957. this.onLoaded.clear();
  119958. this.onStateChange.clear();
  119959. this.isLoaded = false;
  119960. // remove from parent
  119961. try {
  119962. this.parent.removeChild(this._fragment);
  119963. }
  119964. catch (e) {
  119965. //noop
  119966. }
  119967. this.loadRequests.forEach(function (request) {
  119968. request.abort();
  119969. });
  119970. if (this._registeredEvents) {
  119971. this._registeredEvents.forEach(function (evt) {
  119972. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  119973. });
  119974. }
  119975. delete this._fragment;
  119976. };
  119977. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  119978. var _this = this;
  119979. if (!templateConfig) {
  119980. return Promise.reject('No templateConfig provided');
  119981. }
  119982. else if (templateConfig.html) {
  119983. return Promise.resolve(templateConfig.html);
  119984. }
  119985. else {
  119986. var location_1 = this._getTemplateLocation(templateConfig);
  119987. if (helper_1.isUrl(location_1)) {
  119988. return new Promise(function (resolve, reject) {
  119989. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  119990. resolve(data);
  119991. }, undefined, undefined, false, function (request, error) {
  119992. reject(error);
  119993. });
  119994. _this.loadRequests.push(fileRequest);
  119995. });
  119996. }
  119997. else {
  119998. location_1 = location_1.replace('#', '');
  119999. var element = document.getElementById(location_1);
  120000. if (element) {
  120001. return Promise.resolve(element.innerHTML);
  120002. }
  120003. else {
  120004. return Promise.reject('Template ID not found');
  120005. }
  120006. }
  120007. }
  120008. };
  120009. Template.prototype._registerEvents = function () {
  120010. var _this = this;
  120011. this._registeredEvents = this._registeredEvents || [];
  120012. if (this._registeredEvents.length) {
  120013. // first remove the registered events
  120014. this._registeredEvents.forEach(function (evt) {
  120015. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  120016. });
  120017. }
  120018. if (this._configuration.events) {
  120019. var _loop_1 = function (eventName) {
  120020. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  120021. var functionToFire_1 = function (selector, event) {
  120022. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  120023. };
  120024. // if boolean, set the parent as the event listener
  120025. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  120026. var selector = this_1.parent.id;
  120027. if (selector) {
  120028. selector = '#' + selector;
  120029. }
  120030. else {
  120031. selector = this_1.parent.tagName;
  120032. }
  120033. var binding = functionToFire_1.bind(this_1, selector);
  120034. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  120035. this_1._registeredEvents.push({
  120036. htmlElement: this_1.parent,
  120037. eventName: eventName,
  120038. function: binding
  120039. });
  120040. }
  120041. else if (typeof this_1._configuration.events[eventName] === 'object') {
  120042. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  120043. // strict null checl is working incorrectly, must override:
  120044. var event_1 = this_1._configuration.events[eventName] || {};
  120045. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  120046. var htmlElement = _this.parent.querySelector(selector);
  120047. if (!htmlElement) {
  120048. // backcompat, fallback to id
  120049. if (selector && selector.indexOf('#') !== 0) {
  120050. selector = '#' + selector;
  120051. }
  120052. try {
  120053. htmlElement = _this.parent.querySelector(selector);
  120054. }
  120055. catch (e) { }
  120056. }
  120057. if (htmlElement) {
  120058. var binding = functionToFire_1.bind(_this, selector);
  120059. htmlElement.addEventListener(eventName, binding, false);
  120060. _this._registeredEvents.push({
  120061. htmlElement: htmlElement,
  120062. eventName: eventName,
  120063. function: binding
  120064. });
  120065. }
  120066. });
  120067. }
  120068. }
  120069. };
  120070. var this_1 = this;
  120071. for (var eventName in this._configuration.events) {
  120072. _loop_1(eventName);
  120073. }
  120074. }
  120075. };
  120076. Template.prototype._getTemplateLocation = function (templateConfig) {
  120077. if (!templateConfig || typeof templateConfig === 'string') {
  120078. return templateConfig;
  120079. }
  120080. else {
  120081. return templateConfig.location;
  120082. }
  120083. };
  120084. return Template;
  120085. }());
  120086. exports.Template = Template;
  120087. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvdGVtcGxhdGVNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQ0EsdUNBQTREO0FBQzVELG9DQUE4RDtBQUU5RCx1REFBeUQ7QUFDekQsK0NBQThDO0FBRTlDLCtCQUF1QztBQVl2Qzs7O0dBR0c7QUFDSDtJQThCSSx5QkFBbUIsZ0JBQTZCO1FBQTdCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQUM1QyxJQUFJLENBQUMsU0FBUyxHQUFHLEVBQUUsQ0FBQztRQUVwQixJQUFJLENBQUMsY0FBYyxHQUFHLElBQUksc0JBQVUsRUFBWSxDQUFDO1FBQ2pELElBQUksQ0FBQyxnQkFBZ0IsR0FBRyxJQUFJLHNCQUFVLEVBQVksQ0FBQztRQUNuRCxJQUFJLENBQUMscUJBQXFCLEdBQUcsSUFBSSxzQkFBVSxFQUFZLENBQUM7UUFDeEQsSUFBSSxDQUFDLFdBQVcsR0FBRyxJQUFJLHNCQUFVLEVBQW1CLENBQUM7UUFDckQsSUFBSSxDQUFDLGdCQUFnQixHQUFHLElBQUksc0JBQVUsRUFBaUIsQ0FBQztRQUV4RCxJQUFJLENBQUMsWUFBWSxHQUFHLElBQUksMkJBQVksQ0FBQyxJQU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s2QkFDTjt3QkFDTCxDQUFDLENBQUMsQ0FBQztxQkFDTjtpQkFDSjtZQUNMLENBQUM7O1lBaERELEtBQUssSUFBSSxTQUFTLElBQUksSUFBSSxDQUFDLGNBQWMsQ0FBQyxNQUFNO3dCQUF2QyxTQUFTO2FBZ0RqQjtTQUNKO0lBQ0wsQ0FBQztJQUVPLHVDQUFvQixHQUE1QixVQUE2QixjQUFjO1FBQ3ZDLElBQUksQ0FBQyxjQUFjLElBQUksT0FBTyxjQUFjLEtBQUssUUFBUSxFQUFFO1lBQ3ZELE9BQU8sY0FBYyxDQUFDO1NBQ3pCO2FBQU07WUFDSCxPQUFPLGNBQWMsQ0FBQyxRQUFRLENBQUM7U0FDbEM7SUFDTCxDQUFDO0lBQ0wsZUFBQztBQUFELENBQUMsQUFsWUQsSUFrWUM7QUFsWVksNEJBQVEifQ==
  120088. /***/ }),
  120089. /* 64 */
  120090. /***/ (function(module, exports, __webpack_require__) {
  120091. "use strict";
  120092. Object.defineProperty(exports, "__esModule", { value: true });
  120093. /**
  120094. * The EventManager is in charge of registering user interctions with the viewer.
  120095. * It is used in the TemplateManager
  120096. */
  120097. var EventManager = /** @class */ (function () {
  120098. function EventManager(_templateManager) {
  120099. var _this = this;
  120100. this._templateManager = _templateManager;
  120101. this._callbacksContainer = {};
  120102. this._templateManager.onEventTriggered.add(function (eventData) {
  120103. _this._eventTriggered(eventData);
  120104. });
  120105. }
  120106. /**
  120107. * Register a new callback to a specific template.
  120108. * The best example for the usage can be found in the DefaultViewer
  120109. *
  120110. * @param templateName the templateName to register the event to
  120111. * @param callback The callback to be executed
  120112. * @param eventType the type of event to register
  120113. * @param selector an optional selector. if not defined the parent object in the template will be selected
  120114. */
  120115. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  120116. if (!this._callbacksContainer[templateName]) {
  120117. this._callbacksContainer[templateName] = [];
  120118. }
  120119. this._callbacksContainer[templateName].push({
  120120. eventType: eventType,
  120121. callback: callback,
  120122. selector: selector
  120123. });
  120124. };
  120125. /**
  120126. * This will remove a registered event from the defined template.
  120127. * Each one of the variables apart from the template name are optional, but one must be provided.
  120128. *
  120129. * @param templateName the templateName
  120130. * @param callback the callback to remove (optional)
  120131. * @param eventType the event type to remove (optional)
  120132. * @param selector the selector from which to remove the event (optional)
  120133. */
  120134. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  120135. var callbackDefs = this._callbacksContainer[templateName] || [];
  120136. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  120137. };
  120138. EventManager.prototype._eventTriggered = function (data) {
  120139. var templateName = data.template.name;
  120140. var eventType = data.event.type;
  120141. var selector = data.selector;
  120142. var callbackDefs = this._callbacksContainer[templateName] || [];
  120143. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  120144. callbackDef.callback(data);
  120145. });
  120146. };
  120147. /**
  120148. * Dispose the event manager
  120149. */
  120150. EventManager.prototype.dispose = function () {
  120151. this._callbacksContainer = {};
  120152. };
  120153. return EventManager;
  120154. }());
  120155. exports.EventManager = EventManager;
  120156. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXZlbnRNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvZXZlbnRNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBR0E7OztHQUdHO0FBQ0g7SUFJSSxzQkFBb0IsZ0JBQWlDO1FBQXJELGlCQUtDO1FBTG1CLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBaUI7UUFDakQsSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztRQUM5QixJQUFJ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BQUssUUFBUSxDQUFDLEVBQS9ILENBQStILENBQUMsQ0FBQztJQUNqTixDQUFDO0lBRU8sc0NBQWUsR0FBdkIsVUFBd0IsSUFBbUI7UUFDdkMsSUFBSSxZQUFZLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQyxJQUFJLENBQUM7UUFDdEMsSUFBSSxTQUFTLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUM7UUFDaEMsSUFBSSxRQUFRLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQztRQUU3QixJQUFJLFlBQVksR0FBRyxJQUFJLENBQUMsbUJBQW1CLENBQUMsWUFBWSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQ2hFLFlBQVksQ0FBQyxNQUFNLENBQUMsVUFBQSxXQUFXLElBQUksT0FBQSxDQUFDLENBQUMsV0FBVyxDQUFDLFNBQVMsSUFBSSxXQUFXLENBQUMsU0FBUyxLQUFLLFNBQVMsQ0FBQyxJQUFJLENBQUMsQ0FBQyxXQUFXLENBQUMsUUFBUSxJQUFJLFdBQVcsQ0FBQyxRQUFRLEtBQUssUUFBUSxDQUFDLEVBQS9ILENBQStILENBQUMsQ0FBQyxPQUFPLENBQUMsVUFBQSxXQUFXO1lBQ25MLFdBQVcsQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDL0IsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUQ7O09BRUc7SUFDSSw4QkFBTyxHQUFkO1FBQ0ksSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztJQUNsQyxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBOURELElBOERDO0FBOURZLG9DQUFZIn0=
  120157. /***/ }),
  120158. /* 65 */
  120159. /***/ (function(module, exports, __webpack_require__) {
  120160. "use strict";
  120161. var __extends = (this && this.__extends) || (function () {
  120162. var extendStatics = Object.setPrototypeOf ||
  120163. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  120164. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  120165. return function (d, b) {
  120166. extendStatics(d, b);
  120167. function __() { this.constructor = d; }
  120168. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  120169. };
  120170. })();
  120171. Object.defineProperty(exports, "__esModule", { value: true });
  120172. var viewerTemplatePlugin_1 = __webpack_require__(16);
  120173. var HDButtonPlugin = /** @class */ (function (_super) {
  120174. __extends(HDButtonPlugin, _super);
  120175. function HDButtonPlugin(_viewer) {
  120176. var _this = _super.call(this) || this;
  120177. _this._viewer = _viewer;
  120178. _this._buttonClass = "hd-button";
  120179. _this._htmlTemplate = "\n{{#unless hideHd}}\n<style>\n.hd-icon:after {\n font-size: 16px;\n content: \"\\F765\";\n}\n\n.hd-toggled span.hd-icon:after {\n content: \"\\F766\";\n}\n</style>\n<button class=\"hd-button\" title=\"{{text.hdButton}}\">\n <span class=\"icon hd-icon\"></span>\n </button>\n {{/unless}}\n";
  120180. return _this;
  120181. }
  120182. HDButtonPlugin.prototype.onEvent = function (event) {
  120183. var button = event.template.parent.querySelector(".hd-button");
  120184. if (button) {
  120185. button.classList.contains("hd-toggled") ? button.classList.remove("hd-toggled") : button.classList.add("hd-toggled");
  120186. }
  120187. this._viewer.toggleHD();
  120188. };
  120189. return HDButtonPlugin;
  120190. }(viewerTemplatePlugin_1.AbstractViewerNavbarButton));
  120191. exports.HDButtonPlugin = HDButtonPlugin;
  120192. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaGRCdXR0b25QbHVnaW4uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvdGVtcGxhdGluZy9wbHVnaW5zL2hkQnV0dG9uUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7OztBQUFBLGdFQUFxRTtBQUlyRTtJQUFvQyxrQ0FBMEI7SUFJMUQsd0JBQW9CLE9BQXNCO1FBQTFDLFlBQ0ksaUJBQU8sU0FDVjtRQUZtQixhQUFPLEdBQVAsT0FBTyxDQUFlO1FBRmhDLGtCQUFZLEdBQUcsV0FBVyxDQUFDO1FBYzNCLG1CQUFhLEdBQVcsZ1RBZ0JyQyxDQUFDOztJQTFCRSxDQUFDO0lBRUQsZ0NBQU8sR0FBUCxVQUFRLEtBQW9CO1FBQ3hCLElBQUksTUFBTSxHQUFHLEtBQUssQ0FBQyxRQUFRLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxZQUFZLENBQUMsQ0FBQztRQUMvRCxJQUFJLE1BQU0sRUFBRTtZQUNSLE1BQU0sQ0FBQyxTQUFTLENBQUMsUUFBUSxDQUFDLFlBQVksQ0FBQyxDQUFDLENBQUMsQ0FBQyxNQUFNLENBQUMsU0FBUyxDQUFDLE1BQU0sQ0FBQyxZQUFZLENBQUMsQ0FBQyxDQUFDLENBQUMsTUFBTSxDQUFDLFNBQVMsQ0FBQyxHQUFHLENBQUMsWUFBWSxDQUFDLENBQUM7U0FDeEg7UUFDRCxJQUFJLENBQUMsT0FBTyxDQUFDLFFBQVEsRUFBRSxDQUFDO0lBQzVCLENBQUM7SUFtQkwscUJBQUM7QUFBRCxDQUFDLEFBakNELENBQW9DLGlEQUEwQixHQWlDN0Q7QUFqQ1ksd0NBQWMifQ==
  120193. /***/ }),
  120194. /* 66 */
  120195. /***/ (function(module, exports, __webpack_require__) {
  120196. /*!
  120197. * PEP v0.4.3 | https://github.com/jquery/PEP
  120198. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  120199. */
  120200. (function (global, factory) {
  120201. true ? module.exports = factory() :
  120202. typeof define === 'function' && define.amd ? define(factory) :
  120203. (global.PointerEventsPolyfill = factory());
  120204. }(this, function () { 'use strict';
  120205. /**
  120206. * This is the constructor for new PointerEvents.
  120207. *
  120208. * New Pointer Events must be given a type, and an optional dictionary of
  120209. * initialization properties.
  120210. *
  120211. * Due to certain platform requirements, events returned from the constructor
  120212. * identify as MouseEvents.
  120213. *
  120214. * @constructor
  120215. * @param {String} inType The type of the event to create.
  120216. * @param {Object} [inDict] An optional dictionary of initial event properties.
  120217. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  120218. */
  120219. var MOUSE_PROPS = [
  120220. 'bubbles',
  120221. 'cancelable',
  120222. 'view',
  120223. 'detail',
  120224. 'screenX',
  120225. 'screenY',
  120226. 'clientX',
  120227. 'clientY',
  120228. 'ctrlKey',
  120229. 'altKey',
  120230. 'shiftKey',
  120231. 'metaKey',
  120232. 'button',
  120233. 'relatedTarget',
  120234. 'pageX',
  120235. 'pageY'
  120236. ];
  120237. var MOUSE_DEFAULTS = [
  120238. false,
  120239. false,
  120240. null,
  120241. null,
  120242. 0,
  120243. 0,
  120244. 0,
  120245. 0,
  120246. false,
  120247. false,
  120248. false,
  120249. false,
  120250. 0,
  120251. null,
  120252. 0,
  120253. 0
  120254. ];
  120255. function PointerEvent(inType, inDict) {
  120256. inDict = inDict || Object.create(null);
  120257. var e = document.createEvent('Event');
  120258. e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false);
  120259. // define inherited MouseEvent properties
  120260. // skip bubbles and cancelable since they're set above in initEvent()
  120261. for (var i = 2, p; i < MOUSE_PROPS.length; i++) {
  120262. p = MOUSE_PROPS[i];
  120263. e[p] = inDict[p] || MOUSE_DEFAULTS[i];
  120264. }
  120265. e.buttons = inDict.buttons || 0;
  120266. // Spec requires that pointers without pressure specified use 0.5 for down
  120267. // state and 0 for up state.
  120268. var pressure = 0;
  120269. if (inDict.pressure && e.buttons) {
  120270. pressure = inDict.pressure;
  120271. } else {
  120272. pressure = e.buttons ? 0.5 : 0;
  120273. }
  120274. // add x/y properties aliased to clientX/Y
  120275. e.x = e.clientX;
  120276. e.y = e.clientY;
  120277. // define the properties of the PointerEvent interface
  120278. e.pointerId = inDict.pointerId || 0;
  120279. e.width = inDict.width || 0;
  120280. e.height = inDict.height || 0;
  120281. e.pressure = pressure;
  120282. e.tiltX = inDict.tiltX || 0;
  120283. e.tiltY = inDict.tiltY || 0;
  120284. e.twist = inDict.twist || 0;
  120285. e.tangentialPressure = inDict.tangentialPressure || 0;
  120286. e.pointerType = inDict.pointerType || '';
  120287. e.hwTimestamp = inDict.hwTimestamp || 0;
  120288. e.isPrimary = inDict.isPrimary || false;
  120289. return e;
  120290. }
  120291. /**
  120292. * This module implements a map of pointer states
  120293. */
  120294. var USE_MAP = window.Map && window.Map.prototype.forEach;
  120295. var PointerMap = USE_MAP ? Map : SparseArrayMap;
  120296. function SparseArrayMap() {
  120297. this.array = [];
  120298. this.size = 0;
  120299. }
  120300. SparseArrayMap.prototype = {
  120301. set: function(k, v) {
  120302. if (v === undefined) {
  120303. return this.delete(k);
  120304. }
  120305. if (!this.has(k)) {
  120306. this.size++;
  120307. }
  120308. this.array[k] = v;
  120309. },
  120310. has: function(k) {
  120311. return this.array[k] !== undefined;
  120312. },
  120313. delete: function(k) {
  120314. if (this.has(k)) {
  120315. delete this.array[k];
  120316. this.size--;
  120317. }
  120318. },
  120319. get: function(k) {
  120320. return this.array[k];
  120321. },
  120322. clear: function() {
  120323. this.array.length = 0;
  120324. this.size = 0;
  120325. },
  120326. // return value, key, map
  120327. forEach: function(callback, thisArg) {
  120328. return this.array.forEach(function(v, k) {
  120329. callback.call(thisArg, v, k, this);
  120330. }, this);
  120331. }
  120332. };
  120333. var CLONE_PROPS = [
  120334. // MouseEvent
  120335. 'bubbles',
  120336. 'cancelable',
  120337. 'view',
  120338. 'detail',
  120339. 'screenX',
  120340. 'screenY',
  120341. 'clientX',
  120342. 'clientY',
  120343. 'ctrlKey',
  120344. 'altKey',
  120345. 'shiftKey',
  120346. 'metaKey',
  120347. 'button',
  120348. 'relatedTarget',
  120349. // DOM Level 3
  120350. 'buttons',
  120351. // PointerEvent
  120352. 'pointerId',
  120353. 'width',
  120354. 'height',
  120355. 'pressure',
  120356. 'tiltX',
  120357. 'tiltY',
  120358. 'pointerType',
  120359. 'hwTimestamp',
  120360. 'isPrimary',
  120361. // event instance
  120362. 'type',
  120363. 'target',
  120364. 'currentTarget',
  120365. 'which',
  120366. 'pageX',
  120367. 'pageY',
  120368. 'timeStamp'
  120369. ];
  120370. var CLONE_DEFAULTS = [
  120371. // MouseEvent
  120372. false,
  120373. false,
  120374. null,
  120375. null,
  120376. 0,
  120377. 0,
  120378. 0,
  120379. 0,
  120380. false,
  120381. false,
  120382. false,
  120383. false,
  120384. 0,
  120385. null,
  120386. // DOM Level 3
  120387. 0,
  120388. // PointerEvent
  120389. 0,
  120390. 0,
  120391. 0,
  120392. 0,
  120393. 0,
  120394. 0,
  120395. '',
  120396. 0,
  120397. false,
  120398. // event instance
  120399. '',
  120400. null,
  120401. null,
  120402. 0,
  120403. 0,
  120404. 0,
  120405. 0
  120406. ];
  120407. var BOUNDARY_EVENTS = {
  120408. 'pointerover': 1,
  120409. 'pointerout': 1,
  120410. 'pointerenter': 1,
  120411. 'pointerleave': 1
  120412. };
  120413. var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined');
  120414. /**
  120415. * This module is for normalizing events. Mouse and Touch events will be
  120416. * collected here, and fire PointerEvents that have the same semantics, no
  120417. * matter the source.
  120418. * Events fired:
  120419. * - pointerdown: a pointing is added
  120420. * - pointerup: a pointer is removed
  120421. * - pointermove: a pointer is moved
  120422. * - pointerover: a pointer crosses into an element
  120423. * - pointerout: a pointer leaves an element
  120424. * - pointercancel: a pointer will no longer generate events
  120425. */
  120426. var dispatcher = {
  120427. pointermap: new PointerMap(),
  120428. eventMap: Object.create(null),
  120429. captureInfo: Object.create(null),
  120430. // Scope objects for native events.
  120431. // This exists for ease of testing.
  120432. eventSources: Object.create(null),
  120433. eventSourceList: [],
  120434. /**
  120435. * Add a new event source that will generate pointer events.
  120436. *
  120437. * `inSource` must contain an array of event names named `events`, and
  120438. * functions with the names specified in the `events` array.
  120439. * @param {string} name A name for the event source
  120440. * @param {Object} source A new source of platform events.
  120441. */
  120442. registerSource: function(name, source) {
  120443. var s = source;
  120444. var newEvents = s.events;
  120445. if (newEvents) {
  120446. newEvents.forEach(function(e) {
  120447. if (s[e]) {
  120448. this.eventMap[e] = s[e].bind(s);
  120449. }
  120450. }, this);
  120451. this.eventSources[name] = s;
  120452. this.eventSourceList.push(s);
  120453. }
  120454. },
  120455. register: function(element) {
  120456. var l = this.eventSourceList.length;
  120457. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  120458. // call eventsource register
  120459. es.register.call(es, element);
  120460. }
  120461. },
  120462. unregister: function(element) {
  120463. var l = this.eventSourceList.length;
  120464. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  120465. // call eventsource register
  120466. es.unregister.call(es, element);
  120467. }
  120468. },
  120469. contains: /*scope.external.contains || */function(container, contained) {
  120470. try {
  120471. return container.contains(contained);
  120472. } catch (ex) {
  120473. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  120474. return false;
  120475. }
  120476. },
  120477. // EVENTS
  120478. down: function(inEvent) {
  120479. inEvent.bubbles = true;
  120480. this.fireEvent('pointerdown', inEvent);
  120481. },
  120482. move: function(inEvent) {
  120483. inEvent.bubbles = true;
  120484. this.fireEvent('pointermove', inEvent);
  120485. },
  120486. up: function(inEvent) {
  120487. inEvent.bubbles = true;
  120488. this.fireEvent('pointerup', inEvent);
  120489. },
  120490. enter: function(inEvent) {
  120491. inEvent.bubbles = false;
  120492. this.fireEvent('pointerenter', inEvent);
  120493. },
  120494. leave: function(inEvent) {
  120495. inEvent.bubbles = false;
  120496. this.fireEvent('pointerleave', inEvent);
  120497. },
  120498. over: function(inEvent) {
  120499. inEvent.bubbles = true;
  120500. this.fireEvent('pointerover', inEvent);
  120501. },
  120502. out: function(inEvent) {
  120503. inEvent.bubbles = true;
  120504. this.fireEvent('pointerout', inEvent);
  120505. },
  120506. cancel: function(inEvent) {
  120507. inEvent.bubbles = true;
  120508. this.fireEvent('pointercancel', inEvent);
  120509. },
  120510. leaveOut: function(event) {
  120511. this.out(event);
  120512. this.propagate(event, this.leave, false);
  120513. },
  120514. enterOver: function(event) {
  120515. this.over(event);
  120516. this.propagate(event, this.enter, true);
  120517. },
  120518. // LISTENER LOGIC
  120519. eventHandler: function(inEvent) {
  120520. // This is used to prevent multiple dispatch of pointerevents from
  120521. // platform events. This can happen when two elements in different scopes
  120522. // are set up to create pointer events, which is relevant to Shadow DOM.
  120523. if (inEvent._handledByPE) {
  120524. return;
  120525. }
  120526. var type = inEvent.type;
  120527. var fn = this.eventMap && this.eventMap[type];
  120528. if (fn) {
  120529. fn(inEvent);
  120530. }
  120531. inEvent._handledByPE = true;
  120532. },
  120533. // set up event listeners
  120534. listen: function(target, events) {
  120535. events.forEach(function(e) {
  120536. this.addEvent(target, e);
  120537. }, this);
  120538. },
  120539. // remove event listeners
  120540. unlisten: function(target, events) {
  120541. events.forEach(function(e) {
  120542. this.removeEvent(target, e);
  120543. }, this);
  120544. },
  120545. addEvent: /*scope.external.addEvent || */function(target, eventName) {
  120546. target.addEventListener(eventName, this.boundHandler);
  120547. },
  120548. removeEvent: /*scope.external.removeEvent || */function(target, eventName) {
  120549. target.removeEventListener(eventName, this.boundHandler);
  120550. },
  120551. // EVENT CREATION AND TRACKING
  120552. /**
  120553. * Creates a new Event of type `inType`, based on the information in
  120554. * `inEvent`.
  120555. *
  120556. * @param {string} inType A string representing the type of event to create
  120557. * @param {Event} inEvent A platform event with a target
  120558. * @return {Event} A PointerEvent of type `inType`
  120559. */
  120560. makeEvent: function(inType, inEvent) {
  120561. // relatedTarget must be null if pointer is captured
  120562. if (this.captureInfo[inEvent.pointerId]) {
  120563. inEvent.relatedTarget = null;
  120564. }
  120565. var e = new PointerEvent(inType, inEvent);
  120566. if (inEvent.preventDefault) {
  120567. e.preventDefault = inEvent.preventDefault;
  120568. }
  120569. e._target = e._target || inEvent.target;
  120570. return e;
  120571. },
  120572. // make and dispatch an event in one call
  120573. fireEvent: function(inType, inEvent) {
  120574. var e = this.makeEvent(inType, inEvent);
  120575. return this.dispatchEvent(e);
  120576. },
  120577. /**
  120578. * Returns a snapshot of inEvent, with writable properties.
  120579. *
  120580. * @param {Event} inEvent An event that contains properties to copy.
  120581. * @return {Object} An object containing shallow copies of `inEvent`'s
  120582. * properties.
  120583. */
  120584. cloneEvent: function(inEvent) {
  120585. var eventCopy = Object.create(null);
  120586. var p;
  120587. for (var i = 0; i < CLONE_PROPS.length; i++) {
  120588. p = CLONE_PROPS[i];
  120589. eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i];
  120590. // Work around SVGInstanceElement shadow tree
  120591. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  120592. // This is the behavior implemented by Firefox.
  120593. if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) {
  120594. if (eventCopy[p] instanceof SVGElementInstance) {
  120595. eventCopy[p] = eventCopy[p].correspondingUseElement;
  120596. }
  120597. }
  120598. }
  120599. // keep the semantics of preventDefault
  120600. if (inEvent.preventDefault) {
  120601. eventCopy.preventDefault = function() {
  120602. inEvent.preventDefault();
  120603. };
  120604. }
  120605. return eventCopy;
  120606. },
  120607. getTarget: function(inEvent) {
  120608. var capture = this.captureInfo[inEvent.pointerId];
  120609. if (!capture) {
  120610. return inEvent._target;
  120611. }
  120612. if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) {
  120613. return capture;
  120614. }
  120615. },
  120616. propagate: function(event, fn, propagateDown) {
  120617. var target = event.target;
  120618. var targets = [];
  120619. // Order of conditions due to document.contains() missing in IE.
  120620. while (target !== document && !target.contains(event.relatedTarget)) {
  120621. targets.push(target);
  120622. target = target.parentNode;
  120623. // Touch: Do not propagate if node is detached.
  120624. if (!target) {
  120625. return;
  120626. }
  120627. }
  120628. if (propagateDown) {
  120629. targets.reverse();
  120630. }
  120631. targets.forEach(function(target) {
  120632. event.target = target;
  120633. fn.call(this, event);
  120634. }, this);
  120635. },
  120636. setCapture: function(inPointerId, inTarget, skipDispatch) {
  120637. if (this.captureInfo[inPointerId]) {
  120638. this.releaseCapture(inPointerId, skipDispatch);
  120639. }
  120640. this.captureInfo[inPointerId] = inTarget;
  120641. this.implicitRelease = this.releaseCapture.bind(this, inPointerId, skipDispatch);
  120642. document.addEventListener('pointerup', this.implicitRelease);
  120643. document.addEventListener('pointercancel', this.implicitRelease);
  120644. var e = new PointerEvent('gotpointercapture');
  120645. e.pointerId = inPointerId;
  120646. e._target = inTarget;
  120647. if (!skipDispatch) {
  120648. this.asyncDispatchEvent(e);
  120649. }
  120650. },
  120651. releaseCapture: function(inPointerId, skipDispatch) {
  120652. var t = this.captureInfo[inPointerId];
  120653. if (!t) {
  120654. return;
  120655. }
  120656. this.captureInfo[inPointerId] = undefined;
  120657. document.removeEventListener('pointerup', this.implicitRelease);
  120658. document.removeEventListener('pointercancel', this.implicitRelease);
  120659. var e = new PointerEvent('lostpointercapture');
  120660. e.pointerId = inPointerId;
  120661. e._target = t;
  120662. if (!skipDispatch) {
  120663. this.asyncDispatchEvent(e);
  120664. }
  120665. },
  120666. /**
  120667. * Dispatches the event to its target.
  120668. *
  120669. * @param {Event} inEvent The event to be dispatched.
  120670. * @return {Boolean} True if an event handler returns true, false otherwise.
  120671. */
  120672. dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) {
  120673. var t = this.getTarget(inEvent);
  120674. if (t) {
  120675. return t.dispatchEvent(inEvent);
  120676. }
  120677. },
  120678. asyncDispatchEvent: function(inEvent) {
  120679. requestAnimationFrame(this.dispatchEvent.bind(this, inEvent));
  120680. }
  120681. };
  120682. dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
  120683. var targeting = {
  120684. shadow: function(inEl) {
  120685. if (inEl) {
  120686. return inEl.shadowRoot || inEl.webkitShadowRoot;
  120687. }
  120688. },
  120689. canTarget: function(shadow) {
  120690. return shadow && Boolean(shadow.elementFromPoint);
  120691. },
  120692. targetingShadow: function(inEl) {
  120693. var s = this.shadow(inEl);
  120694. if (this.canTarget(s)) {
  120695. return s;
  120696. }
  120697. },
  120698. olderShadow: function(shadow) {
  120699. var os = shadow.olderShadowRoot;
  120700. if (!os) {
  120701. var se = shadow.querySelector('shadow');
  120702. if (se) {
  120703. os = se.olderShadowRoot;
  120704. }
  120705. }
  120706. return os;
  120707. },
  120708. allShadows: function(element) {
  120709. var shadows = [];
  120710. var s = this.shadow(element);
  120711. while (s) {
  120712. shadows.push(s);
  120713. s = this.olderShadow(s);
  120714. }
  120715. return shadows;
  120716. },
  120717. searchRoot: function(inRoot, x, y) {
  120718. if (inRoot) {
  120719. var t = inRoot.elementFromPoint(x, y);
  120720. var st, sr;
  120721. // is element a shadow host?
  120722. sr = this.targetingShadow(t);
  120723. while (sr) {
  120724. // find the the element inside the shadow root
  120725. st = sr.elementFromPoint(x, y);
  120726. if (!st) {
  120727. // check for older shadows
  120728. sr = this.olderShadow(sr);
  120729. } else {
  120730. // shadowed element may contain a shadow root
  120731. var ssr = this.targetingShadow(st);
  120732. return this.searchRoot(ssr, x, y) || st;
  120733. }
  120734. }
  120735. // light dom element is the target
  120736. return t;
  120737. }
  120738. },
  120739. owner: function(element) {
  120740. var s = element;
  120741. // walk up until you hit the shadow root or document
  120742. while (s.parentNode) {
  120743. s = s.parentNode;
  120744. }
  120745. // the owner element is expected to be a Document or ShadowRoot
  120746. if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
  120747. s = document;
  120748. }
  120749. return s;
  120750. },
  120751. findTarget: function(inEvent) {
  120752. var x = inEvent.clientX;
  120753. var y = inEvent.clientY;
  120754. // if the listener is in the shadow root, it is much faster to start there
  120755. var s = this.owner(inEvent.target);
  120756. // if x, y is not in this root, fall back to document search
  120757. if (!s.elementFromPoint(x, y)) {
  120758. s = document;
  120759. }
  120760. return this.searchRoot(s, x, y);
  120761. }
  120762. };
  120763. var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
  120764. var map = Array.prototype.map.call.bind(Array.prototype.map);
  120765. var toArray = Array.prototype.slice.call.bind(Array.prototype.slice);
  120766. var filter = Array.prototype.filter.call.bind(Array.prototype.filter);
  120767. var MO = window.MutationObserver || window.WebKitMutationObserver;
  120768. var SELECTOR = '[touch-action]';
  120769. var OBSERVER_INIT = {
  120770. subtree: true,
  120771. childList: true,
  120772. attributes: true,
  120773. attributeOldValue: true,
  120774. attributeFilter: ['touch-action']
  120775. };
  120776. function Installer(add, remove, changed, binder) {
  120777. this.addCallback = add.bind(binder);
  120778. this.removeCallback = remove.bind(binder);
  120779. this.changedCallback = changed.bind(binder);
  120780. if (MO) {
  120781. this.observer = new MO(this.mutationWatcher.bind(this));
  120782. }
  120783. }
  120784. Installer.prototype = {
  120785. watchSubtree: function(target) {
  120786. // Only watch scopes that can target find, as these are top-level.
  120787. // Otherwise we can see duplicate additions and removals that add noise.
  120788. //
  120789. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  120790. // a removal without an insertion when a node is redistributed among
  120791. // shadows. Since it all ends up correct in the document, watching only
  120792. // the document will yield the correct mutations to watch.
  120793. if (this.observer && targeting.canTarget(target)) {
  120794. this.observer.observe(target, OBSERVER_INIT);
  120795. }
  120796. },
  120797. enableOnSubtree: function(target) {
  120798. this.watchSubtree(target);
  120799. if (target === document && document.readyState !== 'complete') {
  120800. this.installOnLoad();
  120801. } else {
  120802. this.installNewSubtree(target);
  120803. }
  120804. },
  120805. installNewSubtree: function(target) {
  120806. forEach(this.findElements(target), this.addElement, this);
  120807. },
  120808. findElements: function(target) {
  120809. if (target.querySelectorAll) {
  120810. return target.querySelectorAll(SELECTOR);
  120811. }
  120812. return [];
  120813. },
  120814. removeElement: function(el) {
  120815. this.removeCallback(el);
  120816. },
  120817. addElement: function(el) {
  120818. this.addCallback(el);
  120819. },
  120820. elementChanged: function(el, oldValue) {
  120821. this.changedCallback(el, oldValue);
  120822. },
  120823. concatLists: function(accum, list) {
  120824. return accum.concat(toArray(list));
  120825. },
  120826. // register all touch-action = none nodes on document load
  120827. installOnLoad: function() {
  120828. document.addEventListener('readystatechange', function() {
  120829. if (document.readyState === 'complete') {
  120830. this.installNewSubtree(document);
  120831. }
  120832. }.bind(this));
  120833. },
  120834. isElement: function(n) {
  120835. return n.nodeType === Node.ELEMENT_NODE;
  120836. },
  120837. flattenMutationTree: function(inNodes) {
  120838. // find children with touch-action
  120839. var tree = map(inNodes, this.findElements, this);
  120840. // make sure the added nodes are accounted for
  120841. tree.push(filter(inNodes, this.isElement));
  120842. // flatten the list
  120843. return tree.reduce(this.concatLists, []);
  120844. },
  120845. mutationWatcher: function(mutations) {
  120846. mutations.forEach(this.mutationHandler, this);
  120847. },
  120848. mutationHandler: function(m) {
  120849. if (m.type === 'childList') {
  120850. var added = this.flattenMutationTree(m.addedNodes);
  120851. added.forEach(this.addElement, this);
  120852. var removed = this.flattenMutationTree(m.removedNodes);
  120853. removed.forEach(this.removeElement, this);
  120854. } else if (m.type === 'attributes') {
  120855. this.elementChanged(m.target, m.oldValue);
  120856. }
  120857. }
  120858. };
  120859. function shadowSelector(v) {
  120860. return 'body /shadow-deep/ ' + selector(v);
  120861. }
  120862. function selector(v) {
  120863. return '[touch-action="' + v + '"]';
  120864. }
  120865. function rule(v) {
  120866. return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
  120867. }
  120868. var attrib2css = [
  120869. 'none',
  120870. 'auto',
  120871. 'pan-x',
  120872. 'pan-y',
  120873. {
  120874. rule: 'pan-x pan-y',
  120875. selectors: [
  120876. 'pan-x pan-y',
  120877. 'pan-y pan-x'
  120878. ]
  120879. }
  120880. ];
  120881. var styles = '';
  120882. // only install stylesheet if the browser has touch action support
  120883. var hasNativePE = window.PointerEvent || window.MSPointerEvent;
  120884. // only add shadow selectors if shadowdom is supported
  120885. var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;
  120886. function applyAttributeStyles() {
  120887. if (hasNativePE) {
  120888. attrib2css.forEach(function(r) {
  120889. if (String(r) === r) {
  120890. styles += selector(r) + rule(r) + '\n';
  120891. if (hasShadowRoot) {
  120892. styles += shadowSelector(r) + rule(r) + '\n';
  120893. }
  120894. } else {
  120895. styles += r.selectors.map(selector) + rule(r.rule) + '\n';
  120896. if (hasShadowRoot) {
  120897. styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n';
  120898. }
  120899. }
  120900. });
  120901. var el = document.createElement('style');
  120902. el.textContent = styles;
  120903. document.head.appendChild(el);
  120904. }
  120905. }
  120906. var pointermap = dispatcher.pointermap;
  120907. // radius around touchend that swallows mouse events
  120908. var DEDUP_DIST = 25;
  120909. // left, middle, right, back, forward
  120910. var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16];
  120911. var HAS_BUTTONS = false;
  120912. try {
  120913. HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1;
  120914. } catch (e) {}
  120915. // handler block for native mouse events
  120916. var mouseEvents = {
  120917. POINTER_ID: 1,
  120918. POINTER_TYPE: 'mouse',
  120919. events: [
  120920. 'mousedown',
  120921. 'mousemove',
  120922. 'mouseup',
  120923. 'mouseover',
  120924. 'mouseout'
  120925. ],
  120926. register: function(target) {
  120927. dispatcher.listen(target, this.events);
  120928. },
  120929. unregister: function(target) {
  120930. dispatcher.unlisten(target, this.events);
  120931. },
  120932. lastTouches: [],
  120933. // collide with the global mouse listener
  120934. isEventSimulatedFromTouch: function(inEvent) {
  120935. var lts = this.lastTouches;
  120936. var x = inEvent.clientX;
  120937. var y = inEvent.clientY;
  120938. for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
  120939. // simulated mouse events will be swallowed near a primary touchend
  120940. var dx = Math.abs(x - t.x);
  120941. var dy = Math.abs(y - t.y);
  120942. if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
  120943. return true;
  120944. }
  120945. }
  120946. },
  120947. prepareEvent: function(inEvent) {
  120948. var e = dispatcher.cloneEvent(inEvent);
  120949. // forward mouse preventDefault
  120950. var pd = e.preventDefault;
  120951. e.preventDefault = function() {
  120952. inEvent.preventDefault();
  120953. pd();
  120954. };
  120955. e.pointerId = this.POINTER_ID;
  120956. e.isPrimary = true;
  120957. e.pointerType = this.POINTER_TYPE;
  120958. return e;
  120959. },
  120960. prepareButtonsForMove: function(e, inEvent) {
  120961. var p = pointermap.get(this.POINTER_ID);
  120962. // Update buttons state after possible out-of-document mouseup.
  120963. if (inEvent.which === 0 || !p) {
  120964. e.buttons = 0;
  120965. } else {
  120966. e.buttons = p.buttons;
  120967. }
  120968. inEvent.buttons = e.buttons;
  120969. },
  120970. mousedown: function(inEvent) {
  120971. if (!this.isEventSimulatedFromTouch(inEvent)) {
  120972. var p = pointermap.get(this.POINTER_ID);
  120973. var e = this.prepareEvent(inEvent);
  120974. if (!HAS_BUTTONS) {
  120975. e.buttons = BUTTON_TO_BUTTONS[e.button];
  120976. if (p) { e.buttons |= p.buttons; }
  120977. inEvent.buttons = e.buttons;
  120978. }
  120979. pointermap.set(this.POINTER_ID, inEvent);
  120980. if (!p || p.buttons === 0) {
  120981. dispatcher.down(e);
  120982. } else {
  120983. dispatcher.move(e);
  120984. }
  120985. }
  120986. },
  120987. mousemove: function(inEvent) {
  120988. if (!this.isEventSimulatedFromTouch(inEvent)) {
  120989. var e = this.prepareEvent(inEvent);
  120990. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  120991. e.button = -1;
  120992. pointermap.set(this.POINTER_ID, inEvent);
  120993. dispatcher.move(e);
  120994. }
  120995. },
  120996. mouseup: function(inEvent) {
  120997. if (!this.isEventSimulatedFromTouch(inEvent)) {
  120998. var p = pointermap.get(this.POINTER_ID);
  120999. var e = this.prepareEvent(inEvent);
  121000. if (!HAS_BUTTONS) {
  121001. var up = BUTTON_TO_BUTTONS[e.button];
  121002. // Produces wrong state of buttons in Browsers without `buttons` support
  121003. // when a mouse button that was pressed outside the document is released
  121004. // inside and other buttons are still pressed down.
  121005. e.buttons = p ? p.buttons & ~up : 0;
  121006. inEvent.buttons = e.buttons;
  121007. }
  121008. pointermap.set(this.POINTER_ID, inEvent);
  121009. // Support: Firefox <=44 only
  121010. // FF Ubuntu includes the lifted button in the `buttons` property on
  121011. // mouseup.
  121012. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  121013. e.buttons &= ~BUTTON_TO_BUTTONS[e.button];
  121014. if (e.buttons === 0) {
  121015. dispatcher.up(e);
  121016. } else {
  121017. dispatcher.move(e);
  121018. }
  121019. }
  121020. },
  121021. mouseover: function(inEvent) {
  121022. if (!this.isEventSimulatedFromTouch(inEvent)) {
  121023. var e = this.prepareEvent(inEvent);
  121024. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  121025. e.button = -1;
  121026. pointermap.set(this.POINTER_ID, inEvent);
  121027. dispatcher.enterOver(e);
  121028. }
  121029. },
  121030. mouseout: function(inEvent) {
  121031. if (!this.isEventSimulatedFromTouch(inEvent)) {
  121032. var e = this.prepareEvent(inEvent);
  121033. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  121034. e.button = -1;
  121035. dispatcher.leaveOut(e);
  121036. }
  121037. },
  121038. cancel: function(inEvent) {
  121039. var e = this.prepareEvent(inEvent);
  121040. dispatcher.cancel(e);
  121041. this.deactivateMouse();
  121042. },
  121043. deactivateMouse: function() {
  121044. pointermap.delete(this.POINTER_ID);
  121045. }
  121046. };
  121047. var captureInfo = dispatcher.captureInfo;
  121048. var findTarget = targeting.findTarget.bind(targeting);
  121049. var allShadows = targeting.allShadows.bind(targeting);
  121050. var pointermap$1 = dispatcher.pointermap;
  121051. // This should be long enough to ignore compat mouse events made by touch
  121052. var DEDUP_TIMEOUT = 2500;
  121053. var CLICK_COUNT_TIMEOUT = 200;
  121054. var ATTRIB = 'touch-action';
  121055. var INSTALLER;
  121056. // handler block for native touch events
  121057. var touchEvents = {
  121058. events: [
  121059. 'touchstart',
  121060. 'touchmove',
  121061. 'touchend',
  121062. 'touchcancel'
  121063. ],
  121064. register: function(target) {
  121065. INSTALLER.enableOnSubtree(target);
  121066. },
  121067. unregister: function() {
  121068. // TODO(dfreedman): is it worth it to disconnect the MO?
  121069. },
  121070. elementAdded: function(el) {
  121071. var a = el.getAttribute(ATTRIB);
  121072. var st = this.touchActionToScrollType(a);
  121073. if (st) {
  121074. el._scrollType = st;
  121075. dispatcher.listen(el, this.events);
  121076. // set touch-action on shadows as well
  121077. allShadows(el).forEach(function(s) {
  121078. s._scrollType = st;
  121079. dispatcher.listen(s, this.events);
  121080. }, this);
  121081. }
  121082. },
  121083. elementRemoved: function(el) {
  121084. el._scrollType = undefined;
  121085. dispatcher.unlisten(el, this.events);
  121086. // remove touch-action from shadow
  121087. allShadows(el).forEach(function(s) {
  121088. s._scrollType = undefined;
  121089. dispatcher.unlisten(s, this.events);
  121090. }, this);
  121091. },
  121092. elementChanged: function(el, oldValue) {
  121093. var a = el.getAttribute(ATTRIB);
  121094. var st = this.touchActionToScrollType(a);
  121095. var oldSt = this.touchActionToScrollType(oldValue);
  121096. // simply update scrollType if listeners are already established
  121097. if (st && oldSt) {
  121098. el._scrollType = st;
  121099. allShadows(el).forEach(function(s) {
  121100. s._scrollType = st;
  121101. }, this);
  121102. } else if (oldSt) {
  121103. this.elementRemoved(el);
  121104. } else if (st) {
  121105. this.elementAdded(el);
  121106. }
  121107. },
  121108. scrollTypes: {
  121109. EMITTER: 'none',
  121110. XSCROLLER: 'pan-x',
  121111. YSCROLLER: 'pan-y',
  121112. SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/
  121113. },
  121114. touchActionToScrollType: function(touchAction) {
  121115. var t = touchAction;
  121116. var st = this.scrollTypes;
  121117. if (t === 'none') {
  121118. return 'none';
  121119. } else if (t === st.XSCROLLER) {
  121120. return 'X';
  121121. } else if (t === st.YSCROLLER) {
  121122. return 'Y';
  121123. } else if (st.SCROLLER.exec(t)) {
  121124. return 'XY';
  121125. }
  121126. },
  121127. POINTER_TYPE: 'touch',
  121128. firstTouch: null,
  121129. isPrimaryTouch: function(inTouch) {
  121130. return this.firstTouch === inTouch.identifier;
  121131. },
  121132. setPrimaryTouch: function(inTouch) {
  121133. // set primary touch if there no pointers, or the only pointer is the mouse
  121134. if (pointermap$1.size === 0 || (pointermap$1.size === 1 && pointermap$1.has(1))) {
  121135. this.firstTouch = inTouch.identifier;
  121136. this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY };
  121137. this.scrolling = false;
  121138. this.cancelResetClickCount();
  121139. }
  121140. },
  121141. removePrimaryPointer: function(inPointer) {
  121142. if (inPointer.isPrimary) {
  121143. this.firstTouch = null;
  121144. this.firstXY = null;
  121145. this.resetClickCount();
  121146. }
  121147. },
  121148. clickCount: 0,
  121149. resetId: null,
  121150. resetClickCount: function() {
  121151. var fn = function() {
  121152. this.clickCount = 0;
  121153. this.resetId = null;
  121154. }.bind(this);
  121155. this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT);
  121156. },
  121157. cancelResetClickCount: function() {
  121158. if (this.resetId) {
  121159. clearTimeout(this.resetId);
  121160. }
  121161. },
  121162. typeToButtons: function(type) {
  121163. var ret = 0;
  121164. if (type === 'touchstart' || type === 'touchmove') {
  121165. ret = 1;
  121166. }
  121167. return ret;
  121168. },
  121169. touchToPointer: function(inTouch) {
  121170. var cte = this.currentTouchEvent;
  121171. var e = dispatcher.cloneEvent(inTouch);
  121172. // We reserve pointerId 1 for Mouse.
  121173. // Touch identifiers can start at 0.
  121174. // Add 2 to the touch identifier for compatibility.
  121175. var id = e.pointerId = inTouch.identifier + 2;
  121176. e.target = captureInfo[id] || findTarget(e);
  121177. e.bubbles = true;
  121178. e.cancelable = true;
  121179. e.detail = this.clickCount;
  121180. e.button = 0;
  121181. e.buttons = this.typeToButtons(cte.type);
  121182. e.width = (inTouch.radiusX || inTouch.webkitRadiusX || 0) * 2;
  121183. e.height = (inTouch.radiusY || inTouch.webkitRadiusY || 0) * 2;
  121184. e.pressure = inTouch.force || inTouch.webkitForce || 0.5;
  121185. e.isPrimary = this.isPrimaryTouch(inTouch);
  121186. e.pointerType = this.POINTER_TYPE;
  121187. // forward modifier keys
  121188. e.altKey = cte.altKey;
  121189. e.ctrlKey = cte.ctrlKey;
  121190. e.metaKey = cte.metaKey;
  121191. e.shiftKey = cte.shiftKey;
  121192. // forward touch preventDefaults
  121193. var self = this;
  121194. e.preventDefault = function() {
  121195. self.scrolling = false;
  121196. self.firstXY = null;
  121197. cte.preventDefault();
  121198. };
  121199. return e;
  121200. },
  121201. processTouches: function(inEvent, inFunction) {
  121202. var tl = inEvent.changedTouches;
  121203. this.currentTouchEvent = inEvent;
  121204. for (var i = 0, t; i < tl.length; i++) {
  121205. t = tl[i];
  121206. inFunction.call(this, this.touchToPointer(t));
  121207. }
  121208. },
  121209. // For single axis scrollers, determines whether the element should emit
  121210. // pointer events or behave as a scroller
  121211. shouldScroll: function(inEvent) {
  121212. if (this.firstXY) {
  121213. var ret;
  121214. var scrollAxis = inEvent.currentTarget._scrollType;
  121215. if (scrollAxis === 'none') {
  121216. // this element is a touch-action: none, should never scroll
  121217. ret = false;
  121218. } else if (scrollAxis === 'XY') {
  121219. // this element should always scroll
  121220. ret = true;
  121221. } else {
  121222. var t = inEvent.changedTouches[0];
  121223. // check the intended scroll axis, and other axis
  121224. var a = scrollAxis;
  121225. var oa = scrollAxis === 'Y' ? 'X' : 'Y';
  121226. var da = Math.abs(t['client' + a] - this.firstXY[a]);
  121227. var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
  121228. // if delta in the scroll axis > delta other axis, scroll instead of
  121229. // making events
  121230. ret = da >= doa;
  121231. }
  121232. this.firstXY = null;
  121233. return ret;
  121234. }
  121235. },
  121236. findTouch: function(inTL, inId) {
  121237. for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
  121238. if (t.identifier === inId) {
  121239. return true;
  121240. }
  121241. }
  121242. },
  121243. // In some instances, a touchstart can happen without a touchend. This
  121244. // leaves the pointermap in a broken state.
  121245. // Therefore, on every touchstart, we remove the touches that did not fire a
  121246. // touchend event.
  121247. // To keep state globally consistent, we fire a
  121248. // pointercancel for this "abandoned" touch
  121249. vacuumTouches: function(inEvent) {
  121250. var tl = inEvent.touches;
  121251. // pointermap.size should be < tl.length here, as the touchstart has not
  121252. // been processed yet.
  121253. if (pointermap$1.size >= tl.length) {
  121254. var d = [];
  121255. pointermap$1.forEach(function(value, key) {
  121256. // Never remove pointerId == 1, which is mouse.
  121257. // Touch identifiers are 2 smaller than their pointerId, which is the
  121258. // index in pointermap.
  121259. if (key !== 1 && !this.findTouch(tl, key - 2)) {
  121260. var p = value.out;
  121261. d.push(p);
  121262. }
  121263. }, this);
  121264. d.forEach(this.cancelOut, this);
  121265. }
  121266. },
  121267. touchstart: function(inEvent) {
  121268. this.vacuumTouches(inEvent);
  121269. this.setPrimaryTouch(inEvent.changedTouches[0]);
  121270. this.dedupSynthMouse(inEvent);
  121271. if (!this.scrolling) {
  121272. this.clickCount++;
  121273. this.processTouches(inEvent, this.overDown);
  121274. }
  121275. },
  121276. overDown: function(inPointer) {
  121277. pointermap$1.set(inPointer.pointerId, {
  121278. target: inPointer.target,
  121279. out: inPointer,
  121280. outTarget: inPointer.target
  121281. });
  121282. dispatcher.enterOver(inPointer);
  121283. dispatcher.down(inPointer);
  121284. },
  121285. touchmove: function(inEvent) {
  121286. if (!this.scrolling) {
  121287. if (this.shouldScroll(inEvent)) {
  121288. this.scrolling = true;
  121289. this.touchcancel(inEvent);
  121290. } else {
  121291. inEvent.preventDefault();
  121292. this.processTouches(inEvent, this.moveOverOut);
  121293. }
  121294. }
  121295. },
  121296. moveOverOut: function(inPointer) {
  121297. var event = inPointer;
  121298. var pointer = pointermap$1.get(event.pointerId);
  121299. // a finger drifted off the screen, ignore it
  121300. if (!pointer) {
  121301. return;
  121302. }
  121303. var outEvent = pointer.out;
  121304. var outTarget = pointer.outTarget;
  121305. dispatcher.move(event);
  121306. if (outEvent && outTarget !== event.target) {
  121307. outEvent.relatedTarget = event.target;
  121308. event.relatedTarget = outTarget;
  121309. // recover from retargeting by shadow
  121310. outEvent.target = outTarget;
  121311. if (event.target) {
  121312. dispatcher.leaveOut(outEvent);
  121313. dispatcher.enterOver(event);
  121314. } else {
  121315. // clean up case when finger leaves the screen
  121316. event.target = outTarget;
  121317. event.relatedTarget = null;
  121318. this.cancelOut(event);
  121319. }
  121320. }
  121321. pointer.out = event;
  121322. pointer.outTarget = event.target;
  121323. },
  121324. touchend: function(inEvent) {
  121325. this.dedupSynthMouse(inEvent);
  121326. this.processTouches(inEvent, this.upOut);
  121327. },
  121328. upOut: function(inPointer) {
  121329. if (!this.scrolling) {
  121330. dispatcher.up(inPointer);
  121331. dispatcher.leaveOut(inPointer);
  121332. }
  121333. this.cleanUpPointer(inPointer);
  121334. },
  121335. touchcancel: function(inEvent) {
  121336. this.processTouches(inEvent, this.cancelOut);
  121337. },
  121338. cancelOut: function(inPointer) {
  121339. dispatcher.cancel(inPointer);
  121340. dispatcher.leaveOut(inPointer);
  121341. this.cleanUpPointer(inPointer);
  121342. },
  121343. cleanUpPointer: function(inPointer) {
  121344. pointermap$1.delete(inPointer.pointerId);
  121345. this.removePrimaryPointer(inPointer);
  121346. },
  121347. // prevent synth mouse events from creating pointer events
  121348. dedupSynthMouse: function(inEvent) {
  121349. var lts = mouseEvents.lastTouches;
  121350. var t = inEvent.changedTouches[0];
  121351. // only the primary finger will synth mouse events
  121352. if (this.isPrimaryTouch(t)) {
  121353. // remember x/y of last touch
  121354. var lt = { x: t.clientX, y: t.clientY };
  121355. lts.push(lt);
  121356. var fn = (function(lts, lt) {
  121357. var i = lts.indexOf(lt);
  121358. if (i > -1) {
  121359. lts.splice(i, 1);
  121360. }
  121361. }).bind(null, lts, lt);
  121362. setTimeout(fn, DEDUP_TIMEOUT);
  121363. }
  121364. }
  121365. };
  121366. INSTALLER = new Installer(touchEvents.elementAdded, touchEvents.elementRemoved,
  121367. touchEvents.elementChanged, touchEvents);
  121368. var pointermap$2 = dispatcher.pointermap;
  121369. var HAS_BITMAP_TYPE = window.MSPointerEvent &&
  121370. typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
  121371. var msEvents = {
  121372. events: [
  121373. 'MSPointerDown',
  121374. 'MSPointerMove',
  121375. 'MSPointerUp',
  121376. 'MSPointerOut',
  121377. 'MSPointerOver',
  121378. 'MSPointerCancel',
  121379. 'MSGotPointerCapture',
  121380. 'MSLostPointerCapture'
  121381. ],
  121382. register: function(target) {
  121383. dispatcher.listen(target, this.events);
  121384. },
  121385. unregister: function(target) {
  121386. dispatcher.unlisten(target, this.events);
  121387. },
  121388. POINTER_TYPES: [
  121389. '',
  121390. 'unavailable',
  121391. 'touch',
  121392. 'pen',
  121393. 'mouse'
  121394. ],
  121395. prepareEvent: function(inEvent) {
  121396. var e = inEvent;
  121397. if (HAS_BITMAP_TYPE) {
  121398. e = dispatcher.cloneEvent(inEvent);
  121399. e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
  121400. }
  121401. return e;
  121402. },
  121403. cleanup: function(id) {
  121404. pointermap$2.delete(id);
  121405. },
  121406. MSPointerDown: function(inEvent) {
  121407. pointermap$2.set(inEvent.pointerId, inEvent);
  121408. var e = this.prepareEvent(inEvent);
  121409. dispatcher.down(e);
  121410. },
  121411. MSPointerMove: function(inEvent) {
  121412. var e = this.prepareEvent(inEvent);
  121413. dispatcher.move(e);
  121414. },
  121415. MSPointerUp: function(inEvent) {
  121416. var e = this.prepareEvent(inEvent);
  121417. dispatcher.up(e);
  121418. this.cleanup(inEvent.pointerId);
  121419. },
  121420. MSPointerOut: function(inEvent) {
  121421. var e = this.prepareEvent(inEvent);
  121422. dispatcher.leaveOut(e);
  121423. },
  121424. MSPointerOver: function(inEvent) {
  121425. var e = this.prepareEvent(inEvent);
  121426. dispatcher.enterOver(e);
  121427. },
  121428. MSPointerCancel: function(inEvent) {
  121429. var e = this.prepareEvent(inEvent);
  121430. dispatcher.cancel(e);
  121431. this.cleanup(inEvent.pointerId);
  121432. },
  121433. MSLostPointerCapture: function(inEvent) {
  121434. var e = dispatcher.makeEvent('lostpointercapture', inEvent);
  121435. dispatcher.dispatchEvent(e);
  121436. },
  121437. MSGotPointerCapture: function(inEvent) {
  121438. var e = dispatcher.makeEvent('gotpointercapture', inEvent);
  121439. dispatcher.dispatchEvent(e);
  121440. }
  121441. };
  121442. function applyPolyfill() {
  121443. // only activate if this platform does not have pointer events
  121444. if (!window.PointerEvent) {
  121445. window.PointerEvent = PointerEvent;
  121446. if (window.navigator.msPointerEnabled) {
  121447. var tp = window.navigator.msMaxTouchPoints;
  121448. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  121449. value: tp,
  121450. enumerable: true
  121451. });
  121452. dispatcher.registerSource('ms', msEvents);
  121453. } else {
  121454. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  121455. value: 0,
  121456. enumerable: true
  121457. });
  121458. dispatcher.registerSource('mouse', mouseEvents);
  121459. if (window.ontouchstart !== undefined) {
  121460. dispatcher.registerSource('touch', touchEvents);
  121461. }
  121462. }
  121463. dispatcher.register(document);
  121464. }
  121465. }
  121466. var n = window.navigator;
  121467. var s;
  121468. var r;
  121469. var h;
  121470. function assertActive(id) {
  121471. if (!dispatcher.pointermap.has(id)) {
  121472. var error = new Error('InvalidPointerId');
  121473. error.name = 'InvalidPointerId';
  121474. throw error;
  121475. }
  121476. }
  121477. function assertConnected(elem) {
  121478. var parent = elem.parentNode;
  121479. while (parent && parent !== elem.ownerDocument) {
  121480. parent = parent.parentNode;
  121481. }
  121482. if (!parent) {
  121483. var error = new Error('InvalidStateError');
  121484. error.name = 'InvalidStateError';
  121485. throw error;
  121486. }
  121487. }
  121488. function inActiveButtonState(id) {
  121489. var p = dispatcher.pointermap.get(id);
  121490. return p.buttons !== 0;
  121491. }
  121492. if (n.msPointerEnabled) {
  121493. s = function(pointerId) {
  121494. assertActive(pointerId);
  121495. assertConnected(this);
  121496. if (inActiveButtonState(pointerId)) {
  121497. dispatcher.setCapture(pointerId, this, true);
  121498. this.msSetPointerCapture(pointerId);
  121499. }
  121500. };
  121501. r = function(pointerId) {
  121502. assertActive(pointerId);
  121503. dispatcher.releaseCapture(pointerId, true);
  121504. this.msReleasePointerCapture(pointerId);
  121505. };
  121506. } else {
  121507. s = function setPointerCapture(pointerId) {
  121508. assertActive(pointerId);
  121509. assertConnected(this);
  121510. if (inActiveButtonState(pointerId)) {
  121511. dispatcher.setCapture(pointerId, this);
  121512. }
  121513. };
  121514. r = function releasePointerCapture(pointerId) {
  121515. assertActive(pointerId);
  121516. dispatcher.releaseCapture(pointerId);
  121517. };
  121518. }
  121519. h = function hasPointerCapture(pointerId) {
  121520. return !!dispatcher.captureInfo[pointerId];
  121521. };
  121522. function applyPolyfill$1() {
  121523. if (window.Element && !Element.prototype.setPointerCapture) {
  121524. Object.defineProperties(Element.prototype, {
  121525. 'setPointerCapture': {
  121526. value: s
  121527. },
  121528. 'releasePointerCapture': {
  121529. value: r
  121530. },
  121531. 'hasPointerCapture': {
  121532. value: h
  121533. }
  121534. });
  121535. }
  121536. }
  121537. applyAttributeStyles();
  121538. applyPolyfill();
  121539. applyPolyfill$1();
  121540. var pointerevents = {
  121541. dispatcher: dispatcher,
  121542. Installer: Installer,
  121543. PointerEvent: PointerEvent,
  121544. PointerMap: PointerMap,
  121545. targetFinding: targeting
  121546. };
  121547. return pointerevents;
  121548. }));
  121549. /***/ }),
  121550. /* 67 */
  121551. /***/ (function(module, exports, __webpack_require__) {
  121552. "use strict";
  121553. Object.defineProperty(exports, "__esModule", { value: true });
  121554. var defaultViewer_1 = __webpack_require__(8);
  121555. var mappers_1 = __webpack_require__(3);
  121556. var globals_1 = __webpack_require__(4);
  121557. /**
  121558. * Will attach an init function the the DOMContentLoaded event.
  121559. * The init function will be removed automatically after the event was triggered.
  121560. */
  121561. function initListeners() {
  121562. document.addEventListener("DOMContentLoaded", init);
  121563. function init(event) {
  121564. document.removeEventListener("DOMContentLoaded", init);
  121565. if (globals_1.viewerGlobals.disableInit)
  121566. return;
  121567. InitTags();
  121568. }
  121569. }
  121570. exports.initListeners = initListeners;
  121571. /**
  121572. * Select all HTML tags on the page that match the selector and initialize a viewer
  121573. *
  121574. * @param selector the selector to initialize the viewer on (default is 'babylon')
  121575. */
  121576. function InitTags(selector) {
  121577. if (selector === void 0) { selector = 'babylon'; }
  121578. var elements = document.querySelectorAll(selector);
  121579. for (var i = 0; i < elements.length; ++i) {
  121580. var element = elements.item(i);
  121581. // get the html configuration
  121582. var configMapper = mappers_1.mapperManager.getMapper('dom');
  121583. var config = configMapper.map(element);
  121584. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  121585. }
  121586. }
  121587. exports.InitTags = InitTags;
  121588. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5pdGlhbGl6ZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5pdGlhbGl6ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx3REFBdUQ7QUFDdkQsbURBQXdEO0FBQ3hELG1EQUF3RDtBQUd4RDs7O0dBR0c7QUFDSDtJQUNJLFFBQVEsQ0FBQyxnQkFBZ0IsQ0FBQyxrQkFBa0IsRUFBRSxJQUFJLENBQUMsQ0FBQztJQUNwRCxjQUFjLEtBQUs7UUFDZixRQUFRLENBQUMsbUJBQW1CLENBQUMsa0JBQWtCLEVBQUUsSUFBSSxDQUFDLENBQUM7UUFDdkQsSUFBSSx1QkFBYSxDQUFDLFdBQVc7WUFBRSxPQUFPO1FBQ3RDLFFBQVEsRUFBRSxDQUFDO0lBQ2YsQ0FBQztBQUNMLENBQUM7QUFQRCxzQ0FPQztBQUVEOzs7O0dBSUc7QUFDSCxrQkFBeUIsUUFBNEI7SUFBNUIseUJBQUEsRUFBQSxvQkFBNEI7SUFDakQsSUFBSSxRQUFRLEdBQUcsUUFBUSxDQUFDLGdCQUFnQixDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQ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